In this guide, you’ll learn how to remove entries from a database table using SQL. Previously, we discussed how to insert new entries. Now, we will focus on the deletion process and how to verify that the intended rows have been removed.Documentation Index
Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
Use this file to discover all available pages before exploring further.
Basic SQL Delete Syntax
Recall that the basic syntax for deleting a row in SQL is:Example: Deleting a Single Product
Suppose you want to delete the product with an ID of 10. You can execute the following statements:Always use a unique identifier when deleting records to avoid accidentally removing multiple rows.
Handling Non-Existent Rows
There might be cases where the desired product has already been deleted. For instance, if product ID 10 does not exist and you need to delete product ID 11 instead, you would run:Using PostgreSQL’s RETURNING Clause
PostgreSQL provides a helpfulRETURNING clause that retrieves data from the row before it is deleted. This feature is useful when confirming exactly which data was removed. For example:
RETURNING clause, PostgreSQL returns the number of rows that were deleted:
Deleting Multiple Products
You might need to delete multiple rows based on a specific criterion. For example, to remove all products with an inventory of zero, use the following command:Always verify deletions by running a SELECT query after your DELETE operations to ensure that only the intended rows were removed.