1

In a statement like this;

$sql = "SELECT distinct `term`,count(*) as count 
FROM {$temp_table_name} 
group by `term` order by count DESC";  

What does using the back tick character (`) around the field name 'term' buy me? Is the usage of back ticks for performance reasons? Or is it for some sort of a SQL injection protection?

Note: After I submit the question, I realized that the backtick character does not show around the field name 'term' - right here on stackoverflow. I don't know of a way of making it appear here in the question body.

juergen d
  • 201,996
  • 37
  • 293
  • 362
Average Joe
  • 4,521
  • 9
  • 53
  • 81

4 Answers4

6

If term is mysql key word, you need to quote it by `, otherwise, it is not necessary.

Ps: distinct is not necessary in your case, because you group by it.

xdazz
  • 158,678
  • 38
  • 247
  • 274
  • Thank you all! All answers were great. xdazz, if I wanted to get an auto incrementing field as the first field in that {$temp_table_name}, so my rows end up like 1-----mercedes----567 & 2------bmw-------566 and so on, what do I do? Actually, I needed this statement in an insertinto operation when creating a report summary table. Currently that table comes with only two cols that is term and count. I'd like to add an incrementing ID in there as the insertinto does it insertions. – Average Joe Jun 17 '12 at 13:25
3

The back-tick is the 'official' identifier quote character.

http://dev.mysql.com/doc/refman/5.0/en/identifiers.html

It allows a wider array of characters in an identifier, as described on the linked documentation.

Chris Trahey
  • 18,202
  • 1
  • 42
  • 55
2

Backticks just allow the use of spaces or other alternate characters in field names.

I think it's already been pretty well explained here.

Community
  • 1
  • 1
Queequeg
  • 108
  • 7
1

When We use a keyword as a table name,field-name in MySQL use backticks, or double-quotes when ANSI_QUOTES is enabled.Other wise it is not necessary.It is not releated to SQL injection protection

4b0
  • 21,981
  • 30
  • 95
  • 142