Insert if exists only works if there are records in table - sql

I'm using the following query to insert a record into a table only if it does not exist:
INSERT INTO tblExample (exampleColumn)
SELECT 'test' FROM tblExample
WHERE NOT EXISTS (SELECT 1 FROM tblExample where exampleColumn = 'test');
It works fine as long as there is at least 1 record in the table. If there are no records, it will not insert the record into the table.
Can anyone see what is wrong with my query?
Thanks!

Tested with Derby 10.12
INSERT INTO tblExample (exampleColumn)
SELECT *
from (values ('test')) as x(col)
WHERE NOT EXISTS (SELECT 1
FROM tblExample t
where t.exampleColumn = x.col);

Try this,
INSERT INTO tblExample (exampleColumn)
SELECT Value FROM ( SELECT 'test' Value) T1
WHERE NOT EXISTS (SELECT 1 FROM tblExample where exampleColumn = 'test')
Or you can use this
INSERT INTO tblExample (exampleColumn)
SELECT Value FROM ( SELECT 'test' Value) T1
LEFT JOIN tblExample ON exampleColumn = Value
WHERE exampleColumn IS NULL

Query is :
INSERT INTO user (id, name, date)
SELECT 23,test,DATE('2013-02-12')
FROM contact
WHERE NOT EXISTS ( SELECT 1 FROM user WHERE id = 23 )

thanks for your help. I have found that the best way to add a record if it doesn't already exist (even when there are no records in the table) is by using the following statement:
INSERT INTO tblExample(exampleColumn)
(SELECT 'test' FROM tblExample WHERE exampleColumn='test' HAVING COUNT(*)=0);

Your first query "SELECT 'test' FROM tblExample" will return 0 rows if there is not record in a table.
Use bellow code.
IF NOT EXISTS(SELECT * FROM tblExample where exampleColumn='test')
insert into tblExample(exampleColumn) values ('test')

Related

Insert or update data using cte_results in SQL Server

I have a query having cte with number of columns, I want to insert a record if ID from the results of that query does not exist in table that I am inserting, or if the ID exists I want to update data using that ID.
So far I have tried this:
WITH cte_base as(
SELECT DISTINCT ID, statusID
FROM testtable
)
SELECT *
FROM cte_base
IF EXISTS(SELECT * FROM Newtable WHERE EXISTS (SELECT ID FROM cte_base))
UPDATE newtable
SET statusID = 2
WHERE Newtable.ID = cte_base.ID
ELSE
INSERT INTO newtable(ID, statusID)
SELECT ID, statusID
FROM cte_base
WHERE Newtable.ID <> cte_base.ID
I have to run this query against live data, hence I would like to know if my logic is correct.
Basic merge example based on your provided code.
MERGE INTO NewTable AS T
USING
(
SELECT DISTINCT ID,statusID
FROM testtable
) AS S
ON S.ID = T.ID
WHEN MATCHED THEN SET
T.StatusID = 2
WHEN NOT MATCHED INSERT (ID,statusID)
VALUES (S.ID,S.statusID)
;
What are you trying to do?
EXISTS (SELECT ID FROM cte_base)
If cte_base has any records that will be true every time
That is no different than
SELECT DISTINCT ID, statusID
FROM testtable
And will be true every time if there are any records in testtable

How to exclude rows in sql server insert statement?

I have a statement like this
insert into A (id, nid)
(
select id, 100 as nid
from B
group by id
)
this works, but the problem is table A, has a primary key constraint on (id, nid), and some of the rows in the computed nested query, already exist in table A. How can I exclude them from being included in the nested query?
Thanks
You could use EXCEPT:
insert into A (id, nid)
select id, 100 as nid
from B
group by id
EXCEPT
SELECT id, nid
FROM A;
Just check if the rows exist...
insert into A (id, nid)
select id, 100 as nid
from B
WHERE NOT EXISTS (SELECT * FROM A WHERE A.id = B.id AND A.nid = 100)
group by id
PS: the parenthesis around your select are unnecessary
Add Where clause:
insert A (id, nid)
select id, 100 as nid
from B
Where Not exists (Select * from A
Where id = B.Id
and nid = 100)
group by id

Big Query - Only insert if column value does not exist

Does Big Query support operations like "REPLACE INSERT" or something related to that?
If I run a query like this twice:
INSERT INTO table(column1) VALUES(1)
It'll create a duplicated row, is it possible to insert a row only if a column with the same value does not exist?
Thanks!
Below should make it
#standardSQL
INSERT INTO yourTable(column1)
SELECT value FROM (SELECT 1 AS value)
LEFT JOIN yourTable
ON column1 = value
WHERE column1 IS NULL
Does this work for you?
INSERT INTO table(column1)
WITH s AS (SELECT 1 src)
SELECT src FROM s WHERE NOT EXISTS (
SELECT * FROM table t WHERE t.column1 = s.src
)

