SQL query: Can't order by column called “order”?

隐身守侯 提交于 2020-01-21 09:17:06

问题


I am pulling a column in an existing script into my template files, and everything is working great.

The only problem is, that this script has a column called order, and every row then has a number in that column to show which should be at the top etc. If I set my query to "ORDER BY name" for example, everything works fine, but when I use "ORDER BY order", then I get a SQL error.
Can I not have a column called order? I can't change column name, because it's part of the script.

Is there a way around it?

This is the line in my SQL query:

SELECT * FROM categories WHERE hide = 0 ORDER BY order 

回答1:


order is a keyword in SQL. So if you wish to use a keyword as a name, use backtick characters around it:

SELECT * FROM categories WHERE hide = 0 ORDER BY `order`

Try that :)




回答2:


If you are working with Postgres just use "column_name", e.g:

SELECT "order" FROM table_name WHERE "order" > 10 ORDER BY "order";



回答3:


Try using backticks:

SELECT * FROM `categories` WHERE `hide` = 0 ORDER BY `order`

ORDER is a reserved word in SQL. You can use a reserved word as a column name but you must surround it in backticks when referencing it. It's good practice to surround all your column names in backticks so you don't run into this issue.




回答4:


Try using back ticks around the column name, that should do it.




回答5:


From the manual:

A reserved word can be used as an identifier if you quote it.

So you can use it like this:

SELECT * FROM categories WHERE hide = 0 ORDER BY `order`



回答6:


AS orderis a SQL keyword, you should escape it properly as an field identifier by using backticks:

SELECT ... FROM ... ORDER by `order`



回答7:


Worked for me with brackets. SELECT T.* FROM dbo.test AS T ORDER BY [T].[ORDER]



来源:https://stackoverflow.com/questions/12788173/sql-query-cant-order-by-column-called-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!