Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgresql: syntax error at or near "user"

Tags:

sql

postgresql

This is probably a simple question, but I've spent an embarrassing amount of time trying to figure out what's wrong.

I'm trying to run a query on a table "user" containing two columns username and id.

INSERT INTO user
   (username, id) 
VALUES
   ("user", 2)

I end up getting this error.

ERROR:  syntax error at or near "user"
LINE 1: INSERT INTO user
                    ^
********** Error **********

ERROR: syntax error at or near "user"
SQL state: 42601
Character: 13

Here is the table creation for reference

-- Table: public."user"

-- DROP TABLE public."user";

CREATE TABLE public."user"
(
    id integer NOT NULL,
    username text COLLATE pg_catalog."default",
    CONSTRAINT user_pkey PRIMARY KEY (id)
)
WITH (
    OIDS = FALSE
)
TABLESPACE pg_default;

ALTER TABLE public."user"
    OWNER to postgres;
like image 666
1halfazn Avatar asked Jul 28 '17 09:07

1halfazn


1 Answers

In Postgres user is a reserved SQL keyword. You should avoid naming your tables using reserved keywords. As a workaround here, you can place your table name in double quotes when referring to it:

INSERT INTO "user"
   (username, id) 
VALUES
   ('user', 2)

I also switched to using single quotes for string literals. This helps to distinguish the use of double quotes from single ones.

like image 111
Tim Biegeleisen Avatar answered Sep 22 '22 14:09

Tim Biegeleisen