Delete Data
DELETE removes rows from a table.
Like UPDATE, safety depends on your WHERE clause.
Core Concepts
flowchart TD
A[DELETE FROM table] --> B{WHERE condition present?}
B -->|Yes| C[Matching rows removed]
B -->|No| D[All rows removed]
| Statement | Effect |
|---|---|
DELETE FROM logs WHERE id = 10; | Removes one matching row |
DELETE FROM logs; | Removes all rows |
Code Examples
-- Setup sample table and rows.
CREATE TABLE sessions (
session_id INTEGER PRIMARY KEY,
user_name TEXT NOT NULL,
expired INTEGER NOT NULL DEFAULT 0
);
INSERT INTO sessions (user_name, expired)
VALUES ('Ada', 0), ('Alan', 1), ('Linus', 1);
| Expected output |
|---|
| Table created and three rows inserted. |
-- Delete only expired sessions.
DELETE FROM sessions
WHERE expired = 1;
| Expected output |
|---|
| Two rows deleted. |
-- Verify remaining rows.
SELECT session_id, user_name, expired
FROM sessions;
| session_id | user_name | expired |
|---|---|---|
| 1 | Ada | 0 |
SQLite-Specific Nuances
SQLite Nuance
SQLite supports DELETE ... WHERE ... and full-table delete behavior like other SQL databases.
Common Pitfalls / Best Practices
Pitfall
Executing DELETE FROM table; when you meant to remove only a subset.
Best Practice
Use a SELECT with the same filter first, then run DELETE once the row set is confirmed.
Quick Challenge
Delete sessions for user Ada only.
View Solution
DELETE FROM sessions
WHERE user_name = 'Ada';
| Expected output |
|---|
| Exactly one row is removed. |