A RetroSearch Logo

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

Search Query:

Showing content from https://www.w3resource.com/PostgreSQL/snippets/postgresql-update-from-select.php below:

Website Navigation


Understanding PostgreSQL Update from Select Queries

Understanding PostgreSQL Update from Select QueriesLast update on December 31 2024 05:34:20 (UTC/GMT +8 hours)

PostgreSQL Update from Select: Synchronizing Table Data

PostgreSQL allows you to update rows in a table using data retrieved from another table or query. This is achieved through the UPDATE...FROM syntax, which is useful for synchronizing data between tables or for batch updates based on specific criteria.

This guide will explore the syntax, examples, and a step-by-step explanation of how to use UPDATE FROM SELECT in PostgreSQL effectively.

Syntax:

UPDATE target_table
SET column1 = subquery.column1,
    column2 = subquery.column2
FROM (
    SELECT source_column1, source_column2
    FROM source_table
    WHERE conditions
) AS subquery
WHERE target_table.matching_column = subquery.matching_column;

Examples and Code:

1. Basic Update from Select

Code:

-- Create a sample target table
CREATE TABLE employees (
    id SERIAL PRIMARY KEY,
    name TEXT,
    department_id INT,
    salary NUMERIC
);

-- Insert sample data into employees
INSERT INTO employees (name, department_id, salary)
VALUES 
('Alice', 1, 50000),
('Bob', 2, 55000),
('Charlie', 3, 60000);

-- Create a source table with updated data
CREATE TABLE departments (
    id SERIAL PRIMARY KEY,
    department_name TEXT,
    bonus_percent NUMERIC
);

-- Insert sample data into departments
INSERT INTO departments (id, department_name, bonus_percent)
VALUES 
(1, 'HR', 0.10),
(2, 'Engineering', 0.15),
(3, 'Sales', 0.12);

-- Update employees salary based on bonus percentage from departments
UPDATE employees
SET salary = salary + (salary * departments.bonus_percent)
FROM departments
WHERE employees.department_id = departments.id;

Explanation:

2. Using a Subquery

Code:

-- Adjust salary using a subquery
UPDATE employees
SET salary = salary + (
    SELECT salary * bonus_percent 
    FROM departments 
    WHERE employees.department_id = departments.id
);

Explanation:

3. Partial Update with Condition

Code:

-- Only update employees in the Engineering department
UPDATE employees
SET salary = salary + (salary * departments.bonus_percent)
FROM departments	
WHERE employees.department_id = departments.id
AND departments.department_name = 'Engineering';

Explanation:

Explanation

Use Cases

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