This article explains how to update existing rows in a PostgreSQL database using the UPDATE command.
In this article, we explain how to update existing rows in a PostgreSQL database using the UPDATE command. Previously, we discussed how to insert new data and delete entries. Now, we will focus on updating records within the “products” table.
Always include the WHERE clause in your UPDATE statement to ensure that only the intended records are modified.
To immediately confirm the changes after an update, you can use the RETURNING keyword. For example, if you want to update the “is_sale” status of the product with an ID of 30 from false to true and then retrieve the updated record, use the following command:
Copy
Ask AI
UPDATE productsSET is_sale = trueWHERE id = 30RETURNING *;
This command updates the record with ID 30 and returns the complete updated row.
If you need to update multiple rows at once—such as setting the “is_sale” field to true for every product with an ID greater than 15—you can modify the WHERE clause accordingly:
Copy
Ask AI
UPDATE productsSET is_sale = trueWHERE id > 15RETURNING *;
This command applies the update to all records meeting the specified condition and returns all the updated rows.By following these steps, you can efficiently modify entries in a PostgreSQL database while ensuring data integrity and precision in your updates.For more insights on PostgreSQL and SQL commands, explore the PostgreSQL documentation.