When to use single quotes, double quotes, and backticks in MySQL

后端 未结 13 861
一个人的身影
一个人的身影 2021-01-26 10:55

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 backt

相关标签:
13条回答
  • 2021-01-26 11:36

    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.

    0 讨论(0)
  • 2021-01-26 11:37

    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.

    $query = "INSERT INTO table (id, col1, col2) VALUES (NULL, 'val1', 'val2')";
    

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

    $query = "INSERT INTO table (id, col1, col2) VALUES (NULL, '$val1', '$val2')";
    

    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.)

    0 讨论(0)
  • 2021-01-26 11:39

    SQL servers and MySQL, PostgreySQL, Oracle don't understand double quotes("). Thus your query should be free from double quotes(") and should only use single quotes(').

    Back-trip(`) is optional to use in SQL and is used for table name, db name and column names.

    If you are trying to write query in your back-end to call MySQL then you can use double quote(") or single quotes(') to assign query to a variable like:

    let query = "select id, name from accounts";
    //Or
    let query = 'select id, name from accounts';
    

    If ther's a where statement in your query and/or trying to insert a value and/or an update of value which is string use single quote(') for these values like:

    let querySelect = "select id, name from accounts where name = 'John'";
    let queryUpdate = "update accounts set name = 'John' where id = 8";
    let queryInsert = "insert into accounts(name) values('John')";
    
    //Please not that double quotes are only to be used in assigning string to our variable not in the query
    //All these below will generate error
    
    let querySelect = 'select id, name from accounts where name = "John"';
    let queryUpdate = 'update accounts set name = "John" where id = 8';
    let queryInsert = 'insert into accounts(name) values("John")';
    
    //As MySQL or any SQL doesn't understand double quotes("), these all will generate error.
    

    If you want to stay out of this confusion when to use double quotes(") and single quotes('), would recommend to stick with single quotes(') this will include backslash() like:

    let query = 'select is, name from accounts where name = \'John\'';
    

    Problem with double(") or single(') quotes arise when we had to assign some value dynamic and perform some string concatenation like:

    let query = "select id, name from accounts where name = " + fName + " " + lName;
    //This will generate error as it must be like name = 'John Smith' for SQL
    //However our statement made it like name = John Smith
    
    //In order to resolve such errors use
    let query = "select id, name from accounts where name = '" + fName + " " + lName + "'";
    
    //Or using backslash(\)
    let query = 'select id, name from accounts where name = \'' + fName + ' ' + lName + '\'';
    

    If need further clearance do follow quotes in JavaScript

    0 讨论(0)
  • 2021-01-26 11:40

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

    For example:

    Use `database`;
    

    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.

    INSERT INTO `tablename` (`id, `title`) VALUES ( NULL, title1);
    

    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.

    INSERT INTO `tablename` (`id, `title`) VALUES ( NULL, 'title1');
    

    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.

    $query = "INSERT INTO `table` (`id`, `col1`, `col2`) VALUES (NULL, '$val1', '$val2')";
    

    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

    $val1 = "my value 1";
    $val2 = "my value 2";
    $query = "INSERT INTO `table` (`id`, `col1`, `col2`) VALUES (NULL, '$val1', '$val2')";
    

    will make

    INSERT INTO `table` (`id`, `col1`, `col2`) VALUES (NULL, 'my value 1', 'my value 2')
    
    0 讨论(0)
  • 2021-01-26 11:40

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

    With double quotes "" the complete query:

    $query = "INSERT INTO $table_name (id, $col1, $col2)
                     VALUES (NULL, '$val1', '$val2')";
    

    Or

     $query = "INSERT INTO ".$table_name." (id, ".$col1.", ".$col2.")
                   VALUES (NULL, '".$val1."', '".$val2."')";
    

    With single quotes '':

    $query = 'INSERT INTO '.$table_name.' (id, '.$col1.', '.$col2.')
                 VALUES (NULL, '.$val1.', '.$val2.')';
    

    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.

    0 讨论(0)
  • 2021-01-26 11:43

    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.

    Backtick (`)
    table & column ───────┬─────┬──┬──┬──┬────┬──┬────┬──┬────┬──┬───────┐
                          ↓     ↓  ↓  ↓  ↓    ↓  ↓    ↓  ↓    ↓  ↓       ↓
    $query = "INSERT INTO `table` (`id`, `col1`, `col2`, `date`, `updated`) 
                           VALUES (NULL, 'val1', 'val2', '2001-01-01', NOW())";
                                   ↑↑↑↑  ↑    ↑  ↑    ↑  ↑          ↑  ↑↑↑↑↑ 
    Unquoted keyword          ─────┴┴┴┘  │    │  │    │  │          │  │││││
    Single-quoted (') strings ───────────┴────┴──┴────┘  │          │  │││││
    Single-quoted (') DATE    ───────────────────────────┴──────────┘  │││││
    Unquoted function         ─────────────────────────────────────────┴┴┴┴┘    
    

    Variable interpolation

    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).

    // Same thing with some variable replacements
    // Here, a variable table name $table is backtick-quoted, and variables
    // in the VALUES list are single-quoted 
    $query = "INSERT INTO `$table` (`id`, `col1`, `col2`, `date`) VALUES (NULL, '$val1', '$val2', '$date')";
    

    Prepared statements

    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:

    // PDO example with named parameters, unquoted
    $query = "INSERT INTO `table` (`id`, `col1`, `col2`, `date`) VALUES (:id, :col1, :col2, :date)";
    
    // MySQLi example with ? parameters, unquoted
    $query = "INSERT INTO `table` (`id`, `col1`, `col2`, `date`) VALUES (?, ?, ?, ?)";
    

    Characters requring backtick quoting in identifiers:

    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.

    Also, although numbers are valid characters for identifiers, identifiers cannot consist solely of numbers. If they do they must be wrapped in backticks.

    0 讨论(0)
提交回复
热议问题