Search code examples
sqlpostgresqlquoted-identifier

Unable to insert into table where column is a foreign key


When inserting into my table I get this error:

ERROR: column "brandid" of relation "Item" does not exist

The brandId column has a foreign key constraint on it that links it to the id of another table.

the table I am inserting into is defined as such:

Column  |  Type   |                      Modifiers                      | Storage  | Stats target | Description 
---------+---------+-----------------------------------------------------+----------+--------------+-------------
 id      | integer | not null default nextval('"Item_id_seq"'::regclass) | plain    |              | 
 name    | text    | not null                                            | extended |              | 
 price   | money   | not null                                            | plain    |              | 
 sizes   | json    | not null                                            | extended |              | 
 brandId | integer | not null                                            | plain    |              | 
 deptId  | integer | not null                                            | plain    |              | 
Indexes:
    "item_pk" PRIMARY KEY, btree (id)
Foreign-key constraints:
    "Item_fk0" FOREIGN KEY ("brandId") REFERENCES "Brand"(id)
    "Item_fk1" FOREIGN KEY ("deptId") REFERENCES "Department"(id)

I am trying to do the following insert statement:

INSERT INTO "Item" (name, price, sizes, brandId, deptId) VALUES
        ('Air Force 1', '120.00', '{"12" : 1 , "10" : 12}',
            (SELECT id FROM "Brand" WHERE name= 'Nike'),
            (SELECT id FROM "Department" WHERE name= 'Mens Shoes'));

All the id columns across my database are of type serial.

The Brand and Department tables have been populated already and those select statements have been tested and work correctly.


Solution

  • Error tells you that pgsql cannot find field brandid (instead of brandId as you expected). Difference is i vs I. Try put field name in insert query in double quotes

    INSERT INTO "Item" (name, price, sizes, "brandId", "deptId") VALUES
        ('Air Force 1', '120.00', '{"12" : 1 , "10" : 12}',
            (SELECT id FROM "Brand" WHERE name= 'Nike'),
            (SELECT id FROM "Department" WHERE name= 'Mens Shoes'));