ERROR: syntax error in or next to "SELECT"

I am really new to postgres. The question looks very simple, but I just don’t see where I made a mistake.

I created the table as follows:

  CREATE TABLE IF NOT EXISTS t(
        tn VARCHAR(30) NOT NULL,
        PRIMARY KEY(tn)
    );

I want to insert an instance if the instance does not exist. Here is my code:

INSERT INTO t (tn) 
VALUES 
(SELECT 'q' WHERE NOT EXISTS (SELECT * FROM t WHERE tn = 'q')) ;

And the psql console keeps giving me an error

ERROR:  syntax error at or near "SELECT"

I checked each part of the code individually, for example,

SELECT 'q' WHERE NOT EXISTS (SELECT * FROM t WHERE tn = 'q');

and

INSERT INTO t (tn) VALUES ('p');

performed without errors. But an error occurs when I stack them.

Does anyone know where I am wrong ..?

+4
source share
1 answer

Lose VALUESand brackets ...

INSERT INTO t (tn) 
SELECT 'q' WHERE NOT EXISTS (SELECT * FROM t WHERE tn = 'q');
+4
source

Source: https://habr.com/ru/post/1662042/


All Articles