How to Update Records in Table from CTE in SQL
Last Updated : 19 Dec, 2024
Common Table Expressions (CTEs) in SQL is an important feature that provides a temporary result set that can be referred to within a SELECT, INSERT, UPDATE, or DELETE statement.
In this article, we will learn how to use CTEs to update records in SQL along with examples along with an explanation.
What is Common Table Expression (CTE )?
A CTE (Common Table Expression) in SQL is defined as a temporary result set or a "virtual table" that we can refer to within a SELECT, INSERT, UPDATE, or DELETE query. It is defined using the WITH keyword and helps to simplify complex queries by breaking them into smaller, more manageable parts.
Syntax:
WITH CTE_Name AS (
SELECT column1, column2, ...
FROM TableName
WHERE condition
)
UPDATE TableName
SET column = new_value
FROM TableName
JOIN CTE_Name
ON TableName.id = CTE_Name.id;
Example of Updating Records with a CTE
To understand how to update records with the CTE in SQL, We will consider one table called Employees to execute queries are shown below
CREATE TABLE Employees (
EmployeeID INT PRIMARY KEY,
Name VARCHAR(100),
Department VARCHAR(50),
Salary DECIMAL(10, 2)
);
INSERT INTO Employees (EmployeeID, Name, Department, Salary) VALUES
(1, 'Alice', 'HR', 50000),
(2, 'Bob', 'IT', 60000),
(3, 'Charlie', 'IT', 70000),
(4, 'David', 'HR', 55000);
Employees Table:
Employees TableExample 1: Increasing Salaries of IT Department Employees Using CTE
Suppose we want to increase the salary of IT department employees by 10%. The query using a CTE and UPDATE statement is shown below:
Query:
WITH IT_Employees AS (
SELECT EmployeeID, Salary
FROM Employees
WHERE Department = 'IT'
)
UPDATE e
SET e.Salary = e.Salary * 1.10
FROM Employees e
JOIN IT_Employees it
ON e.EmployeeID = it.EmployeeID;
Output:
OutputExplanation:
- This query first creates a temporary table IT_Employees that retrieves the EmployeeID and Salary of employees from the 'Employees' table who belong to the 'IT' department.
- Then, the UPDATE statement joins the original 'Employees' table with the IT_Employees table on the EmployeeID.
- For the matched records it updates the Salary by multiplying it by 1.10 and giving a 10% raise to all IT department employees.
Example 2: Updating Employee Department Based on Salary Using CTE
Let's find employees with salaries greater than $60,000 and update their department to 'Executive' in the Employees table.
Query:
WITH HighEarners AS (
SELECT EmployeeID
FROM Employees
WHERE Salary > 60000
)
UPDATE Employees
SET Department = 'Executive'
FROM Employees
JOIN HighEarners
ON Employees.EmployeeID = HighEarners.EmployeeID;
Output:
OutputExplanation:
- The WITH clause defines a CTE named HighEarners which selects the EmployeeID of employees earning more than $60,000.
- The UPDATE statement modifies the Department field of employees in the Employees table.
- A JOIN matches records from the Employees table with the HighEarners CTE to ensure only the relevant rows are updated.
Benefits of Using CTEs for Updates
- Improved Readability: CTEs make the query easier to read and maintain.
- Modular Design: Complex logic can be broken into smaller parts.
- Reusable Logic: The same CTE can be used in multiple operations within the same query.
- Focus on Target Rows: By isolating rows in the CTE, the UPDATE operation becomes more precise.
Conclusion
Overall, Using CTEs to update records in SQL is a powerful technique that enhances code clarity and maintainability. Whether you're applying complex update conditions or simply modifying a subset of rows, CTEs provide a structured and efficient approach. After reading whole article now you have clear understanding about how to use CTEs to update record in table very easily.
Similar Reads
How to Update a Column in a Table in SQL Server
In the database management area, updating columns in a table is a normal query and it is important software that ensures the accuracy and integrity of data. Whether we are making spelling corrections, editing or altering existing information, or being attentive to changing requirements, carrying out
4 min read
How to Update Top 100 Records in SQL?
As our systems get more complex and complex, there is often a need to update the underlying data to accommodate the evolution of the system. SQL provides a variety of ways to update the data so that the system developer can manipulate the data in whatever way necessary. In this article, we will be l
5 min read
How to Update Top 100 Records in PL/SQL?
In terms of database management, the ability to update specific subsets of data is crucial for maintaining system integrity and meeting user needs. In this article, we will understand two primary methods for updating top records. Using the ROWNUM function and Using the ORDER BY clause. Each method i
4 min read
How to Copy Rows from One Table to Another in SQL?
In SQL, copying rows from one table to another is a common operation that simplifies data migration and duplication tasks. Whether creating backup tables, transferring data for analysis, or setting up a new schema, the ability to efficiently replicate data across tables is invaluable. This operation
3 min read
How to Get Latest Updated Records in SQL?
SQL is a flexible and widely used relational database management system in the software industry. Retrieving the latest updated records is a critical operation for data analysis, debugging, or monitoring changes in a database. In this article, we will explain various SQL techniques to get the latest
4 min read
How to Update Top 100 Records in SQL Server
SQL Server is a Relational database Management system which is developed by Microsoft and is one of the most used databases in the world. It provides the developer with a set of rich functionalities to create tables, insert data in them, and then manipulate and play with them as and when necessary.
5 min read
How to Update a Table Data From Another Table in SQLite
SQLite is an embedded database that doesn't use a database like Oracle in the background to operate. The SQLite offers some features which are that it is a serverless architecture, quick, self-contained, reliable, full-featured SQL database engine. SQLite does not require any server to perform queri
3 min read
How to Update From One Table to Another Based on an ID Match in SQL
In SQL, updating data between tables is a common operation used to maintain data consistency and accuracy across related datasets. Whether we need to synchronize records, update fields, or correct discrepancies, SQL provides efficient methods to achieve this. In this article, we will explain how to
4 min read
SQL Query to Update All Rows in a Table
Updating all rows in a SQL table is a common task when we need to make changes to every record without specifying individual rows. This operation can be performed using the UPDATE statement combined with the SET clause, which allows for modifying values across all rows of a specified table. Understa
5 min read
SQL Query to Update All Columns in a Table
In SQL, sometimes we need to write a single query to update the values of all columns in a table. We will use the UPDATE keyword to achieve this. For this, we use a specific kind of query shown in the below demonstration. For this article, we will be using the Microsoft SQL Server as our database an
2 min read