Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Databases
  • SQL
  • MySQL
  • PostgreSQL
  • PL/SQL
  • MongoDB
  • SQL Cheat Sheet
  • SQL Interview Questions
  • MySQL Interview Questions
  • PL/SQL Interview Questions
  • Learn SQL and Database
Open In App
Next Article:
How to Update a Column in a Table in SQL Server
Next article icon

How to Update Records in Table from CTE in SQL

Last Updated : 19 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

employeesTable
Employees Table

Example 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:

Example1
Output

Explanation:

  • 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:

Example2
Output

Explanation:

  • 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.


Next Article
How to Update a Column in a Table in SQL Server

S

satyamguptboxl
Improve
Article Tags :
  • SQL
  • Databases

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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences