SQL: Deleting Rows
Welcome to the Deleting Rows lesson!
This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!
Deleting data is as important as inserting it. Privacy laws like the GDPR even make it a legal requirement.
We can delete data with the
DELETEstatement. LikeUPDATE, it will delete every row by default. You'll want to be very careful withDELETE!>
exec(`CREATE TABLE users (email TEXT, name TEXT)`);exec(`INSERT INTO users (email, name) VALUES ('amir@example.com', 'Amir')`);exec(`INSERT INTO users (email, name) VALUES ('betty.j@example.com', 'Betty')`);exec(`DELETE FROM users`);exec(`SELECT name FROM users`);Result:
[]
We can use a
WHEREclause to limit the deletion. As withSELECTandUPDATE, theWHEREcan include function calls, mathematical expressions, etc.>
exec(`CREATE TABLE users (email TEXT, name TEXT)`);exec(`INSERT INTO users (email, name) VALUES ('amir@example.com', 'Amir')`);exec(`INSERT INTO users (email, name) VALUES ('betty.j@example.com', 'Betty')`);exec(`DELETE FROM users WHERE name = 'Betty'`);exec(`SELECT name FROM users`);Result:
[{name: 'Amir'}]Here's a code problem:
If multiple rows match a
WHEREclause, they'll all be deleted. Delete all of the people named "Amir" or "Betty".exec(`CREATE TABLE users (email TEXT, name TEXT);INSERT INTO users (email, name)VALUES ('amir@example.com', 'Amir');INSERT INTO users (email, name)VALUES ('betty.j@example.com', 'Betty');INSERT INTO users (email, name)VALUES ('betty.k@example.com', 'Betty');INSERT INTO users (email, name)VALUES ('cindy@example.com', 'Cindy');`);exec(`DELETE FROM users WHERE name = 'Amir' OR name = 'Betty'`);exec(`SELECT name FROM users`);- Goal:
[{name: 'Cindy'}]- Yours:
[{name: 'Cindy'}]