PostgreSQL column 'foo' does not exist

前端 未结 10 2128
盖世英雄少女心
盖世英雄少女心 2020-12-05 12:32

I have a table that has 20 integer columns and 1 text column named \'foo\'

If I run query:

SELECT * from table_name where foo is NULL
10条回答
  •  一向
    一向 (楼主)
    2020-12-05 13:14

    It could be quotes themselves that are the entire problem. I had a similar problem and it was due to quotes around the column name in the CREATE TABLE statement. Note there were no whitespace issues, just quotes causing problems.

    The column looked like it was called anID but was really called "anID". The quotes don't appear in typical queries so it was hard to detect (for this postgres rookie). This is on postgres 9.4.1

    Some more detail:

    Doing postgres=# SELECT * FROM test; gave:

      anID | value 
     ------+-------
         1 | hello
         2 | baz
         3 | foo (3 rows)
    

    but trying to select just the first column SELECT anID FROM test; resulted in an error:

    ERROR:  column "anid" does not exist 
    LINE 1: SELECT anID FROM test;
                    ^
    

    Just looking at the column names didn't help: postgres=# \d test;

              Table "public.test"
     Column |       Type        | Modifiers 
    --------+-------------------+-----------
     anID   | integer           | not null
     value  | character varying | 
    Indexes:
        "PK on ID" PRIMARY KEY, btree ("anID")
    

    but in pgAdmin if you click on the column name and look in the SQL pane it populated with:

    ALTER TABLE test ADD COLUMN "anID" integer;
    ALTER TABLE test ALTER COLUMN "anID" SET NOT NULL;
    

    and lo and behold there are the quoutes around the column name. So then ultimately postgres=# select "anID" FROM test; works fine:

     anID 
    ------
        1
        2
        3
    (3 rows)
    

    Same moral, don't use quotes.

提交回复
热议问题