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










534














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:



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


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.










share|improve this question



















  • 6




    Note that this is a very MySQL specific question. SQL in general (i.e. ISO/ANSI SQL) has a different set of quotes: double quotes are for delimited identifiers, e.g. "tablename", and single quotes are for literals, e.g. 'this is a some text'. Back-ticks are never used in standard SQL. (If you need to include a double quote in an identifier, type it twice as "odd""tablename". Similarly, double single quotes in literals, like 'Conan O''Brien'.)
    – jarlh
    Nov 25 '16 at 9:02
















534














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:



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


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.










share|improve this question



















  • 6




    Note that this is a very MySQL specific question. SQL in general (i.e. ISO/ANSI SQL) has a different set of quotes: double quotes are for delimited identifiers, e.g. "tablename", and single quotes are for literals, e.g. 'this is a some text'. Back-ticks are never used in standard SQL. (If you need to include a double quote in an identifier, type it twice as "odd""tablename". Similarly, double single quotes in literals, like 'Conan O''Brien'.)
    – jarlh
    Nov 25 '16 at 9:02














534












534








534


155





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:



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


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.










share|improve this question















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:



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


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.







mysql sql quotes






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 23 '18 at 8:46







user8226878

















asked Jul 4 '12 at 1:53









Nate

8,7562386168




8,7562386168







  • 6




    Note that this is a very MySQL specific question. SQL in general (i.e. ISO/ANSI SQL) has a different set of quotes: double quotes are for delimited identifiers, e.g. "tablename", and single quotes are for literals, e.g. 'this is a some text'. Back-ticks are never used in standard SQL. (If you need to include a double quote in an identifier, type it twice as "odd""tablename". Similarly, double single quotes in literals, like 'Conan O''Brien'.)
    – jarlh
    Nov 25 '16 at 9:02













  • 6




    Note that this is a very MySQL specific question. SQL in general (i.e. ISO/ANSI SQL) has a different set of quotes: double quotes are for delimited identifiers, e.g. "tablename", and single quotes are for literals, e.g. 'this is a some text'. Back-ticks are never used in standard SQL. (If you need to include a double quote in an identifier, type it twice as "odd""tablename". Similarly, double single quotes in literals, like 'Conan O''Brien'.)
    – jarlh
    Nov 25 '16 at 9:02








6




6




Note that this is a very MySQL specific question. SQL in general (i.e. ISO/ANSI SQL) has a different set of quotes: double quotes are for delimited identifiers, e.g. "tablename", and single quotes are for literals, e.g. 'this is a some text'. Back-ticks are never used in standard SQL. (If you need to include a double quote in an identifier, type it twice as "odd""tablename". Similarly, double single quotes in literals, like 'Conan O''Brien'.)
– jarlh
Nov 25 '16 at 9:02





Note that this is a very MySQL specific question. SQL in general (i.e. ISO/ANSI SQL) has a different set of quotes: double quotes are for delimited identifiers, e.g. "tablename", and single quotes are for literals, e.g. 'this is a some text'. Back-ticks are never used in standard SQL. (If you need to include a double quote in an identifier, type it twice as "odd""tablename". Similarly, double single quotes in literals, like 'Conan O''Brien'.)
– jarlh
Nov 25 '16 at 9:02













12 Answers
12






active

oldest

votes


















524














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.






share|improve this answer


















  • 34




    "but single quotes are more widely accepted by other RDBMS" - using single quotes for string literals is defined (and required) by the SQL standard
    – a_horse_with_no_name
    Jul 14 '14 at 8:57










  • @a_horse_with_no_name almost no one use ANSI MySQL ('|' for string concat - really?)
    – Good Person
    Dec 7 '15 at 23:31






  • 1




    this isn't true: "MySQL also expects DATE and DATETIME literal values to be single-quoted as strings like '2001-01-01 00:00:00'"
    – Kick_the_BUCKET
    Apr 12 '16 at 14:59






  • 1




    @evilReiko MySQL docs don't seem to address alias quoting clearly. It will accept single, double, or backtick for aliases but that may be affected by different ANSI SQL modes. I'm not sure what the SQL spec requires for alias quotes -- Personal preference: for consistency I quote them the same as column identifiers - that is, I either backtick them if needed, or leave them unquoted if not. I don't use single or double quotes on aliases.
    – Michael Berkowski
    Aug 16 '17 at 15:36






  • 1




    @GuneyOzsan Yes, very vulnerable. Never ever use a variable for a table name unless it has been validated against a list of acceptable table names - create an array of permissible names and check the variable matches something in the list to make it safe to use. Otherwise you cannot safely escape a table name variable for use.
    – Michael Berkowski
    Oct 27 '18 at 1:55


















