How to Update Table Rows in PostgreSQL Using Subquery?
Last Updated :
13 Feb, 2024
PostgreSQL is a general-purpose object-relational database management system and is open-source. It ensures data integrity features like constraints, transactions and foreign key support. In this article, We will understand How to update table rows in PostgreSQL using subquery using various methods, examples and so on.
Introduction to Update Statement in SQL
The UPDATE statement is used to modify the records of the table. With the help of the UPDATE Statement, we can easily update the already existing data in the table.
Basic Syntax for the UPDATE statement:
UPDATE table_name
SET column1 = value1, column2 = value2, ...
[WHERE condition];
Explanation:
- table_name is the name of table from which records will updated.
- column1, column2, etc are the columns within the table that will updated.
- value1, value2, etc are the new values to be assigned to the respective columns.
- condition is the condition that we used to update table
Setting Up Environment
Let's create table and adding some records into table. The below query creates two tables and inserts records in them:
CREATE TABLE test1
(
id INT,
name VARCHAR(20),
age INT
);
INSERT INTO test1 VALUES(1, 'Alex', 20);
INSERT INTO test1 VALUES(4, 'Jane', 34);
INSERT INTO test1 VALUES(9, 'Tyler', 11);
CREATE TABLE test2
(
id INT,
name VARCHAR(20),
age INT
);
INSERT INTO test2 VALUES(1, 'Austin', 25);
INSERT INTO test2 VALUES(5, 'Jesse', 34);
INSERT INTO test2 VALUES(9, 'Tyler', 23);
INSERT INTO test2 VALUES(3, 'Smith', 11);
Our table test1 after some data inserted into it look like:
OutputOur table test2 after some data inserted into it look like:
OutputUpdate Rows Using Subquery
We will use a UPDATE statement with a subquery to update tables based on some logic. The subquery allows us to interact with other tables during the update statement.
Example 1: Updating Based on Subquery Results
The following query updates the test1 table records which are present in test2 table with the values of the test2 table:
UPDATE test1
SET
name=t.name,
age=t.age
FROM (
SELECT * FROM test2
) t
WHERE test1.id=t.id;
Output:
OutputExplanation: As we can see the records with ids 1 and 9 were updated in the table.
Example 2: Updating with JOIN Subquery Result
We will update the values of test1 using the value obtained by performing a join between test1 and test2 in the subquery. We take the least of the two ages in both the tables and add 2 to it. It defines the new age for the person.
UPDATE test1
SET
name=t.name,
age=t.age
FROM (
SELECT test2.id, test2.name, LEAST(test1.age, test2.age)+2 AS age FROM test2
JOIN test1
ON test1.id=test2.id
) t
WHERE test1.id=t.id;
Output:
OutputExplanation: As we can see the records for 1 and 9 are updated.
Example 3: Updating with Aggregated Subquery Result
The following query updates the age of all the employees in test1 table to be the sum of all the ages in test2 value.
UPDATE test1
SET
age=t.age
FROM (
SELECT SUM(age) as age FROM test2
);
Output:
OutputExplanation: As we can see the age for all records has been updated to 93.
Technical Example
Let's create some tables and insert some record into it for queries.
-- create department table
CREATE TABLE department (
id INT PRIMARY KEY NOT NULL,
name VARCHAR(100) NOT NULL
);
-- insert data
INSERT INTO department VALUES
(1, 'Engineering'),
(2, 'Sales'),
(3, 'Marketing');
Output:
OutputThe following query creates a employee table and inserts some records in it.
-- create employee table
CREATE TABLE employee (
id INT PRIMARY KEY NOT NULL,
name VARCHAR(100) NOT NULL,
deptId INT NOT NULL
);
-- insert data
INSERT INTO employee VALUES
(1, 'Aayush', 1),
(2, 'Dhruv', 2),
(3, 'Sid', 1),
(4, 'Ankit', 3),
(5, 'Yash', 3),
(6, 'Sakshi', 2);
Output:
OutputThe following query creates a salaries table and inserts some records in it.
-- create salary table
CREATE TABLE salary
(
id INT PRIMARY KEY NOT NULL ,
empId INT NOT NULL,
amount NUMERIC(10, 2) NOT NULL
);
-- insert data
INSERT INTO salary VALUES
(1, 1, 50000.00),
(2, 3, 55000.00),
(3, 2, 60000.00),
(4, 4, 52000.00),
(5, 6, 48000.00),
(6, 5, 45000.00);
Output:
OutputExplanation: Our table has been created above.
We will update the salary of all the employees of Engineering department by 10%. We fetch the employee id for all the employees of Engineering department using a subquery and use that result in the UPDATE statement to update the salary.
UPDATE salary
SET amount = amount * 1.1
WHERE empId IN (
SELECT id
FROM employee
WHERE deptId = (
SELECT id
FROM department
WHERE name = 'Engineering'
)
);
Output:
OutputExplanation: As we can see the salary of employee 1 whose name Aayush is increased from 50000 to 55000 and that of employee 3 whose name is Sid is increased from 55000 to 60500.
Let's update the salary of each employee to average salary of their department.
UPDATE salary s
SET amount=t.avg_sal
FROM (
SELECT e.id, t.avg_sal FROM (
SELECT d.id, AVG(s.amount) AS avg_sal
FROM employee e, department d, salary s
WHERE e.deptId=d.id AND e.id=s.empId
GROUP BY d.id
) t, employee e
WHERE e.deptId=t.id
) t
WHERE s.empId=t.id;
Output:
OutputExplanation: We can see the salary of each employee is updated in the salary table. We have write a two subqueries in the update statement and in the inner subquery we calculate the average salary for each department. In the outer subquery we select the average department salary for each employee.
Conclusion
In this article we covered how we can update table records in PostgreSQL using subquery. We understood how powerful using subquery alongside update statement is and can allow us to modify data in complex fashion.
Similar Reads
SQL Tutorial Structured Query Language (SQL) is the standard language used to interact with relational databases. Whether you want to create, delete, update or read data, SQL provides the structure and commands to perform these operations. SQL is widely supported across various database systems like MySQL, Oracl
8 min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
SQL Commands | DDL, DQL, DML, DCL and TCL Commands SQL commands are crucial for managing databases effectively. These commands are divided into categories such as Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), Data Query Language (DQL), and Transaction Control Language (TCL). In this article, we will e
7 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Normal Forms in DBMS In the world of database management, Normal Forms are important for ensuring that data is structured logically, reducing redundancy, and maintaining data integrity. When working with databases, especially relational databases, it is critical to follow normalization techniques that help to eliminate
7 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
SQL Query Interview Questions SQL or Structured Query Language, is the standard language for managing and manipulating relational databases such as MySQL, Oracle, and PostgreSQL. It serves as a powerful tool for efficiently handling data whether retrieving specific data points, performing complex analysis, or modifying database
15+ min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
Polymorphism in Java Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read