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 Table Rows Using Subquery in MySQL
Next article icon

How to Update Table Rows in SQL Server using Subquery ?

Last Updated : 11 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Updating table rows in SQL Server using a subquery is a common operation that allows us to modify records based on values derived from another table or query.

In this article, we will explain how to update table rows in SQL Server using subquery with the help of examples.

Updating Table Rows Using a Subquery in SQL Server

A subquery allows us to perform updates based on related data from another table, making our operations more dynamic. We can use the UPDATE statement along with a subquery to update rows in a table based on the result of another query.

The subquery typically returns a value that is used to set the value of a column in the target table. Let’s break down the concept using a simple example.

Syntax:

UPDATE target_table
SET target_column = (
SELECT subquery_column
FROM subquery_table
WHERE subquery_condition
)
WHERE target_condition;

Example to Update Table Rows in SQL Server using Subquery

Let's consider two tables: Employees and Departments. We want to update the salary of employees based on their department's budget.

Employees Table

Query:

CREATE TABLE Employees (
EmployeeID INT PRIMARY KEY,
EmployeeName VARCHAR(50),
DepartmentID INT,
Salary DECIMAL(10, 2)
);

INSERT INTO Employees (EmployeeID, EmployeeName, DepartmentID, Salary) VALUES
(1, 'Alice', 101, 50000),
(2, 'Bob', 102, 60000),
(3, 'Charlie', 101, 55000
);

Output:

EmployeeIDEmployeeNameDepartmentIDSalary
1Alice10150000
2Bob10260000
3Charlie10155000

Departments Table:

Query:

CREATE TABLE Departments (
DepartmentID INT PRIMARY KEY,
DepartmentName VARCHAR(50),
Budget DECIMAL(10, 2)
);

INSERT INTO Departments (DepartmentID, DepartmentName, Budget) VALUES
(101, 'HR', 80000),
(102, 'IT', 50000);

Output:

DepartmentIDDepartmentNameBudget
101HR80000
102IT50000

Example Scenario 1: Updating Employee Salaries

We want to increase the salary of employees in the HR department (DepartmentID 101) by 10% if the department's budget exceeds 75,000.

Query:

UPDATE Employees
SET Salary = Salary * 1.10 -- Increase salary by 10%
WHERE DepartmentID = 101 AND
(SELECT Budget
FROM Departments
WHERE DepartmentID = Employees.DepartmentID) > 75000;

Output:

EmployeeIDEmployeeNameDepartmentIDSalary
1Alice10155000
2Bob10260000
3Charlie10160500

Explanation:

  • UPDATE Employees: This part specifies that we are updating the Employees table.
  • SET Salary = Salary * 1.10: This sets the new salary to be 10% more than the current salary.
  • WHERE DepartmentID = 101: This condition filters the rows in the Employees table to only those in the HR department.
  • Subquery: The subquery retrieves the Budget from the Departments table for the department of the employee being updated. The condition checks if the budget exceeds 75000.

Conclusion

Using subqueries to update rows in SQL Server allows for flexible and powerful data manipulation. We can conditionally update records based on related data in other tables, making SQL operations more dynamic.

With proper understanding and application of subqueries, we can improve the effectiveness of SQL queries and improve data management tasks in your applications.


Next Article
How to Update Table Rows Using Subquery in MySQL

M

mishraaabcf9
Improve
Article Tags :
  • SQL Server
  • Databases

Similar Reads

  • How to Update Table Rows in SQLite Using Subquery
    SQLite is a lightweight, serverless RDBMS that is used to store and manipulate the data in the database in relational or tabular form. It can run on various operating systems like Windows, macOS, Linux and mobile operating systems like Android and iOS. SQLite is designed for single-user access. Mult
    4 min read
  • How to Update Table Rows in PL/SQL Using Subquery?
    Updating table rows in PL/SQL via subqueries allows precise data modifications based on specific conditions. By integrating subqueries within the UPDATE statement, rows can be selectively targeted for updates, enhancing data management efficiency. This article explores the concept of updating rows i
    4 min read
  • How to Update Table Rows in PostgreSQL Using Subquery?
    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,
    5 min read
  • How to Update Table Rows Using Subquery in MySQL
    Updating table rows using subqueries in MySQL enables precise modifications based on specific conditions or values from other tables. This technique leverages subqueries within the SET or WHERE clauses of the UPDATE statement, allowing dynamic and context-specific updates. This guide covers the synt
    5 min read
  • How to Update Two Tables in One Statement in SQL Server?
    To update two tables in one statement in SQL Server, use the BEGIN TRANSACTION clause and the COMMIT clause. The individual UPDATE clauses are written in between the former ones to execute both updates simultaneously. Here, we will learn how to update two tables in a single statement in SQL Server.
    3 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 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 Multiple Records Using One Query in SQL Server?
    To update multiple records in the SQL server, use the UPDATE Statement. Using the SQL UPDATE statement with the WHERE clause users can update multiple records in the table based on some condition. There can be two cases in this situation: Table of Content Update Multiple Records Based on One Conditi
    4 min read
  • How to Perform Batch Updates in SQL Server
    The Update statement is a SQL keyword to update data in the database. We can update all the rows in the database or some values with the help of conditions. The update is a SQL keyword, and it falls under Data Manipulation Language (DML), as the name suggests it is used to manipulate the data. Updat
    5 min read
  • How to Use the IN Operator With a SubQuery?
    The IN Operator in SQL allows to specifies multiple values in WHERE clause, it can help you to easily test if an expression matches any value in the list of values. The use of IN Operator reduces the need for multiple OR conditions in statements like SELECT, INSERT, UPDATE, and DELETE. Sub Queries:T
    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