Backticks in MySQL
- June 18th, 2010
- Posted in Linux . PHP
- By Mr. Nerd
- Write comment
I’ve always wondered, why software such as phpMyAdmin uses a pair of backticks around every table- or column-name, while you read a lot of SQL-statements that don’t.
The answer is quite simple and you’re likely to run into this issue sometime, if you’re creating a lot of MySQL-queries. Take the following (fictional) table name, for example:
Table-1
This is a valid table name in MySQL, so now let’s take a look what’s inside. You’re probably using a statement like:
SELECT * FROM Table-1;
And bang, you’ll get something like: “You have an error in your SQL syntax“. Why is that? If you take a closer look, you’ll see that the syntax is ambiguous. The parser does not understand if you want to reference the table named Table-1 or if you want to subtract 1 from the column named Table.
So to clarify things for the database engine, you must use a pair of backticks, which will escape all special characters contained within them:
SELECT * FROM `Table-1`;
By the way, the same rules apply if you have any other databases, tables or columns named with reserved keywords. A more classic example is to have a column named max or min (both MySQL-functions).
If you’re lazy, you can only add the backticks at the necessary places, for a more consistent look, you might as well add them everywhere. I’m not sure if this is part of any SQL-Standard or if it’s just MySQL specialty.