Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL - INSERT INTO only when the record does not exist [duplicate]

Tags:

c#

sql

sql-server

I realize there a lot of answered SO question on this same topic, but I can't seem to use any of that information to figure out what's wrong with my query.

I'm trying to insert a record into my table only if a record with the same database_owner and database_name (those are two of my column names) does not already exist.

I'm using the query:

INSERT INTO users_databases (database_name, database_key, database_secret, database_owner) 
VALUES ('DB1', '263f690d-7ac3-49f2-aa3b-f5672e4639a2', '367123d8-e5a7-46a0-8101-21f39e6ac8d9', '[email protected]') 
WHERE
   NOT EXISTS 
   (SELECT database_name FROM uses_databases WHERE database_name = 'DB1' AND database_owner = '[email protected]');

But I'm getting the error Incorrect syntax near the keyword 'WHERE'.

I should also point out that running the query

SELECT database_name 
FROM uses_databases 
WHERE database_name = 'DB1' AND database_owner = '[email protected]' 

does return a record.

Where could I be going wrong? From what I've read in the other questions, this looks correct. But it's obviously not. :-) Any advice would be super helpful.

like image 689
Brett Avatar asked Feb 12 '26 11:02

Brett


1 Answers

The easiest solution would be something like this:

IF NOT EXISTS (SELECT database_name FROM uses_databases WHERE database_name = 'DB1' AND database_owner = '[email protected]')
    INSERT INTO users_databases (database_name, database_key, database_secret, database_owner) 
    VALUES ('DB1', '263f690d-7ac3-49f2-aa3b-f5672e4639a2', '367123d8-e5a7-46a0-8101-21f39e6ac8d9', '[email protected]');
like image 177
p.s.w.g Avatar answered Feb 15 '26 02:02

p.s.w.g



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!