Tuesday, 30 July 2019

How to Retain the Backslash when Escaping Quotes in MySQL – QUOTE()

Using a backslash to escape single quotes is a commonly used technique to ensure that the single quotes don’t interfere with MySQL‘s handling of the full string.
Single quotes are used to surround a string, so a single quote within the string itself could cause havoc if it isn’t properly escaped. Simply inserting a backslash immediately before the quote mark ensures that MySQL doesn’t terminate the string prematurely.
However, there may be occasions where you want the backslash to remain. For example, you might intend to use the string in an SQL statement, and therefore, you want it to be properly escaped first.
This is where the QUOTE() function comes in.
The MySQL QUOTE() function quotes a string to produce a result that can be used as a properly escaped data value in an SQL statement. The string is returned enclosed by single quotation marks and with each instance of backslash (\), single quote ('), ASCII NUL, and Control+Z preceded by a backslash.

Syntax of the QUOTE() Function

Here’s how the syntax goes:
QUOTE(str)
Where str is the (already) escaped string.

Example

An example probably explains this better than my explanation:
SELECT QUOTE('Don\'t!') AS Result;
Result:
+-----------+
| Result    |
+-----------+
| 'Don\'t!' |
+-----------+
At first glance, you might be thinking “but nothing happened – the result is exactly the same as the argument”. However, that’s exactly why this function is useful. If we hadn’t used the QUOTE() function, here’s what would’ve happened:
SELECT 'Don\'t!' AS Result;
Result:
+--------+
| Result |
+--------+
| Don't! |
+--------+
So by using the QUOTE() function, we retain the single quotes and the backslash.
Of course, in many cases, this is exactly what you want. In many cases, the backslash and surrounding quotes should be removed. But there may be some cases where you want exactly what the QUOTE() function does for you.

The Alternative

The QUOTE() function saves you from having to do something like this:
SELECT '''Don\\\'t!''' AS Result;
Result:
+-----------+
| Result    |
+-----------+
| 'Don\'t!' |
+-----------+
So it saves us from having to use three single quotes for every single quote, and three backslashes for every single backslash.

0 comments:

Post a Comment