How to use the SQL DELETE clause

Subscribe to my newsletter and never miss my upcoming articles

Deletion is a fundamental operation when working with relational databases. It is used when one or more rows are to be removed from a table. The WHERE clause always accompanies the DELETE clause.

So, let's say we have a table of user posts. To delete rows without a user_id foreign key, we can run this query:

DELETE FROM `posts` WHERE user_id IS NULL;

You may be tempted to write it this way:

DELETE FROM `posts` WHERE user_id=NULL;

This doesn't work because NULL does not equal NULL in SQL. Since the value in the column is unknown, we can't compare it with another unknown. Check this StackOverflow page to learn more.

Thanks for reading. Adios ✌🏾🧡.

No Comments Yet