Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why put ` around columns?

Tags:

mysql

In some code i see people put ` around their columns. Why? IS there any difference from not using them?

SELECT `players`.`name`, `houses`.`id` FROM `players`, `houses` 
WHERE `houses`.`owner` = `players`.`id`
like image 967
Jack Avatar asked Jul 16 '10 07:07

Jack


1 Answers

Using the backquotes allows reserved words to be used as column or table names e.g.

SELECT `values` FROM `references` WHERE `precision` > 0

and names with nonalphanumerics must be enclosed between the "`"s too, e.g.

SELECT `user name` FROM `registered users` WHERE `total score` > 0

See http://dev.mysql.com/doc/refman/5.1/en/identifiers.html for detail.


I think this is often seen when those names are used dynamically, e.g. (artificial example)

mysql_prepare_statement("SELECT `%q` FROM `%q` WHERE `%q` > 0", col, tbl, col_cond);

in this form, any kinds of column and table names can be handled identically, and malicious injection attempts such as col = "1; DROP TABLE users--" can be avoided.

like image 90
kennytm Avatar answered Nov 03 '22 02:11

kennytm