I'd like to combine an insert query with a "where not exists" so as not to violate PK constraints. However, syntax such as the following gives me an Incorrect syntax near the keyword 'WHERE'
error -
INSERT INTO myTable(columns...)
VALUES(values...)
WHERE NOT EXISTS
(SELECT *
FROM myTable
WHERE pk_part1 = value1,
AND pk_part2 = value2)
How can I accomplish this?
(In general, can you combine an insert with a where clause?)
The basic syntax for INSERT IF NOT EXISTS is as follows. Copy INSERT INTO name_of_the_table (column_name) SELECT * FROM (SELECT value_name) AS val WHERE NOT EXISTS (<conditonal expression>); In the name_of_the_table we insert the value_name in the column_name if the conditional expression is met.
The alternative (and generally preferred) method for INSERTING into rows that may contain duplicate UNIQUE or PRIMARY KEY values is to use the INSERT ... ON DUPLICATE KEY UPDATE statement and clause.
Copying specific rows from a table: We can copy specific rows from a table to insert into another table by using WHERE clause with the SELECT statement. We have to provide appropriate condition in the WHERE clause to select specific rows.
Using Joins Instead of IN or EXISTS An alternative for IN and EXISTS is an INNER JOIN, while a LEFT OUTER JOIN with a WHERE clause checking for NULL values can be used as an alternative for NOT IN and NOT EXISTS.
INSERT INTO myTable(columns...)
Select values...
WHERE NOT EXISTS
(SELECT *
FROM myTable
WHERE pk_part1 = value1,
AND pk_part2 = value2)
Edit: After reading martins link, If admit, that the best solution is:
BEGIN TRY
INSERT INTO myTable(columns...)
values( values...)
END TRY
BEGIN CATCH
IF ERROR_NUMBER() <> 2627
RAISERROR etc
END CATCH;
The simplest way to keep a unique list of values is to either a) set the column(s) as the primary key or b) create a unique constraint on the column(s). Either of these would result in an error when attempting to insert/update values to something that already exists in the table, when a NOT EXISTS/etc would fail silently -- no error, query will execute properly.
That said, use an INSERT/SELECT (don't include the VALUES portion):
INSERT INTO myTable(columns...)
SELECT [statically defined values...]
FROM ANY_TABLE
WHERE NOT EXISTS (SELECT NULL
FROM myTable
WHERE pk_part1 = value1
AND pk_part2 = value2)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With