5

Why, when I try to do an order by query, do I always get an error telling me to check the syntax by the ORDER BY 'order' DESC?

Here's my query:

SELECT * FROM posts ORDER BY order DESC;

What am I doing wrong?

Dharman
  • 30,962
  • 25
  • 85
  • 135
Sam Clark
  • 429
  • 3
  • 7
  • 12

3 Answers3

9

order is a reserved word in SQL; case does not matter. It must be quoted when used as an identifier. From the MySQL Reserved Words documentation:

Certain words such as SELECT, DELETE, or BIGINT [or ORDER] are reserved and require special treatment for use as identifiers such as table and column names.

Traditional MySQL quotes:

SELECT * FROM posts ORDER BY `order` DESC;

Proper (ANSI) SQL quotes (some databases support [order] as well):

SELECT * FROM posts ORDER BY "order" DESC;

Although I would consider renaming the column to avoid such confusing issues in the future.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
2

Order is a reserved keyword.

Try,

SELECT * FROM posts ORDER BY `order` DESC;
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
KV Prajapati
  • 93,659
  • 19
  • 148
  • 186
1

The column name is order which is a keyword. You need to do this:

SELECT * FROM posts ORDER BY `order` DESC;
joshuahealy
  • 3,529
  • 22
  • 29