i'm looking for a way to delete records in table 1 with matching combinations in table 2 on 'stn' and 'jaar'. The contents of column 'jaar' in table2 is formatted in a previous stage/query by
year(datum) AS 'jaar'
Sorry, can't find again the site where i found this "solution".
DELETE FROM table1
WHERE stn, year(datum) IN (SELECT stn, jaar FROM table2);
You can use the WHERE clause with a DELETE query to delete the selected rows, otherwise all the records would be deleted.
The DELETE command is used to delete existing records in a table.
If you run a DELETE statement with no conditions in the WHERE clause, all of the records from the table will be deleted.
In SQL, you can delete a row in a table by using the DELETE query and the WHERE clause.
You can achieve this using exists
:
DELETE FROM table1 WHERE exists( SELECT 1 FROM table2 WHERE table2.stn = table1.stn and table2.jaar = year(table1.datum) )
The canonical T-SQL (SqlServer) answer is to use a DELETE
with JOIN
as such
DELETE o FROM Orders o INNER JOIN Customers c ON o.CustomerId = c.CustomerId WHERE c.FirstName = 'sklivvz'
This will delete all orders which have a customer with first name Sklivvz.
Try adding parentheses around the row in table1
e.g.
DELETE
FROM table1
WHERE (stn, year(datum)) IN (SELECT stn, jaar FROM table2);
The above is Standard SQL-92 code. If that doesn't work, it could be that your SQL product of choice doesn't support it.
Here's another Standard SQL approach that is more widely implemented among vendors e.g. tested on SQL Server 2008:
MERGE INTO table1 AS t1
USING table2 AS s1
ON t1.stn = s1.stn
AND s1.jaar = YEAR(t1.datum)
WHEN MATCHED THEN DELETE;
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