JochemQuery
JochemQuery

Reputation: 1547

Are quotes around tables and columns in a MySQL query really necessary?

I have a short question about mysql query.

What is correct?

SELECT * FROM Persons WHERE Year='1965'

Or

SELECT * FROM `Persons` WHERE `Year` = '1965'

Is this a personal choice or is this something what is really wrong?

Upvotes: 10

Views: 1889

Answers (4)

Mattias
Mattias

Reputation: 9481

Both methods are correct, the single quotation mark indicates starts and endings of a string.

Therefore if you for example use a column alias with a space like Birth year then you will need to use the single quotation mark like this;

... WHERE `Birth year` = `1965`

However it is not recommended only use more then one word in the aliases.

And as @Cody Caughlan said also when you use MySQL reserved words.

Upvotes: 2

Nadh
Nadh

Reputation: 7243

What if you have a table named table, or a column named where. These are reserved keywords. If you used those in your queries without backticks, they'd produce an invalid query (Of course, using reserved keywords is bad practice).

SELECT something FROM table WHERE where = 1;

vs.

SELECT something FROM `table` WHERE `where` = 1;

Upvotes: 6

Manuel
Manuel

Reputation: 10303

Both are correct, but the second one will ALWAYS be accepted, even when you use keywords or functions like while and NOW() that would normally be seen as operators.

Upvotes: 7

Cody Caughlan
Cody Caughlan

Reputation: 32748

Quotes are needed if your identifiers (column, table names, operators, etc.) contain MySQL reserved words.

See here for the complete list of reserved words: http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html

Upvotes: 9

Related Questions