102














There are two types of quotes in MySQL:




  1. ' for enclosing string literals


  2. ` for enclosing identifiers such as table and column names

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:




  1. By default the " character can be used to enclose string literals just like '

  2. In ANSI_QUOTES mode the " character can be used to enclose identifiers just like `

The following query will produce different results (or errors) depending on SQL mode:



SELECT "column" FROM table WHERE foo = "bar"


ANSI_QUOTES disabled



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



ANSI_QUOTES enabled



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



When to use what



  • I suggest that you avoid using " so that your code becomes independent of SQL modes

  • Always quote identifiers since it is a good practice (quite a few questions on SO discuss this)





share|improve this answer






























    29














    (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:



    $foo = "bar";
    echo 'there is a $foo'; // There is a $foo
    echo "there is a $foo"; // There is a bar
    echo `ls -l`; // ... a directory list





    share|improve this answer






























      19














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





      share|improve this answer






























        12














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



        1. " 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.


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


        3. () 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' .






        share|improve this answer






























          11














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






          share|improve this answer






























            10














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



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


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



            $query = "INSERT INTO `table` (`id`, `name`, `email`) VALUES (' ".$_POST['id']." ', ' ".$_POST['name']." ', ' ".$_POST['email']." ')";


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






            share|improve this answer






















            • Therefore double quotes are flexible but can't be used as identifiers.
              – rhavendc
              May 31 '16 at 8:39










            • Please never ever directly use unescaped user input in your query!
              – jankal
              Dec 27 '16 at 9:13










            • @jankal It's just example.I specified that if you are using direct user input then n then...........
              – vipul sorathiya
              Dec 28 '16 at 8:01










            • @vipulsorathiya Please specify in your answer that POST variables should be escaped. You're now pointing at using them direct in your query. Bad for beginners who try this...
              – RFLdev
              Aug 16 '17 at 12:18


















            9














            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.






            share|improve this answer






























              9














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



              1. BACKTICKS(`) are used around identifier names.

              2. SINGLE QUOTES(') are used around values.

              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.



              DB [XXX]> create temporary table `123456e6` (`id` char (8));
              Query OK, 0 rows affected (0.03 sec)


              ERROR when not using backticks.



              DB [XXX]> create temporary table 123451e6 (`id` char (8));
              ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '123451e6 (`id` char (8))' at line 1


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



              DB [XXX]> create temporary table 123451a6 (`id` char (8));
              Query OK, 0 rows affected (0.03 sec)


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






              share|improve this answer






























                7














                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.






                share|improve this answer






























                  2














                  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.






                  share|improve this answer




























                    0














                    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






                    share|improve this answer



















                      protected by Samuel Liew Oct 5 '15 at 8:58



                      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?














                      12 Answers
                      12






                      active

                      oldest

                      votes








                      12 Answers
                      12






                      active

                      oldest

                      votes









                      active

                      oldest

                      votes






                      active

                      oldest

                      votes









                      524














                      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.






                      share|improve this answer


















                      • 34




                        "but single quotes are more widely accepted by other RDBMS" - using single quotes for string literals is defined (and required) by the SQL standard
                        – a_horse_with_no_name
                        Jul 14 '14 at 8:57










                      • @a_horse_with_no_name almost no one use ANSI MySQL ('|' for string concat - really?)
                        – Good Person
                        Dec 7 '15 at 23:31






                      • 1




                        this isn't true: "MySQL also expects DATE and DATETIME literal values to be single-quoted as strings like '2001-01-01 00:00:00'"
                        – Kick_the_BUCKET
                        Apr 12 '16 at 14:59






                      • 1




                        @evilReiko MySQL docs don't seem to address alias quoting clearly. It will accept single, double, or backtick for aliases but that may be affected by different ANSI SQL modes. I'm not sure what the SQL spec requires for alias quotes -- Personal preference: for consistency I quote them the same as column identifiers - that is, I either backtick them if needed, or leave them unquoted if not. I don't use single or double quotes on aliases.
                        – Michael Berkowski
                        Aug 16 '17 at 15:36






                      • 1




                        @GuneyOzsan Yes, very vulnerable. Never ever use a variable for a table name unless it has been validated against a list of acceptable table names - create an array of permissible names and check the variable matches something in the list to make it safe to use. Otherwise you cannot safely escape a table name variable for use.
                        – Michael Berkowski
                        Oct 27 '18 at 1:55















                      524














                      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.






                      share|improve this answer


















                      • 34




                        "but single quotes are more widely accepted by other RDBMS" - using single quotes for string literals is defined (and required) by the SQL standard
                        – a_horse_with_no_name
                        Jul 14 '14 at 8:57










                      • @a_horse_with_no_name almost no one use ANSI MySQL ('|' for string concat - really?)
                        – Good Person
                        Dec 7 '15 at 23:31






                      • 1




                        this isn't true: "MySQL also expects DATE and DATETIME literal values to be single-quoted as strings like '2001-01-01 00:00:00'"
                        – Kick_the_BUCKET
                        Apr 12 '16 at 14:59






                      • 1




                        @evilReiko MySQL docs don't seem to address alias quoting clearly. It will accept single, double, or backtick for aliases but that may be affected by different ANSI SQL modes. I'm not sure what the SQL spec requires for alias quotes -- Personal preference: for consistency I quote them the same as column identifiers - that is, I either backtick them if needed, or leave them unquoted if not. I don't use single or double quotes on aliases.
                        – Michael Berkowski
                        Aug 16 '17 at 15:36






                      • 1




                        @GuneyOzsan Yes, very vulnerable. Never ever use a variable for a table name unless it has been validated against a list of acceptable table names - create an array of permissible names and check the variable matches something in the list to make it safe to use. Otherwise you cannot safely escape a table name variable for use.
                        – Michael Berkowski
                        Oct 27 '18 at 1:55













                      524












                      524








                      524






                      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.






                      share|improve this answer














                      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.







                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited Aug 20 '17 at 5:34









                      Nisse Engström

                      4,10892034




                      4,10892034










                      answered Jul 4 '12 at 1:57









                      Michael Berkowski

                      223k34374342




                      223k34374342







                      • 34




                        "but single quotes are more widely accepted by other RDBMS" - using single quotes for string literals is defined (and required) by the SQL standard
                        – a_horse_with_no_name
                        Jul 14 '14 at 8:57










                      • @a_horse_with_no_name almost no one use ANSI MySQL ('|' for string concat - really?)
                        – Good Person
                        Dec 7 '15 at 23:31






                      • 1




                        this isn't true: "MySQL also expects DATE and DATETIME literal values to be single-quoted as strings like '2001-01-01 00:00:00'"
                        – Kick_the_BUCKET
                        Apr 12 '16 at 14:59






                      • 1




                        @evilReiko MySQL docs don't seem to address alias quoting clearly. It will accept single, double, or backtick for aliases but that may be affected by different ANSI SQL modes. I'm not sure what the SQL spec requires for alias quotes -- Personal preference: for consistency I quote them the same as column identifiers - that is, I either backtick them if needed, or leave them unquoted if not. I don't use single or double quotes on aliases.
                        – Michael Berkowski
                        Aug 16 '17 at 15:36






                      • 1




                        @GuneyOzsan Yes, very vulnerable. Never ever use a variable for a table name unless it has been validated against a list of acceptable table names - create an array of permissible names and check the variable matches something in the list to make it safe to use. Otherwise you cannot safely escape a table name variable for use.
                        – Michael Berkowski
                        Oct 27 '18 at 1:55












                      • 34




                        "but single quotes are more widely accepted by other RDBMS" - using single quotes for string literals is defined (and required) by the SQL standard
                        – a_horse_with_no_name
                        Jul 14 '14 at 8:57










                      • @a_horse_with_no_name almost no one use ANSI MySQL ('|' for string concat - really?)
                        – Good Person
                        Dec 7 '15 at 23:31






                      • 1




                        this isn't true: "MySQL also expects DATE and DATETIME literal values to be single-quoted as strings like '2001-01-01 00:00:00'"
                        – Kick_the_BUCKET
                        Apr 12 '16 at 14:59






                      • 1




                        @evilReiko MySQL docs don't seem to address alias quoting clearly. It will accept single, double, or backtick for aliases but that may be affected by different ANSI SQL modes. I'm not sure what the SQL spec requires for alias quotes -- Personal preference: for consistency I quote them the same as column identifiers - that is, I either backtick them if needed, or leave them unquoted if not. I don't use single or double quotes on aliases.
                        – Michael Berkowski
                        Aug 16 '17 at 15:36






                      • 1




                        @GuneyOzsan Yes, very vulnerable. Never ever use a variable for a table name unless it has been validated against a list of acceptable table names - create an array of permissible names and check the variable matches something in the list to make it safe to use. Otherwise you cannot safely escape a table name variable for use.
                        – Michael Berkowski
                        Oct 27 '18 at 1:55







                      34




                      34




                      "but single quotes are more widely accepted by other RDBMS" - using single quotes for string literals is defined (and required) by the SQL standard
                      – a_horse_with_no_name
                      Jul 14 '14 at 8:57




                      "but single quotes are more widely accepted by other RDBMS" - using single quotes for string literals is defined (and required) by the SQL standard
                      – a_horse_with_no_name
                      Jul 14 '14 at 8:57












                      @a_horse_with_no_name almost no one use ANSI MySQL ('|' for string concat - really?)
                      – Good Person
                      Dec 7 '15 at 23:31




                      @a_horse_with_no_name almost no one use ANSI MySQL ('|' for string concat - really?)
                      – Good Person
                      Dec 7 '15 at 23:31




                      1




                      1




                      this isn't true: "MySQL also expects DATE and DATETIME literal values to be single-quoted as strings like '2001-01-01 00:00:00'"
                      – Kick_the_BUCKET
                      Apr 12 '16 at 14:59




                      this isn't true: "MySQL also expects DATE and DATETIME literal values to be single-quoted as strings like '2001-01-01 00:00:00'"
                      – Kick_the_BUCKET
                      Apr 12 '16 at 14:59




                      1




                      1




                      @evilReiko MySQL docs don't seem to address alias quoting clearly. It will accept single, double, or backtick for aliases but that may be affected by different ANSI SQL modes. I'm not sure what the SQL spec requires for alias quotes -- Personal preference: for consistency I quote them the same as column identifiers - that is, I either backtick them if needed, or leave them unquoted if not. I don't use single or double quotes on aliases.
                      – Michael Berkowski
                      Aug 16 '17 at 15:36




                      @evilReiko MySQL docs don't seem to address alias quoting clearly. It will accept single, double, or backtick for aliases but that may be affected by different ANSI SQL modes. I'm not sure what the SQL spec requires for alias quotes -- Personal preference: for consistency I quote them the same as column identifiers - that is, I either backtick them if needed, or leave them unquoted if not. I don't use single or double quotes on aliases.
                      – Michael Berkowski
                      Aug 16 '17 at 15:36




                      1




                      1




                      @GuneyOzsan Yes, very vulnerable. Never ever use a variable for a table name unless it has been validated against a list of acceptable table names - create an array of permissible names and check the variable matches something in the list to make it safe to use. Otherwise you cannot safely escape a table name variable for use.
                      – Michael Berkowski
                      Oct 27 '18 at 1:55




                      @GuneyOzsan Yes, very vulnerable. Never ever use a variable for a table name unless it has been validated against a list of acceptable table names - create an array of permissible names and check the variable matches something in the list to make it safe to use. Otherwise you cannot safely escape a table name variable for use.
                      – Michael Berkowski
                      Oct 27 '18 at 1:55













                      102














                      There are two types of quotes in MySQL:




                      1. ' for enclosing string literals


                      2. ` for enclosing identifiers such as table and column names

                      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:




                      1. By default the " character can be used to enclose string literals just like '

                      2. In ANSI_QUOTES mode the " character can be used to enclose identifiers just like `

                      The following query will produce different results (or errors) depending on SQL mode:



                      SELECT "column" FROM table WHERE foo = "bar"


                      ANSI_QUOTES disabled



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



                      ANSI_QUOTES enabled



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



                      When to use what



                      • I suggest that you avoid using " so that your code becomes independent of SQL modes

                      • Always quote identifiers since it is a good practice (quite a few questions on SO discuss this)





                      share|improve this answer



























                        102














                        There are two types of quotes in MySQL:




                        1. ' for enclosing string literals


                        2. ` for enclosing identifiers such as table and column names

                        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:




                        1. By default the " character can be used to enclose string literals just like '

                        2. In ANSI_QUOTES mode the " character can be used to enclose identifiers just like `

                        The following query will produce different results (or errors) depending on SQL mode:



                        SELECT "column" FROM table WHERE foo = "bar"


                        ANSI_QUOTES disabled



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



                        ANSI_QUOTES enabled



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



                        When to use what



                        • I suggest that you avoid using " so that your code becomes independent of SQL modes

                        • Always quote identifiers since it is a good practice (quite a few questions on SO discuss this)





                        share|improve this answer

























                          102












                          102








                          102






                          There are two types of quotes in MySQL:




                          1. ' for enclosing string literals


                          2. ` for enclosing identifiers such as table and column names

                          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:




                          1. By default the " character can be used to enclose string literals just like '

                          2. In ANSI_QUOTES mode the " character can be used to enclose identifiers just like `

                          The following query will produce different results (or errors) depending on SQL mode:



                          SELECT "column" FROM table WHERE foo = "bar"


                          ANSI_QUOTES disabled



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



                          ANSI_QUOTES enabled



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



                          When to use what



                          • I suggest that you avoid using " so that your code becomes independent of SQL modes

                          • Always quote identifiers since it is a good practice (quite a few questions on SO discuss this)





                          share|improve this answer














                          There are two types of quotes in MySQL:




                          1. ' for enclosing string literals


                          2. ` for enclosing identifiers such as table and column names

                          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:




                          1. By default the " character can be used to enclose string literals just like '

                          2. In ANSI_QUOTES mode the " character can be used to enclose identifiers just like `

                          The following query will produce different results (or errors) depending on SQL mode:



                          SELECT "column" FROM table WHERE foo = "bar"


                          ANSI_QUOTES disabled



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



                          ANSI_QUOTES enabled



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



                          When to use what



                          • I suggest that you avoid using " so that your code becomes independent of SQL modes

                          • Always quote identifiers since it is a good practice (quite a few questions on SO discuss this)






                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited Jul 20 '18 at 23:45

























                          answered Jan 2 '13 at 14:17









                          Salman A

                          176k66336424




                          176k66336424





















                              29














                              (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:



                              $foo = "bar";
                              echo 'there is a $foo'; // There is a $foo
                              echo "there is a $foo"; // There is a bar
                              echo `ls -l`; // ... a directory list





                              share|improve this answer



























                                29














                                (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:



                                $foo = "bar";
                                echo 'there is a $foo'; // There is a $foo
                                echo "there is a $foo"; // There is a bar
                                echo `ls -l`; // ... a directory list





                                share|improve this answer

























                                  29












                                  29








                                  29






                                  (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:



                                  $foo = "bar";
                                  echo 'there is a $foo'; // There is a $foo
                                  echo "there is a $foo"; // There is a bar
                                  echo `ls -l`; // ... a directory list





                                  share|improve this answer














                                  (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:



                                  $foo = "bar";
                                  echo 'there is a $foo'; // There is a $foo
                                  echo "there is a $foo"; // There is a bar
                                  echo `ls -l`; // ... a directory list






                                  share|improve this answer














                                  share|improve this answer



                                  share|improve this answer








                                  edited Nov 26 '15 at 11:13









                                  Peter Mortensen

                                  13.5k1983111




                                  13.5k1983111










                                  answered Jul 4 '12 at 2:03









                                  Chris Trahey

                                  17.1k13250




                                  17.1k13250





















                                      19














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





                                      share|improve this answer



























                                        19














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





                                        share|improve this answer

























                                          19












                                          19








                                          19






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





                                          share|improve this answer














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






                                          share|improve this answer














                                          share|improve this answer



                                          share|improve this answer








                                          edited Aug 20 '17 at 22:04









                                          Nisse Engström

                                          4,10892034




                                          4,10892034










                                          answered Jul 4 '12 at 2:00









                                          Starx

                                          58.4k35155239




                                          58.4k35155239





















                                              12














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



                                              1. " 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.


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


                                              3. () 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' .






                                              share|improve this answer



























                                                12














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



                                                1. " 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.


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


                                                3. () 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' .






                                                share|improve this answer

























                                                  12












                                                  12








                                                  12






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



                                                  1. " 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.


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


                                                  3. () 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' .






                                                  share|improve this answer














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



                                                  1. " 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.


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


                                                  3. () 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' .







                                                  share|improve this answer














                                                  share|improve this answer



                                                  share|improve this answer








                                                  edited Mar 27 '17 at 19:31









                                                  marc_s

                                                  571k12811031252




                                                  571k12811031252










                                                  answered Jan 3 '17 at 11:42









                                                  Kumar Rakesh

                                                  2,28021234




                                                  2,28021234





















                                                      11














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






                                                      share|improve this answer



























                                                        11














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






                                                        share|improve this answer

























                                                          11












                                                          11








                                                          11






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






                                                          share|improve this answer














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







                                                          share|improve this answer














                                                          share|improve this answer



                                                          share|improve this answer








                                                          edited Nov 26 '15 at 11:26









                                                          Peter Mortensen

                                                          13.5k1983111




                                                          13.5k1983111










                                                          answered Jul 4 '12 at 2:16









                                                          xdazz

                                                          132k26198231




                                                          132k26198231





















                                                              10














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



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


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



                                                              $query = "INSERT INTO `table` (`id`, `name`, `email`) VALUES (' ".$_POST['id']." ', ' ".$_POST['name']." ', ' ".$_POST['email']." ')";


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






                                                              share|improve this answer






















                                                              • Therefore double quotes are flexible but can't be used as identifiers.
                                                                – rhavendc
                                                                May 31 '16 at 8:39










                                                              • Please never ever directly use unescaped user input in your query!
                                                                – jankal
                                                                Dec 27 '16 at 9:13










                                                              • @jankal It's just example.I specified that if you are using direct user input then n then...........
                                                                – vipul sorathiya
                                                                Dec 28 '16 at 8:01










                                                              • @vipulsorathiya Please specify in your answer that POST variables should be escaped. You're now pointing at using them direct in your query. Bad for beginners who try this...
                                                                – RFLdev
                                                                Aug 16 '17 at 12:18















                                                              10














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



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


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



                                                              $query = "INSERT INTO `table` (`id`, `name`, `email`) VALUES (' ".$_POST['id']." ', ' ".$_POST['name']." ', ' ".$_POST['email']." ')";


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






                                                              share|improve this answer






















                                                              • Therefore double quotes are flexible but can't be used as identifiers.
                                                                – rhavendc
                                                                May 31 '16 at 8:39










                                                              • Please never ever directly use unescaped user input in your query!
                                                                – jankal
                                                                Dec 27 '16 at 9:13










                                                              • @jankal It's just example.I specified that if you are using direct user input then n then...........
                                                                – vipul sorathiya
                                                                Dec 28 '16 at 8:01










                                                              • @vipulsorathiya Please specify in your answer that POST variables should be escaped. You're now pointing at using them direct in your query. Bad for beginners who try this...
                                                                – RFLdev
                                                                Aug 16 '17 at 12:18













                                                              10












                                                              10








                                                              10






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



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


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



                                                              $query = "INSERT INTO `table` (`id`, `name`, `email`) VALUES (' ".$_POST['id']." ', ' ".$_POST['name']." ', ' ".$_POST['email']." ')";


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






                                                              share|improve this answer














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



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


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



                                                              $query = "INSERT INTO `table` (`id`, `name`, `email`) VALUES (' ".$_POST['id']." ', ' ".$_POST['name']." ', ' ".$_POST['email']." ')";


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







                                                              share|improve this answer














                                                              share|improve this answer



                                                              share|improve this answer








                                                              edited Jun 22 '17 at 4:59

























                                                              answered Jun 16 '15 at 10:25









                                                              vipul sorathiya

                                                              9971020




                                                              9971020











                                                              • Therefore double quotes are flexible but can't be used as identifiers.
                                                                – rhavendc
                                                                May 31 '16 at 8:39










                                                              • Please never ever directly use unescaped user input in your query!
                                                                – jankal
                                                                Dec 27 '16 at 9:13










                                                              • @jankal It's just example.I specified that if you are using direct user input then n then...........
                                                                – vipul sorathiya
                                                                Dec 28 '16 at 8:01










                                                              • @vipulsorathiya Please specify in your answer that POST variables should be escaped. You're now pointing at using them direct in your query. Bad for beginners who try this...
                                                                – RFLdev
                                                                Aug 16 '17 at 12:18
















                                                              • Therefore double quotes are flexible but can't be used as identifiers.
                                                                – rhavendc
                                                                May 31 '16 at 8:39










                                                              • Please never ever directly use unescaped user input in your query!
                                                                – jankal
                                                                Dec 27 '16 at 9:13










                                                              • @jankal It's just example.I specified that if you are using direct user input then n then...........
                                                                – vipul sorathiya
                                                                Dec 28 '16 at 8:01










                                                              • @vipulsorathiya Please specify in your answer that POST variables should be escaped. You're now pointing at using them direct in your query. Bad for beginners who try this...
                                                                – RFLdev
                                                                Aug 16 '17 at 12:18















                                                              Therefore double quotes are flexible but can't be used as identifiers.
                                                              – rhavendc
                                                              May 31 '16 at 8:39




                                                              Therefore double quotes are flexible but can't be used as identifiers.
                                                              – rhavendc
                                                              May 31 '16 at 8:39












                                                              Please never ever directly use unescaped user input in your query!
                                                              – jankal
                                                              Dec 27 '16 at 9:13




                                                              Please never ever directly use unescaped user input in your query!
                                                              – jankal
                                                              Dec 27 '16 at 9:13












                                                              @jankal It's just example.I specified that if you are using direct user input then n then...........
                                                              – vipul sorathiya
                                                              Dec 28 '16 at 8:01




                                                              @jankal It's just example.I specified that if you are using direct user input then n then...........
                                                              – vipul sorathiya
                                                              Dec 28 '16 at 8:01












                                                              @vipulsorathiya Please specify in your answer that POST variables should be escaped. You're now pointing at using them direct in your query. Bad for beginners who try this...
                                                              – RFLdev
                                                              Aug 16 '17 at 12:18




                                                              @vipulsorathiya Please specify in your answer that POST variables should be escaped. You're now pointing at using them direct in your query. Bad for beginners who try this...
                                                              – RFLdev
                                                              Aug 16 '17 at 12:18











                                                              9














                                                              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.






                                                              share|improve this answer



























                                                                9














                                                                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.






                                                                share|improve this answer

























                                                                  9












                                                                  9








                                                                  9






                                                                  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.






                                                                  share|improve this answer














                                                                  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.







                                                                  share|improve this answer














                                                                  share|improve this answer



                                                                  share|improve this answer








                                                                  edited Aug 20 '17 at 22:11









                                                                  Nisse Engström

                                                                  4,10892034




                                                                  4,10892034










                                                                  answered Jul 4 '12 at 2:03









                                                                  diEcho

                                                                  37.2k26125197




                                                                  37.2k26125197





















                                                                      9














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



                                                                      1. BACKTICKS(`) are used around identifier names.

                                                                      2. SINGLE QUOTES(') are used around values.

                                                                      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.



                                                                      DB [XXX]> create temporary table `123456e6` (`id` char (8));
                                                                      Query OK, 0 rows affected (0.03 sec)


                                                                      ERROR when not using backticks.



                                                                      DB [XXX]> create temporary table 123451e6 (`id` char (8));
                                                                      ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '123451e6 (`id` char (8))' at line 1


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



                                                                      DB [XXX]> create temporary table 123451a6 (`id` char (8));
                                                                      Query OK, 0 rows affected (0.03 sec)


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






                                                                      share|improve this answer



























                                                                        9














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



                                                                        1. BACKTICKS(`) are used around identifier names.

                                                                        2. SINGLE QUOTES(') are used around values.

                                                                        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.



                                                                        DB [XXX]> create temporary table `123456e6` (`id` char (8));
                                                                        Query OK, 0 rows affected (0.03 sec)


                                                                        ERROR when not using backticks.



                                                                        DB [XXX]> create temporary table 123451e6 (`id` char (8));
                                                                        ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '123451e6 (`id` char (8))' at line 1


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



                                                                        DB [XXX]> create temporary table 123451a6 (`id` char (8));
                                                                        Query OK, 0 rows affected (0.03 sec)


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






                                                                        share|improve this answer

























                                                                          9












                                                                          9








                                                                          9






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



                                                                          1. BACKTICKS(`) are used around identifier names.

                                                                          2. SINGLE QUOTES(') are used around values.

                                                                          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.



                                                                          DB [XXX]> create temporary table `123456e6` (`id` char (8));
                                                                          Query OK, 0 rows affected (0.03 sec)


                                                                          ERROR when not using backticks.



                                                                          DB [XXX]> create temporary table 123451e6 (`id` char (8));
                                                                          ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '123451e6 (`id` char (8))' at line 1


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



                                                                          DB [XXX]> create temporary table 123451a6 (`id` char (8));
                                                                          Query OK, 0 rows affected (0.03 sec)


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






                                                                          share|improve this answer














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



                                                                          1. BACKTICKS(`) are used around identifier names.

                                                                          2. SINGLE QUOTES(') are used around values.

                                                                          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.



                                                                          DB [XXX]> create temporary table `123456e6` (`id` char (8));
                                                                          Query OK, 0 rows affected (0.03 sec)


                                                                          ERROR when not using backticks.



                                                                          DB [XXX]> create temporary table 123451e6 (`id` char (8));
                                                                          ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '123451e6 (`id` char (8))' at line 1


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



                                                                          DB [XXX]> create temporary table 123451a6 (`id` char (8));
                                                                          Query OK, 0 rows affected (0.03 sec)


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







                                                                          share|improve this answer














                                                                          share|improve this answer



                                                                          share|improve this answer








                                                                          edited Sep 7 '18 at 7:11









                                                                          MPJ

                                                                          301116




                                                                          301116










                                                                          answered Jan 28 '17 at 7:35







                                                                          user5574289




























                                                                              7














                                                                              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.






                                                                              share|improve this answer



























                                                                                7














                                                                                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.






                                                                                share|improve this answer

























                                                                                  7












                                                                                  7








                                                                                  7






                                                                                  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.






                                                                                  share|improve this answer














                                                                                  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.







                                                                                  share|improve this answer














                                                                                  share|improve this answer



                                                                                  share|improve this answer








                                                                                  edited Nov 26 '15 at 12:27









                                                                                  Peter Mortensen

                                                                                  13.5k1983111




                                                                                  13.5k1983111










                                                                                  answered Jul 9 '15 at 6:21









                                                                                  john igneel

                                                                                  172214




                                                                                  172214





















                                                                                      2














                                                                                      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.






                                                                                      share|improve this answer

























                                                                                        2














                                                                                        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.






                                                                                        share|improve this answer























                                                                                          2












                                                                                          2








                                                                                          2






                                                                                          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.






                                                                                          share|improve this answer












                                                                                          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.







                                                                                          share|improve this answer












                                                                                          share|improve this answer



                                                                                          share|improve this answer










                                                                                          answered Feb 18 '18 at 22:10









                                                                                          Funk Forty Niner

                                                                                          80.5k1247101




                                                                                          80.5k1247101





















                                                                                              0














                                                                                              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






                                                                                              share|improve this answer

























                                                                                                0














                                                                                                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






                                                                                                share|improve this answer























                                                                                                  0












                                                                                                  0








                                                                                                  0






                                                                                                  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






                                                                                                  share|improve this answer












                                                                                                  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







                                                                                                  share|improve this answer












                                                                                                  share|improve this answer



                                                                                                  share|improve this answer










                                                                                                  answered Aug 22 '18 at 6:47









                                                                                                  NAVIN

                                                                                                  1,6023623




                                                                                                  1,6023623















                                                                                                      protected by Samuel Liew Oct 5 '15 at 8:58



                                                                                                      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?



                                                                                                      這個網誌中的熱門文章

                                                                                                      What does pagestruct do in Eviews?

                                                                                                      Dutch intervention in Lombok and Karangasem

                                                                                                      Channel Islands