Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ERROR: syntax error at or near "SELECT"

I am really new to postgres. The question looks very simple but I just cant see where I got wrong.

I a table created 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 the error

ERROR:  syntax error at or near "SELECT"

I have checked every piece of code individually, for instance both

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

and

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

run without error. But error occurs when I put them together.

Does anyone know where I got wrong..?

like image 221
Y_KL Avatar asked Nov 26 '16 23:11

Y_KL


People also ask

What Is syntax error at or near?

Syntax Error, an error that can occur due to a slight carelessness of the software, occurs during coding. The error that usually occurs when writing the source code can confuse the site. Such errors, which can also occur in computer programs, can confuse the computer.

Why am I getting a syntax error in SQL?

Misspellings are the most common cause for error in SQL. Unfortunately, SQL will not autocorrect mistyped keywords, tables, columns, or values. Check keyword spelling by referring to the documentation for the type of SQL you are using.


1 Answers

Lose VALUES and the brackets...

INSERT INTO t (tn) 
SELECT 'q' WHERE NOT EXISTS (SELECT * FROM t WHERE tn = 'q');
like image 106
Bohemian Avatar answered Sep 17 '22 05:09

Bohemian