Delete using join-queries

by Allan Svelmøe Hansen April 24, 2008 18:29

Occasionally I run into having to clean or modify data using a range of more or less complex conditions.
Then the following syntax comes in handy, because it is actually possible to use complex queries utilizing joins, to delete information from.

The example is realtive simple but it illustrates the point quite well ....... I hope :)

DELETE T1
FROM Table1 T1
INNER JOIN Table2 T2 ON T1.TableOneID T2.TableOneID

As can be seen the syntax is a little bit different from a normal delete. This query will delete all rows in T1 aka Table1 which would be selected out by my query.

A good rule when building such queries to delete from is to build them up as selects, and then when you have selected the correct data out, you can substitute the SELECT with a DELETE <ALIAS>

I use this type of synax a lot in at work and just wanted to share it, in case it wasn't as known for people. It can quickly become a powerful tool for deleting the correct data when normal subqueries aren't useful.

Bookmark and Share DotnetKicks dotnetshoutout

Tags: , ,

SQL

Add comment




  Country flag

biuquote
  • Comment
  • Preview
Loading



Powered by BlogEngine.NET 1.6.1.0
Theme by Mads Kristensen | Modified by Mooglegiant

About:
Allan Svelmøe Hansen

My real name is Allan Svelmøe Hansen.
I live in Denmark, where I work as a developer for hedal:kruse:brohus using SQL Server and the .NET framework since 2004.
My primary fields of expertise is back-end data integration, database design and optimization.


       View Allan Svelmøe Hansen's profile on LinkedIn     

Disclaimer

The opinions expressed herein are my own personal opinions and thoughts and does not represent my employers view in any way, nor are my results guaranteed for all situations.
Content is presented "as is", with no warranty.