More SQL Please: DELETE

pop out tables

users

| id | name_first | name_last | email_address | created_at | active | |----|------------|-----------|---------------------------|---------------------|--------| | 1 | James | Mitchell | jmitchell@email.net | 2023-04-30 09:20:00 | 1 | | 2 | Simon | Chen | simon@sqlanalytics.io | 2023-06-15 14:30:00 | 1 | | 3 | Zara | Amini | zara@aminiconsulting.com | 2023-08-22 11:15:00 | 1 | | 4 | James | Weber | wjames@email.org | 2023-11-05 15:45:00 | 1 | | 5 | Charlotte | Davies | charlotte@zapzoop.io | 2024-02-12 09:49:00 | 0 | | 6 | Marcus | Crawford | marcus@mcrawford.ca | 2024-03-01 09:10:01 | 0 | | 7 | Elena | Moreno | elena@hellocorp.com | 2024-03-12 19:29:11 | 1 | | 8 | Priya | Amini | priya@aminiconsulting.com | 2024-03-24 16:40:00 | 1 |

posts

| id | user_id | content | created_at | |----|---------|--------------------------------|---------------------| | 1 | 1 | Hey folks, how's it going? | 2023-09-22 09:15:00 | | 2 | 3 | I can't wait for the weekend!! | 2023-09-29 16:40:00 |

The DELETE statement allows you to delete existing rows from a table.

A DELETE will delete every row from a table unless a WHERE clause is provided.

It is not required to provide a WHERE clause but it is highly recommended to avoid accidentally deleting all the rows in a table. Some database engines will warn or even prevent you from running a table-wide DELETE statement.

It's usually a good idea to run a SELECT statement with the same WHERE clause as the DELETE to check which rows will be deleted before actually performing the delete.

Remember that each example on this website is editable and runnable so you can see the results of your DELETE by querying the contents of the table, i.e.: SELECT * FROM users;

DELETE FROM users
WHERE id = 8;
1 row affected.
Some database engines support the RETURNING clause, which will cause the database to return the rows that were deleted. You can specify the column names to return or * to include all columns.
DELETE FROM users
WHERE id = 8
RETURNING id, email_address;
| id | email_address | |----|---------------------------| | 8 | priya@aminiconsulting.com |

In this example we have two tables that have a relationship with each other; a post must have an associated user that created it.

Remember that when you create a table you can define Constraints that will tell the database to enforce certain rules on a column. In this example we defined a PRIMARY KEY on the id column of the users table and a FOREIGN KEY on the user_id column of the posts table that references the user's id.

When we try to delete a user that still has posts in the database, the deletion fails because of this constraint we added. This prevents the database from having posts that are no longer associated with a user, also known as "orphaned" records. See more in Schema Design.

DELETE FROM users
WHERE id = 1;
1 row affected.
previous: UPDATE home next: JOIN