A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.w3resource.com/PostgreSQL/snippets/postgres-delete-row.php below:

Website Navigation


Using the DELETE Command to Remove Rows in PostgreSQL

Using the DELETE Command to Remove Rows in PostgreSQLLast update on December 23 2024 07:39:10 (UTC/GMT +8 hours)

Deleting Rows in PostgreSQL

In PostgreSQL, the DELETE statement is used to remove rows from a table. This can be done conditionally (based on a WHERE clause) to delete specific rows, or without conditions to remove all rows in a table. Proper use of DELETE ensures that only the desired data is removed, while caution is advised to avoid unintentional data loss.

Syntax:

DELETE FROM table_name
WHERE condition;

Here:

Examples of Deleting Rows in PostgreSQL

Example 1: Delete a Specific Row

Suppose you want to delete a customer with a specific ID from the customers table:

Code:


DELETE FROM customers
WHERE customer_id = 101;

Explanation:

Example 2: Delete Multiple Rows Based on Condition

To delete all orders from the orders table where the order_status is 'cancelled':

Code:

DELETE FROM orders
WHERE order_status = 'cancelled';

Explanation:

Example 3: Delete All Rows from a Table

To remove all rows from the products table, you can use DELETE without a WHERE clause:

Code:

DELETE FROM products;

Explanation:

Note: Use caution when deleting all rows. It’s often safer to use TRUNCATE TABLE products;, which is faster for large datasets.

Using RETURNING with DELETE to Confirm Deleted Rows

PostgreSQL's RETURNING clause can be paired with DELETE to return details of deleted rows, useful for confirmation or logging:

Code:

DELETE FROM customers
WHERE customer_id = 101
RETURNING customer_id, customer_name;

Explanation:

Practical Tips for Using DELETE in PostgreSQL:

Summary:

The DELETE statement in PostgreSQL provides controlled row deletion from tables, whether for specific entries or entire datasets. Combined with the RETURNING clause, DELETE allows you to track deleted data. Understanding and using DELETE effectively is crucial to maintaining data integrity within your database.

All PostgreSQL Questions, Answers, and Code Snippets Collection.


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4