PostgreSQL Update Data

PostgreSQL UPDATE Statement

The UPDATE statement is explicitly utilized to seamlessly modify existing records. It allows you to cleanly alter data inside a table without deleting the entire row.

It is an incredibly powerful, yet exceptionally dangerous, database command natively. A single, poorly constructed update query can destroy millions of records instantly.

Basic Syntax

The query natively begins with the UPDATE keyword followed by the targeted table. You use the SET keyword to explicitly define which column gets the brand new value.

Most critically, you must utilize the WHERE clause to specify exactly which row to change. Without a WHERE clause, the database will aggressively update every single row.

Basic Update Syntax:

UPDATE table_name
SET column1 = value1, column2 = value2
WHERE condition;

Updating a Single Row

The absolute safest way to confidently update a record is by targeting its Primary Key. Because the Primary Key is strictly unique, it guarantees only one row is ever touched.

Let's smoothly update the email address of a specific user with the ID of 5.

Targeted Update Example:

-- Safely update the email of user ID 5 exclusively
UPDATE Users
SET Email = 'new_email@example.com'
WHERE UserID = 5;

Updating Multiple Columns

You can efficiently update several columns inside a single row completely simultaneously. You simply separate the key-value pairs cleanly with a comma after the SET keyword.

This is highly efficient for entirely overhauling a user's profile in one quick network trip.

Multiple Column Update:

-- Update both the email and the username simultaneously safely
UPDATE Users
SET Email = 'john@example.com', Username = 'john_doe'
WHERE UserID = 5;

Updating with Calculations

The UPDATE statement is fully capable of evaluating mathematical calculations natively. You can reference the existing column value strictly to accurately compute the new value.

This is frequently utilized to forcefully increase prices or seamlessly increment view counts.

Calculated Update Example:

-- Increase the price of all 'Electronics' by 10 firmly
UPDATE Products
SET Price = Price + 10
WHERE Category = 'Electronics';

The Danger of Omitting WHERE

If you carelessly forget to type the WHERE clause, disaster strikes immediately. The query UPDATE Users SET Age = 30; will make every single user 30 years old.

Always double-check your WHERE conditions before executing any UPDATE command.

Summary

The UPDATE statement cleanly mutates old data safely into brand new data states. You utilize the SET keyword to elegantly map the fresh column values securely.

Never, ever forget the WHERE clause unless you truly want to overwrite the entire table.

Exercise

What terrible thing happens if you omit the WHERE clause in an UPDATE statement?