A string literal is a piece of text written inside your SQL, such as 'Pune'.
Single quotes
Standard SQL uses single quotes for text:
SELECT 'Hello' AS greeting;
+----------+
| greeting |
+----------+
| Hello |
+----------+
1 row in set
MySQL also accepts double quotes for text by default, but that is not portable and breaks if ANSI_QUOTES is on. Use single quotes.
An apostrophe inside text
Two ways to put a single quote inside a single-quoted string:
SELECT 'It''s fine' AS doubled_quote, 'It\'s fine' AS backslash_quote;
+---------------+-----------------+
| doubled_quote | backslash_quote |
+---------------+-----------------+
| It's fine | It's fine |
+---------------+-----------------+
1 row in set
Doubling the quote ('') is the standard way. The backslash form is MySQL-specific.
Escape sequences
Inside a string, a backslash starts an escape sequence (a special code):
| Sequence | Meaning |
|---|---|
\' | single quote |
\\ | a backslash |
\n | new line |
\t | tab |
\0 | NUL character |
\% and \_ | literal percent and underscore (used with LIKE) |
SELECT 'line one\nline two' AS two_lines, 'C:\\temp' AS path;
+-------------------+---------+
| two_lines | path |
+-------------------+---------+
| line one
line two | C:\temp |
+-------------------+---------+
1 row in set
The \n made a real new line and \\ became a single backslash.
NO_BACKSLASH_ESCAPES
NO_BACKSLASH_ESCAPES turns the backslash into an ordinary character, which is what standard SQL does. Code that depends on backslash escapes breaks in that mode, so do not mix the two styles in one project.Joining adjacent strings
Two literals next to each other are joined:
SELECT 'Hello, ' 'world' AS joined;
+--------------+
| joined |
+--------------+
| Hello, world |
+--------------+
1 row in set
That is occasionally useful in long text, and is a classic way to lose a comma by accident, so be careful.
Hexadecimal and binary literals
SELECT 0x4D7953514C AS hex_value, CAST(0x4D7953514C AS CHAR) AS as_text, b'1010' + 0 AS binary_value;
+-----------+---------+--------------+
| hex_value | as_text | binary_value |
+-----------+---------+--------------+
| MySQL | MySQL | 10 |
+-----------+---------+--------------+
1 row in set
Escaping is not a security tool
Putting a user’s text into an SQL string by hand, even with escaping, is how SQL injection happens. The correct protection is prepared statements, where the SQL and the data travel separately (Prepared Statements and SQL Injection). Learn quoting so you can read SQL, and use parameters when your code has user input.
Mixing quote types
'It's fine' fails: MySQL thinks the string ends at the apostrophe in “It’s”. Double it ('It''s fine') or escape it.