Open In App

SQL Query to Update Columns Values With Column of Another Table

Last Updated : 23 Sep, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

In SQL update belongs to DDL (Data definition language). Using the UPDATE command we can update the present data in the table using the necessary queries. In this article, we see how to update column values with column values of another table using MSSQL as a server.

Syntax: For update query

UPDATE table_name 
SET old_value = new_value
WHERE condition 

Step 1: Creating a Database

We use the below command to create a database named GeeksforGeeks:

Query:

CREATE DATABASE GeeksforGeeks;

Output:

Step 2: Using the Database

To use the GeeksforGeeks database use the below command:

Query:

USE GeeksforGeeks;

Output:

Step 3: Creating two Tables

Create a table student_details with  3 columns and table Updated_CG with 2 columns using the following SQL queries:  

Query:

CREATE TABLE student_details(
  stu_id VARCHAR(8),
  stu_name VARCHAR(20),
  stu_cgpa DECIMAL(4,2) );

Query:

CREATE TABLE Updated_CG(
stu_id VARCHAR(20),
updated_cg DECIMAL(4,2));

Output:

Step 4: The query for Inserting rows into the Table

Inserting rows into student_details table using the following SQL query

Query:

INSERT INTO student_details VALUES('40001','PRADEEP',9.6);
INSERT INTO student_details VALUES('40002','ASHOK',8.2);
INSERT INTO student_details VALUES('40003','PAVAN KUMAR',7.6);
INSERT INTO student_details VALUES('40004','NIKHIL',8.2);
INSERT INTO student_details VALUES('40005','RAHUL',7.0);

Output:

Step 5: Inserting rows into Updated_CG using the following SQL query

Query:

INSERT INTO Updated_CG VALUES('40001',8.6);
INSERT INTO Updated_CG VALUES('40002',8.4);
INSERT INTO Updated_CG VALUES('40003',6.6);
INSERT INTO Updated_CG VALUES('40004',7.2);
INSERT INTO Updated_CG VALUES('40005',7.8);

Output:

 Step 6: Viewing the inserted data

Query:

SELECT * FROM student_details
SELECT * FROM Updated_CG

Output:

  • Query to update the old C.G.P.A in student_details table to new C.G.P.A   from the table Upadated_CG

Query:

UPDATE student_details 
SET stu_cgpa = (SELECT updated_cg 
FROM Updated_CG 
WHERE student_details.stu_id = Updated_CG.stu_id)

Output:

Step 7: Viewing the updated table

Query:

SELECT * FROM stuent_details

Output:


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads