To delete specific rows from a table, you can utilize the WHERE clause in conjunction with the DELETE statement. The WHERE clause allows you to define conditions that must be met for a row to be deleted. This powerful combination empowers you to target and remove rows based on various criteria, such as a specific value or a range of values.
#Delete Rows
DELETE FROM table_name WHERE column1 = value1 AND column2 = value2 ...
If you need to remove all rows from a table, the TRUNCATE TABLE statement provides a more efficient alternative. Unlike the DELETE statement, which deletes rows one by one, the TRUNCATE TABLE statement removes all rows from the specified table in a single operation. This approach offers improved performance and is especially useful when dealing with large datasets.
Deleting Rows Exercise Solution
CREATE TABLE customers (first_name NOT NULL, last_name NOT NULL, age);
INSERT INTO customers (first_name, last_name, age)
VALUES ("John", "Doe", 23), ("Eric", "Smith", 26);
SELECT * FROM customers;
DELETE FROM customers WHERE first_name = "Eric";
SELECT * FROM customers;
When performing row deletion operations, it is crucial to ensure data safety and maintain consistency. SQL’s transactional capabilities allow you to wrap your DELETE statements within a transaction. This enables you to rollback the changes if necessary, ensuring that your data remains intact and protected during the deletion process.