How to deal with SQL column names that look like SQL keywords?

后端 未结 14 1099
温柔的废话
温柔的废话 2020-11-22 13:24

One of my columns is called from. I can\'t change the name because I didn\'t make it. Am I allowed to do something like SELECT from FROM TableName

相关标签:
14条回答
  • 2020-11-22 13:46

    If it had been in PostgreSQL, use double quotes around the name, like:

    select "from" from "table";
    

    Note: Internally PostgreSQL automatically converts all unquoted commands and parameters to lower case. That have the effect that commands and identifiers aren't case sensitive. sEleCt * from tAblE; is interpreted as select * from table;. However, parameters inside double quotes are used as is, and therefore ARE case sensitive: select * from "table"; and select * from "Table"; gets the result from two different tables.

    0 讨论(0)
  • 2020-11-22 13:46

    These are the two ways to do it:

    1. Use back quote as here:

    SELECT `from` FROM TableName

    1. You can mention with table name as:

    SELECT TableName.from FROM TableName

    0 讨论(0)
  • 2020-11-22 13:47

    Judging from the answers here and my own experience. The only acceptable answer, if you're planning on being portable is don't use SQL keywords for table, column, or other names.

    All these answers work in the various databases but apparently a lot don't support the ANSI solution.

    0 讨论(0)
  • 2020-11-22 13:50

    If you ARE using SQL Server, you can just simply wrap the square brackets around the column or table name.

    select [select]
    from [table]
    
    0 讨论(0)
  • 2020-11-22 13:51

    The following will work perfectly:

    SELECT DISTINCT table.from AS a FROM table
    
    0 讨论(0)
  • 2020-11-22 13:53

    In MySQL, alternatively to using back quotes (`), you can use the UI to alter column names. Right click the table > Alter table > Edit the column name that contains sql keyword > Commit.

    select [from] from <table>
    

    As a note, the above does not work in MySQL

    0 讨论(0)
提交回复
热议问题