Skip to main content

Common Table Expressions in SQL Server - CTE

A common table expression (CTE) can be thought of as a temporary result set that is defined within the execution scope of a single SELECT, INSERT, UPDATE, DELETE, or CREATE VIEW statement. A CTE is similar to a derived table in that it is not stored as an object and lasts only for the duration of the query. Unlike a derived table, a CTE can be self-referencing and can be referenced multiple times in the same query.


In simple layman's terms, CTE basically provides data at the runtime which may come from multiple tables. For e.g. if we have different tables like emp, dept, salgrade etc. then CTE can help in getting the resultset/dataset from multiple tables and form a temporary table. Then we can refer this table within other query any number of times. 


For e.g. if we want to display the following:


Deptno
Dname
Location
TotalCount
10
Hotel Management
Amritsar
6
20
Information Technology
Chicago
1
30
Finance
Ludhiana
2

Now in the above example there are two tables used i.e. 
a. Emp - which stores the information about the employees with their deptno.
b. Dept - which acts as the master of the Department information


The 'total count' column is generated from the 'Emp' table with the help of CTE and then referred in the other query to display dept wise information. The following is the syntax of the CTE that is used to generate the result as mentioned above.



With TotalNoOfEmployeesDeptWise(Deptno, TotalCount) as 
(
Select Deptno, COUNT(*) from Emp group by Deptno
)
Select Dept.Deptno, Dept.Dname, Dept.Location, x.TotalCount from Dept, TotalNoOfEmployeesDeptWise x
where X.Deptno=Dept.Deptno

So as you can see in the code, the first line, starting with 'With', the CTE starts and generates a runtime dataset.
And 'Select' is actual query that is referring to the CTE for displaying information.






Comments

Gagan Jagdev said…
Really a good article, thanks for sharing

Popular posts from this blog

How to use QueryExtenderControl in ASP.NET with LINQ

Queryextender control is a control that helps in doing actions like filtration, searching, sorting etc. on the LINQ Data source with few steps. In fact we don’t have to write any code with this. Screenshot given below is just an example that can easily be achieved through this control. In the above screenshot, we can see that there is a GridView Control that has been binded to a LINQData Source Control. And we have a DropDownlistBox that is also binded to another LINQData Source Control and displaying only grouped jobs. The GridView display all the employees who are matching the Job Parameter. This is done through QueryExtender Control. Also we can search for any name in the employee name's through Query Extender control. The code in the HTML goes like: < form id ="form1" runat ="server">     < div >         Select Job: < asp : DropDownList ID ="Job" runat ="server" DataSourceID ="LinqDataSource2...

Using GUID or UniqueIdentifiers in SQL Server

In order to differentiate between two rows, we normally use primary keys or identity values which may be same across two tables. In order to overcome this problem we can use a special type named "GUID" . Its a hexadecimal number (Base 16) and the advantage is  that they are unique across all databases and tables.  In SQL Server the same concept is implemented through UNIQUEIDENTIFIER  data type. In order to generate a new value, we use the NEWID() function. For e.g.  a. Creating a table that uses the UNIQUEIDENTIFIER datatype Create table Test ( Empno uniqueidentifier, Ename varchar(20) ) b. Inserting rows in the tables with the use of NEWID() function insert into Test values (newId(),'ABC') insert into Test values (newid(),'XYZ') insert into test values (newid(),'MNO') c. Selecting the rows from the table. Select * from test  Empno                             ...

How to Delete Record through Knex.

This post is all about of deleting records through KNEX ORM in Nodejs. The following code shows how to achieve this: knex("depts").where("deptno","50").del() .then(function (count) {     console.log(count); }) .finally(function () {     knex.destroy(); }); The above code deletes a record from a table "Depts" where Deptno = 50. It has a "then" Promise attached that will show how many records were deleted with this command. Also "finally" is the method that will always execute and will close the KNEX connection. Happy Coding !!!