Geek Culture
Published in

Geek Culture

What happens when you update Common Table Expressions (CTEs)?

Advance your SQL skills in CTEs

Photo by Elena Taranenko on Unsplash
  1. CTE based on a single base table
  2. CTE based on more than 1 base table and update affects 1 base table
  3. CTE based on more than 1 base table and update affects 2 base tables
Employee
Department
With EmpUpdateGender
as
( Select Id, Name, Gender from tblEmployee)
Update EmpUpdateGender Set Gender = 'Female' where Id = 20
Updated Employee Table: Alen’s gender is updated
With EmpUpdateGender as 
(Select Id, Name, Gender, DeptName
from tblEmployee
join tblDepartment
on tblDepartment.DeptId = tblEmployee.DepartmentId)
Update EmpUpdateGender set Gender = 'Male' where Id = 20
Update Employee Table: Alen’s gender is updated

CTE based on 2 base tables and update on 2 base tables

With EmpByDeptName as
(Select Id, Name, Gender, DeptName
from tblEmployee
join tblDepartment
on tblDepartment.DeptId = tblEmployee.DepartmentId)
Update EmpByDeptName set Gender = 'Female', DeptName='Engineering' where id = 20
ERROR !!!!!!
With EmpByDeptName as
(Select Id, Name, Gender, DeptName
from tblEmployee
join tblDepartment
on tblDepartment.DeptId = tblEmployee.DepartmentId)
Update EmpByDeptName set DeptName='Production' where id = 30
Data Comparison when DeptName is updated for Id=30

Conclusion

--

--

A new tech publication by Start it up (https://medium.com/swlh).

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store