Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using backticks around field names

After reading a couple of answers and comments on some SQL questions here, and also hearing that a friend of mine works at a place which has a policy which bans them, I'm wondering if there's anything wrong with using backticks around field names in MySQL.

That is:

SELECT `id`, `name`, `anotherfield` ... -- vs -- SELECT id, name, anotherfield ... 
like image 969
nickf Avatar asked Nov 04 '08 10:11

nickf


People also ask

Should you use Backticks in SQL?

Backticks ( ` ) are used to indicate database, table, and column names. Unless you're using reserved or conflicting words for table and database names, you'll not need to use them.

Can field names have spaces?

Blanks spaces are restricted in the naming convention of the database object's name and column name of the table. If you want to include the blanks space in the object name or column name, the query and application code must be written differently.

What does Backtick do in SQL?

Backticks are used in MySQL to select columns and tables from your MySQL source. In the example below we are calling to the table titled Album and the column Title . Using backticks we are signifying that those are the column and table names.


2 Answers

Using backticks permits you to use alternative characters. In query writing it's not such a problem, but if one assumes you can just use backticks, I would assume it lets you get away with ridiculous stuff like

SELECT `id`, `my name`, `another field` , `field,with,comma`  

Which does of course generate badly named tables.

If you're just being concise I don't see a problem with it, you'll note if you run your query as such

EXPLAIN EXTENDED Select foo,bar,baz  

The generated warning that comes back will have back-ticks and fully qualified table names. So if you're using query generation features and automated re-writing of queries, backticks would make anything parsing your code less confused.

I think however, instead of mandating whether or not you can use backticks, they should have a standard for names. It solves more 'real' problems.

like image 172
Kent Fredric Avatar answered Nov 15 '22 22:11

Kent Fredric


The only problem with backticks is that they are not ANSI-SQL compliant, e.g. they don't work in SQL Server.

If there is a chance you would have to port your SQL to another database, use double quotes.

like image 40
Alexander Kojevnikov Avatar answered Nov 15 '22 22:11

Alexander Kojevnikov