Issue with NOT IN

SELECT *
FROM table -> 35 records
SELECT *
FROM table
WHERE x IN (SELECT x
FROM table1) -> 34 records
SELECT *
FROM table
WHERE x NOT IN (SELECT x
FROM table1) -> 0 records
Any ideas as to how this could be possible?
The simple fix for the NULL value is:
SELECT *
FROM table
WHERE x NOT IN (SELECT x
FROM table1
WHERE x is not null);
However, it is recommended to use not exists rather than not in because of the NULL issue:
select t.*
from table t
where not exists (select 1 from table1 t1 where t1.x = t.x);
One of your x values is NULL. NULL values will never evaluate to true in any comparison (since the value is unknown).
As others have said, 1 of your values is likely to be NULL. You can test for this using IS NULL in your WHERE clause. For example:
SELECT *
FROM MyTable
WHERE MyColumn IS NULL
This simple example would find all records in MyTable that have NULL in MyColumn.
"Any null values returned by subquery or expression that are compared to test_expression using IN or NOT IN return UNKNOWN. Using null values in together with IN or NOT IN can produce unexpected results.
"
NOT/IN MSDN
for a Note, NOT IN is appropriate when you know the number of rows coming from sub-query will remain always small and finite values.
it is not advisable if that list items are uncertain. instead use the LEFT JOIN type query.
EDIT-1 For #John Gibb
DECLARE #t TABLE
(
id INT NULL
)
DECLARE #t1 TABLE
(
id INT NULL
)
INSERT INTO #t (id) SELECT 1 UNION ALL SELECT NULL UNION ALL SELECT 2
INSERT INTO #t1 (id) SELECT 1 UNION ALL SELECT NULL
SELECT *
FROM #t
WHERE id NOT IN (SELECT id FROM #t1)
SELECT *
FROM #t t
LEFT JOIN #t1 t1
ON t.id=t1.id
WHERE t1.id IS NULL
AND t.id IS NOT NULL

INSERT INTO SELECT from UPDATE

I need to select some values from a table to be updated, and then update them right away. Furthermore, I need to insert one new record in a table for each updated record. To select records and update I am using a structure like
UPDATE TableA SET SomeField = 1 OUTPUT RecordID FROM TableA WHERE RecordID IN
(
SELECT TOP #Something RecordID FROM TableA
)
Now, for the insert part, I would like to wrap the UPDATE statement into an INSERT INTO SELECT, thus taking advantage of the OUTPUT clause. However, SQL complains when I do
INSERT INTO TableA SELECT ( RecordID , GETDATE() ) FROM
(
UPDATE TableA SET SomeField = 1 OUTPUT RecordID FROM TableA WHERE RecordID IN
(
SELECT TOP #Something RecordID FROM TableA
)
)
Can't I do it all in one statement, even with the OUTPUT clause?
UPDATE TableA SET SomeField = 1
OUTPUT inserted.RecordID, GETDATE() into TableA (RecordID , DT)
FROM TableA
WHERE RecordID IN
(
SELECT TOP #Something RecordID FROM TableA
)
Just not sure - you're trying to insert updated rows again ?
It is posible to use output to insert the updated rows from one table to another:
However I cannot make that syntax you are using to work.
Please check out this link
Of course, you could try something like this:
INSERT INTO TableA (RecordID, Value)
SELECT RecordID, GETDATE()
FROM OPENQUERY(
yourserver,
'UPDATE TableA
SET SomeField = 1
OUTPUT inserted.RecordID
WHERE RecordID IN (SELECT TOP (5) RecordID FROM TableA)'
)
But there's a couple of issues with the approach:
You'd need to create a linked server yourserver.
The 'remote' query wouldn't be very swift.
You'd have hard time replacing TOP (5) with TOP (#Something). Actually you'd most probably have to turn the entire statement into a dynamic query. (That's right, you'd have to put the already dynamic UPDATE inside another dynamic query.)
I expect, with the last issue the one-statement limitation would finally be broken.
So, instead, why not have it like this:
DECLARE #tmpRecords TABLE (RecordID int);
UPDATE TableA
SET SomeField = 1
OUTPUT inserted.RecordID INTO #tmpRecords (RecordID)
WHERE RecordID IN (SELECT TOP (#Something) RecordID FROM TableA);
INSERT INTO TableA (RecordID, SomeDateColumn)
SELECT RecordID, GETDATE()
FROM #tmpRecords;