1

I want to insert a new record if the record is not present in the table

For that I am using below query in Teradata

 INSERT INTO sample(id, name) VALUES('12','rao')
 WHERE NOT EXISTS (SELECT id FROM sample WHERE id = '12'); 

When I execute the above query I am getting below error.

 WHERE NOT EXISTS
 
Failure 3706 Syntax error: expected something between ')' and the 'WHERE' keyword.

Can anyone help with the above issue. It will be very helpful.

Merrin K
  • 792
  • 1
  • 7
  • 17
Sharma
  • 11
  • 3
  • Does this answer your question? [How to 'insert if not exists' in MySQL?](https://stackoverflow.com/questions/1361340/how-to-insert-if-not-exists-in-mysql) – Merrin K Dec 30 '20 at 10:04

3 Answers3

1

You can use INSERT INTO ... SELECT ... as follows:

INSERT INTO sample(id,name)
 select '12','rao'
   WHERE NOT EXISTS (SELECT id FROM sample WHERE id = '12');

You can also create the primary/unique key on id column to avoid inserting duplicate data in id column.

Popeye
  • 34,354
  • 4
  • 8
  • 30
0

I would advise writing the query as:

INSERT INTO sample (id, name)
   SELECT id, name
   FROM (SELECT 12 as id, 'rao' as name) x
   WHERE NOT EXISTS (SELECT 1 FROM sample s WHERE s.id = x.id);

This means that you do not need to repeat the constant value -- such repetition can be a cause of errors in queries. Note that I removed the single quotes. id looks like a number so treat it as a number.

The uniqueness of ids is usually handled using a unique constraint or index:

alter table sample add constraint unq_sample_id unique (id);

This makes sure that the database ensures uniqueness. Your approach can fail if two inserts are run at the same time with the same id. An attempt to insert a duplicates returns an error (which the exists can then avoid).

In practice, id columns are usually generated automatically by the database. So the create table statement would look more like:

id integer generated by default as identity

And the insert would look like:

insert into sample (name)
    values (name);
Gordon Linoff
  • 1,122,135
  • 50
  • 484
  • 624
0

If id is the Primary Index of the table you can use MERGE:

merge into sample as tgt 
using VALUES('12','rao') as src (id, name)
on src.id = tgt.id
when not matched
then insert (src.id,src.name)
dnoeth
  • 54,996
  • 3
  • 29
  • 45