When to use single quotes, double quotes, and back ticks in MySQL


I am trying to learn the best way to write queries. I also understand the importance of being consistent. Until now, I have randomly used single quotes, double quotes, and back ticks without any real thought.



Example:



Also, in the above example, consider that "table," "col[n]," and "val[n]" may be variables.



What is the standard for this? What do you do?



I've been reading answers to similar questions on here for about 20 minutes, but it seems like there is no definitive answer to this question.



Backticks are to be used for table and column identifiers, but are only necessary when the identifier is a MySQL reserved keyword, or when the identifier contains whitespace characters or characters beyond a limited set (see below) It is often recommended to avoid using reserved keywords as column or table identifiers when possible, avoiding the quoting issue.



Single quotes should be used for string values like in the VALUES() list. Double quotes are supported by MySQL for string values as well, but single quotes are more widely accepted by other RDBMS, so it is a good habit to use single quotes instead of double.



MySQL also expects DATE and DATETIME literal values to be single-quoted as strings like '2001-01-01 00:00:00'. Consult the Date and Time Literals documentation for more details, in particular alternatives to using the hyphen - as a segment delimiter in date strings.



So using your example, I would double-quote the PHP string and use single quotes on the values 'val1', 'val2'. NULL is a MySQL keyword, and a special (non)-value, and is therefore unquoted.



None of these table or column identifiers are reserved words or make use of characters requiring quoting, but I've quoted them anyway with backticks (more on this later...).



Functions native to the RDBMS (for example, NOW() in MySQL) should not be quoted, although their arguments are subject to the same string or identifier quoting rules already mentioned.



The quoting patterns for variables do not change, although if you intend to interpolate the variables directly in a string, it must be double-quoted in PHP. Just make sure that you have properly escaped the variables for use in SQL. (It is recommended to use an API supporting prepared statements instead, as protection against SQL injection).



When working with prepared statements, consult the documentation to determine whether or not the statement's placeholders must be quoted. The most popular APIs available in PHP, PDO and MySQLi, expect unquoted placeholders, as do most prepared statement APIs in other languages:



According to MySQL documentation, you do not need to quote (backtick) identifiers using the following character set:



ASCII: [0-9,a-z,A-Z$_] (basic Latin letters, digits 0-9, dollar, underscore)



You can use characters beyond that set as table or column identifiers, including whitespace for example, but then you must quote (backtick) them.



There are two types of quotes in MySQL:



And then there is " which is a special case. It could be used for one of above-mentioned purposes at a time depending on MySQL server's sql_mode:



The query will select the string literal "column" where column foo is equal to string "bar"



The query will select the column column where column foo is equal to column bar



(There are good answers above regarding the SQL nature of your question, but this may also be relevant if you are new to PHP.)



Perhaps it is important to mention that PHP handles single and double quoted strings differently...



Single-quoted strings are 'literals' and are pretty much WYSIWYG strings. Double-quoted strings are interpreted by PHP for possible variable-substitution (backticks in PHP are not exactly strings; they execute a command in the shell and return the result).



Examples:



Backticks are generally used to indicate an identifier and as well be safe from accidentally using the Reserved Keywords.



For example:



Here the backticks will help the server to understand that the database is in fact the name of the database, not the database identifier.



Same can be done for the table names and field names. This is a very good habit if you wrap your database identifier with backticks.



Check this answer to understand more about backticks.



Now about Double quotes & Single Quotes (Michael has already mentioned that).



But, to define a value you have to use either single or double quotes. Lets see another example.



Here I have deliberately forgotten to wrap the title1 with quotes. Now the server will take the title1 as a column name (i.e. an identifier). So, to indicate that it's a value you have to use either double or single quotes.



Now, in combination with PHP, double quotes and single quotes make your query writing time much easier. Let's see a modified version of the query in your question.



Now, using double quotes in the PHP, you will make the variables $val1, and $val2 to use their values thus creating a perfectly valid query. Like



will make



Basically in Mysql, There are these kinds of identifier are used in query ` ," ,' and () .



" or ' use for enclosing the string like values "26-01-2014 00:00:00" or '26-01-2014 00:00:00' . These identifier use only for string not aggregate function like now() or sum ,max etc.



` use for enclosing table or table column e.g. select column_name from table_name where id='2'



() are use only for just enclose parts of query e.g. select column_name from table_name where (id='2' and gender='male') or name='rakesh' .



The string literals in MySQL and PHP are the same.



A string is a sequence of bytes or characters, enclosed within either
single quote (“'”) or double quote (“"”) characters.



So if your string contains single quotes, then you could use double quotes to quote the string, or if it contains double quotes, then you could use single quotes to quote the string. But if your string contains both single quotes and double quotes, you need to escape the one that used to quote the string.



Mostly, we use single quotes for an SQL string value, so we need to use double quotes for a PHP string.



And you could use a variable in PHP's double-quoted string:



But if $val1 or $val2 contains single quotes, that will make your SQL be wrong. So you need to escape it before it is used in sql; that is what mysql_real_escape_string is for. (Although a prepared statement is better.)



In combination of PHP and MySQL, double quotes and single quotes make your query-writing time so much easier.



Now, suppose you are using a direct post variable into the MySQL query then, use it this way:



This is the best practice for using PHP variables into MySQL.



Single quotes should be used for string values like in the VALUES() list.



Backticks are generally used to indicate an identifier and as well be safe from accidentally using the reserved keywords.



In combination of PHP and MySQL, double quotes and single quotes make your query writing time so much easier.



If table cols and values are variables then there are two ways:



With double quotes "" the complete query:



Or



With single quotes '':



Use back ticks `` when a column/value name is similar to a MySQL reserved keyword.



Note: If you are denoting a column name with a table name then use back ticks like this:



`table_name`. `column_name` <-- Note: exclude . from back ticks.



There has been many helpful answers here, generally culminating into two points.



AND as @MichaelBerkowski said



Backticks are to be used for table and column identifiers, but are
only necessary when the identifier is a MySQL reserved keyword, or
when the identifier contains whitespace characters or characters
beyond a limited set (see below) It is often recommended to avoid
using reserved keywords as column or table identifiers when possible,
avoiding the quoting issue.



There is a case though where an identifier can neither be a reserved keyword or contain whitespace or characters beyond limited set but necessarily require backticks around them.



EXAMPLE



123E10 is a valid identifier name but also a valid INTEGER literal.



[Without going into detail how you would get such an identifier name], Suppose I want to create a temporary table named 123456e6.



No ERROR on backticks.



ERROR when not using backticks.



However, 123451a6 is a perfectly fine identifier name (without back ticks).



This is completely because 1234156e6 is also an exponential number.



Besides all of the (well-explained) answers, there hasn't been the following mentioned and I visit this Q&A quite often.



In a nutshell; MySQL thinks you want to do math on its own table/column and interprets hyphens such as "e-mail" as e minus mail.



Disclaimer: So I thought I would add this as an "FYI" type of answer for those who are completely new to working with databases and who may not understand the technical terms described already.




Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).


Would you like to answer one of these unanswered questions instead?

Popular posts from this blog

The Dalles, Oregon

眉山市

清晰法令