Salman Quader
Salman Quader

Reputation: 195

what is different between FROM `tableName` and FROM tableName?


1) "select * from `union` WHERE `thanaId`='$thana_id'" // it's working
    VS
2) "select * from union WHERE thanaId='$thana_id'" // it's not working

1 sql query run properly but 2 Sql query can't execute properly. what is meaning of [``]..
what is different between 1 sql query and 2 sql query?

Upvotes: 0

Views: 231

Answers (3)

spencer7593
spencer7593

Reputation: 108510

The difference in behavior is because UNION is a Reserved Word in MySQL. It can't be used as an identifier unless it is escaped.

In MySQL, identifiers can be escaped by enclosing them in backtick characters.

The first statement works, because the token following the keyword FROM is interpreted as an identifier, because it's enclosed in backtick characters.

The second statement is throwing syntax error, because the token is interpreted as a reserved word UNION and that appears in a spot where MySQL isn't expecting it (where MySQL doesn't allow it.)


Excerpt from the MySQL Reference manual:

backticks

Identifiers within MySQL SQL statements must be quoted using the backtick character (`) if they contain special characters or reserved words. For example, to refer to a table named FOO#BAR or a column named SELECT, you would specify the identifiers as `FOO#BAR` and `SELECT`. Since the backticks provide an extra level of safety, they are used extensively in program-generated SQL statements, where the identifier names might not be known in advance.

Many other database systems use double quotation marks (") around such special names. For portability, you can enable ANSI_QUOTES mode in MySQL and use double quotation marks instead of backticks to qualify identifier names.

Upvotes: 0

Martin
Martin

Reputation: 22770

The backtick encases the string to be treated as a string named literal rather than be interpreted by the MySQL engine. The word union is a reserved / keyword and so MYSQL will be expecting a different syntax because it won't realise that you're using this word as a name identifier.

You would do very well to read and learn this page from the MySQL manual. Every word from the list on this page should be encased in backticks in MySQL queries if you want MySQL to treat it as a name.

It's also useful as much as possible to not name columns/tables with Keywords or reserved words!

Upvotes: 2

Rehban Khatri
Rehban Khatri

Reputation: 954

Difference is that if any word in a mysql statement is quoted with a back tick(`), mysql ASSUMES that you are refering to a table or a column or some mysql field.

For further instructions you may check out this answer

Thanks, RK

Upvotes: -1

Related Questions