Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 29

Difference between Primary Key and Unique key?

Primary Key Foreign Key


Primary key uniquely identify a record in the Foreign key is a field in the table that is primary key
table in another table

Primary Key can't accept null values. Foreign key can accept multiple null value.

We can have only one Primary key in a table. We can have more than one foreign key in a table.
By default, Primary key is clustered index and Foreign key do not automatically create an index,
data in the database table is physically organized clustered or non-clustered. You can manually create
in the sequence of clustered index. an index on foreign key.

Difference between Union and Union all?

Union Union ALL


union always returns the distinct rows. It do not give union all always returns all the rows ,it do not
duplicates remove duplicate rows.
this is slower,becz union must perform distinct sort
operation to remove the duplicate valuefrom the result
set This is faster
cannot use union for text data type columns becz text
data type cannot be used as an operand to union
,intersect and except operators becz it s not can use union all for text data type columns(as
comparable(it throws an run time error) it returns all the rows of both tables)

Difference between Char and Varchar?

CHAR VARCHAR
used to store character string value of fixed Used to store alphanumeric data of variable
length length.

The length varies from 0 to 255. The length varies from 0 to 65,535.
Uses static memory allocation. Uses dynamic memory allocation.
Char should be used when the length of the Varchar should be used only when the length of
variable is known. the variable is not known

It only accepts characters. It accepts both characters and numbers


It’s 50 percent faster than Varchar. It’s slower than Char.

DIFFERENCE between Varchar and Nvarchar?


VARCHAR NVARCHAR
Nvarchar stores UNICODE data.If you have
Varchar stores ASCII data and should be your data requirements to store UNICODE or multilingual
type of choice for normal use. data(eg:Arabian,German), nvarchar is the choice
varchar uses 1. nvarchar uses 2 bytes per character

Varchar supports up to 8000 characters in the field Nvarchar only supports up to 4000 characters
definition

Difference between Function and Stored Procedure?

Function Stored Procedure


in Stored Procedure it is optional. Even a
Function must return a value procedure can return zero or n values.
Procedures can have input or output
Functions can have only input parameters parameters.
Functions can be called from Procedure Procedures cannot be called from a Function
Procedure allows SELECT as well as
Function allows only SELECT statement in it DML(INSERT/UPDATE/DELETE) statement in it
Exception can be handled by try-catch block in
try-catch block cannot be used in a Function a Procedure
Stored Procedures cannot be used in the SQL
statements anywhere in the
Function can be WHERE/HAVING/SELECT section

Difference between Having and where clause?

Having where
HAVING clause can only be used with SELECT
query. Means if you want perform INSERT, UPDATE We can use WHERE clause with SELECT,
and DELETE clause it will retuns an error. INSERT, UPDATE and DELETE clause
Example "Update Mas_Employee Set Salary = 1500 Example it works fine for "Update
Having Id =1" Query will be generated error like Mas_Employee Set Salary = 1500 WHERE Id
"Incorrect syntax near the keyword 'HAVING'. ". =1".
WHERE clause is used for filtering rows and it
HAVING clause is used to filter groups in SQL. applies on each and every row.
WHERE clause is used before GROUP BY
HAVING clause is used after GROUP BY clause. clause.
We can't use aggregate functions in the where
clause unless it is in a sub query contained in a
We can use aggregate function in HAVING clause. HAVING clause.

Difference Between In and Between?


Between In
The BETWEEN operator is used to fetch rows based on a range of The IN operator is used to check for values contained
values. in specific sets.
Example SELECT * FROM Students
Example SELECT * FROM Students WHERE ROLL_NO IN (20,21,23);
WHERE ROLL_NO BETWEEN 20 AND 30; This query will select all those rows from the table
This query will select all those rows from the table Students Students where the value of the field ROLL_NO is
where the value of the field ROLL_NO lies between 20 and 30. either 20 or 21 or 23.

Difference between View and Materialized View:

View Materialized View


In Views query result is not stored in the disk or Materialized view allow to store the query result in disk or
database table.
but in case of Materialized view we need to refresh the view
In case of View we always get latest data for getting latest data.
Performance of View is less than Materialized view.  
In case of Materialized view we need an extra trigger or
this is not required for views in the database. some automatic method so that we can keep MV refreshed

Difference Between Stored Procedure and View:

View Stored Procedure


views do not accept parameters A stored procedure accepts parameters
a view can contain only one single select
query. A stored procedure can contain several statements
Using stored procedures, one or more tables can be
using view no table can be modified. modified
A view can be used within a stored procedure a stored procedure cannot be used inside a view

Difference between Triggers and Stored Procedures

Triggers Stored Procedure


Event and actions needs to be identified at at the time of creating a stored procedure, it is not
the time of creating a trigger important.
Trigger can be run automatically when any
event occurs stored procedures have to be run manually.
a trigger cannot be called in a stored
procedure. A stored procedure can be called within a trigger
Triggers execute implicitly stored procedures execute explicitly.
A trigger cannot be called from front end a stored procedure can be
Aggregate functions:
 Aggregate functions perform a calculation on set of values and returns a singl evalue.
 Aggregate functions ignore null values.
 Aggregate functions are often used with group by clause of select statement.

AVg,MIN,MAX,COUNT,SUM,

Avg :calculates the avg of set f values.

Count: counts rows in a specified table or view.

Min :gets min value in a set of values.

Max: gets max value in a set of values.

Sum: calculates the sum values.

Examples:
1.
1 SELECT
2     categoryid, SUM(unitsinstock)
3 FROM
4     products
5 GROUP BY categoryid;

2.
SELECT
    categoryid, AVG(unitsinstock)
3
FROM
4
    products
5
GROUP BY categoryid;

3.
SELECT
    COUNT(*)
FROM
    products;

4.
SELECT
    MAX(unitsinstock)
FROM
    products;

Scalar Functions:
rand(10): This will generate random number of 10 characters.
upper('dotnet')

round(17.56719,3): This will round off the given number to 3 places of decimal means 17.567

lower('DOTNET')

ltrim(' dotnet')

convert(int, 15.56): This will convert the given float value to integer means 15.

Substr ():This will extract characters from a text field

Ananlytic Functions:

Lead
Lag

Set operators in SQL:


UNION
UNIONALL
MINUS
INTERSECT

JOINS:
INNER JOIN ,LEFT JOIN ,RIGHT JOIN,CARTESION PRODUCT,OUTER JOIN
EMP

Id name FN LN deptid
1 ram abc a 1
2 sham xyz b 1
3 chai hdy s 2
4 poo sud p 3
5 tanu dhjc d 3
6 vee dbhh y 3
7 bari jcjc l 1
8 sita hdh n NULL

DEPT
deptnam
Id e
1 IT
2 EC
3 mech
4 civil
5 bio
6 chem

INNER JOIN:
The join that displays only the rows that have a match in both the joined tables is known as inner
join.
select * from emp a inner join dept b
on a.deptid=b.id
deptnam
Id name FN LN deptid id e
1 ram abc a 1 1 IT
2 sham xyz b 1 1 IT
3 chai hdy s 2 2 EC
4 poo sud p 3 3 mech
5 tanu dhjc d 3 3 mech
6 vee dbhh y 3 3 mech
7 bari jcjc l 1 1 IT

LEFT JOIN:
Left join displays all the rows from first table and matched rows from second table like that.
select * from emp a left join dept b
on a.deptid=b.id

deptnam
Id name FN LN deptid id e
1 ram abc a 1 1 IT
2 sham xyz b 1 1 IT
3 chai hdy s 2 2 EC
4 poo sud p 3 3 mech
5 tanu dhjc d 3 3 mech
6 vee dbhh y 3 3 mech
7 bari jcjc l 1 1 IT
8 sita hdh n NULL NULL NULL

Right Join:

Right outer join displays all the rows of second table and matched rows from first table like that.

select * from emp a right join dept b


on a.deptid=b.id

deptnam
Id name FN LN deptid id e
1 ram abc a 1 1 IT
2 sham xyz b 1 1 IT
7 bari jcjc l 1 1 IT
3 chai hdy s 2 2 EC
4 poo sud p 3 3 mech
5 tanu dhjc d 3 3 mech
6 vee dbhh y 3 3 mech
NULL NULL NULL NULL NULL 4 civil
NULL NULL NULL NULL NULL 5 bio
NULL NULL NULL NULL NULL 6 chem

Full outer join:

Full outer join returns all the rows from both tables whether it has been matched or not.
select * from emp a FULL OUTER JOIN dept b
on a.deptid=b.id

deptnam
Id name FN LN deptid id e
1 ram abc a 1 1 IT
2 sham xyz b 1 1 IT
3 chai hdy s 2 2 EC
4 poo sud p 3 3 mech
5 tanu dhjc d 3 3 mech
6 vee dbhh y 3 3 mech
7 bari jcjc l 1 1 IT
8 sita hdh n NULL NULL NULL
NULL NULL NULL NULL NULL 4 civil
NULL NULL NULL NULL NULL 5 bio
NULL NULL NULL NULL NULL 6 chem
CROSS join:

A cross join that produces Cartesian product of the tables that are involved in the join. The size of a
Cartesian product is the number of the rows in the first table multiplied by the number of rows in the
second table like this.
select * from emp a cross join dept b

deptnam
Id name FN LN deptid id e
1 ram abc a 1 1 IT
2 sham xyz b 1 1 IT
3 chai hdy s 2 1 IT
4 poo sud p 3 1 IT
5 tanu dhjc d 3 1 IT
6 vee dbhh y 3 1 IT
7 bari jcjc l 1 1 IT
8 sita hdh n NULL 1 IT
1 ram abc a 1 2 EC
2 sham xyz b 1 2 EC
3 chai hdy s 2 2 EC
4 poo sud p 3 2 EC
5 tanu dhjc d 3 2 EC
6 vee dbhh y 3 2 EC
7 bari jcjc l 1 2 EC
8 sita hdh n NULL 2 EC
1 ram abc a 1 3 mech
2 sham xyz b 1 3 mech
3 chai hdy s 2 3 mech
4 poo sud p 3 3 mech
5 tanu dhjc d 3 3 mech
6 vee dbhh y 3 3 mech
7 bari jcjc l 1 3 mech
8 sita hdh n NULL 3 mech
1 ram abc a 1 4 civil
2 sham xyz b 1 4 civil
3 chai hdy s 2 4 civil
4 poo sud p 3 4 civil
5 tanu dhjc d 3 4 civil
6 vee dbhh y 3 4 civil
7 bari jcjc l 1 4 civil
8 sita hdh n NULL 4 civil
1 ram abc a 1 5 bio
2 sham xyz b 1 5 bio
3 chai hdy s 2 5 bio
4 poo sud p 3 5 bio
5 tanu dhjc d 3 5 bio
6 vee dbhh y 3 5 bio
7 bari jcjc l 1 5 bio
8 sita hdh n NULL 5 bio
1 ram abc a 1 6 chem
2 sham xyz b 1 6 chem
3 chai hdy s 2 6 chem
4 poo sud p 3 6 chem
5 tanu dhjc d 3 6 chem
6 vee dbhh y 3 6 chem
7 bari jcjc l 1 6 chem
8 sita hdh n NULL 6 chem

Self join:

Joining the table itself called self join. Self join is used to retrieve the records having some relation or
similarity with other records in the same table. Here, we need to use aliases for the same table to set
a self join between single table and retrieve records satisfying the condition in where clause.

CTE Function:

COALESCE:
Returns the first non null value.
Middlenam
Id Firstname e Lastname
1 sam null Null
2 null todd tanzan
3 null null Sara
4 ben parker Null
5 james nick nancy

Select id, coalesce (Firstname, middlename,lastname) as Name From Employee;

Output  
Id Name
1 Sam
2 Todd
3 Sara
4 Ben
5 James

Difference between isnull and Coalesce function?


Both ISNULL and Coalesce gives the first non-null value but,
ISNULL can have only 2 parameters, whereas coalesce can have multiple arguments i.e.
columns.
Example:
Table: Person

FirstNam
e Surname PetName
Prasad Null Null
Raju Null Null
Null Kulkarni Null
Null Shinde Null
Null Null Cherry

In this it has 3 columns, if you are using ISNULL


Select isnull (Firstname, Surname) as Name from Person
Output:

Name
Prasad
Raju
Kulkarni
Shinde

Only for 2 columns it can be used, if you try to give Petname then an error is thrown.
So for using multiple columns use Coalesce function.
Select coalesce (Firstname, Surname, Petname) as Name from Person
Output:

Name
Prasad
Raju
Kulkarni
Shinde
Cherry

NVL: Null Value Logic.

This function allows you to replace a NULL value with another Value.

It is helpful, when there is no data for a particular column but you want to display something else.

Example 1:

A common concept in database tables is to store a start and end date for a record, which is used to track
when a record is effective for

In some cases, the end date is set to NULL if there is no end date or if it is the active record.

Table Name: customer_history

CUSTOME CUSTOMER_ STAT START_D END_D


R_ID NAME US ATE ATE

Prosp
1 ABC 1-Jan-17 10-Jan-17
ect

2 ABC Signed 11-Jan-17 (null)

3 DJ Signed 1-Jan-17 (null)

In
4 WXY Progre 26-Feb-17 (null)
ss

5 FED Signed 21-Dec-17 3-Feb-17

6 FED (null) 4-Feb-17 15-Feb-17

In the above table we don’t want to display a null or empty value, so we have to use a NVL function.

We first need to work out what value we want to display. This could be a static date (i.e., 31-DEC-9999).

Query:

Select CUSTOMER_ID,

CUSTOMER_NAME,

STATUS,
START_DATE,

NVL (END_DATE, ‘31-DEC-9999’)

from customer_history;

Result:

CUSTOMER_ CUSTOMER_NA STAT START_DA NVL(END_DATE,'


ID ME US TE 31-DEC-9999')

Prospec
1 ABC 1-Jan-17 10-Jan-17
t

2 ABC Signed 11-Jan-17 31-Dec-99

3 DJ Signed 1-Jan-17 31-Dec-99

In
4 WXY Progres 26-Feb-17 31-Dec-99
s

5 FED Signed 21-Dec-17 3-Feb-17

6 FED (null) 4-Feb-17 15-Feb-17

So the NVL function can be used to translate a NULL date value to something else.

Example 2:

If there is a missing data that should be populated, if you are loading a data from one table into another
table and cannot use NULL values for some reason.

In the above table status column cannot be null. And the business rule specifies that we need a value for
status, but we can’t update the table.

So we can use NVL function here.

Query:

Select CUSTOMER_ID,

CUSTOMER_NAME,

NVL (STATUS,’Unknown’) as status,

START_DATE,
END_DATE

From customer_history;

Result:
CUSTOMER CUSTOMER_NA STAT START_DA END_DA
_ID ME US TE TE

Prospec
1 ABC 1-Jan-17 10-Jan-17
t

2 ABC Signed 11-Jan-17 (null)

3 DJ Signed 1-Jan-17 (null)

In
4 WXY Progres 26-Feb-17 (null)
s

5 FED Signed 21-Dec-17 3-Feb-17

Unkno
6 FED 4-Feb-17 15-Feb-17
wn

This now satisfies the business rule that says the status column cannot be null in your new table.

SQL CONSTRAINTS:
Constraints are used to set the rules for all records in the table. If any constraints get violated then it can
abort the action that caused it.

Constraints are defined while creating the database itself with CREATE TABLE statement or even after
the table is created once with ALTER TABLE statement.

There are 5 major constraints are used in SQL, such as

NOT NULL: That indicates that the column must have some value and cannot be left null.
CREATE TABLE Persons (
    ID int NOT NULL,
    LastName varchar(255) NOT NULL,
    FirstName varchar(255) NOT NULL,
    Age int
);

UNIQUE: This constraint is used to ensure that each row and column has unique value and no value is
being repeated in any other row or column.
CREATE TABLE Persons (
    ID int NOT NULL UNIQUE,
    LastName varchar(255) NOT NULL,
    FirstName varchar(255),
    Age int
);

PRIMARY KEY: This constraint is used in association with NOT NULL and UNIQUE constraints such as on
one or the combination of more than one columns to identify the particular record with a unique
identity.
CREATE TABLE Persons (
    ID int NOT NULL PRIMARY KEY,
    LastName varchar(255) NOT NULL,
    FirstName varchar(255),
    Age int
);

FOREIGN KEY: It is used to ensure the referential integrity of data in the table and also matches the
value in one table with another using Primary Key.
CREATE TABLE Orders (
    OrderID int NOT NULL PRIMARY KEY,
    OrderNumber int NOT NULL,
    PersonID int FOREIGN KEY REFERENCES Persons(PersonID)
);

CHECK: It is used to ensure whether the value in columns fulfills the specified condition
CREATE TABLE Persons (
    ID int NOT NULL,
    LastName varchar(255) NOT NULL,
    FirstName varchar(255),
    Age int CHECK (Age>=18)
);

RANK:
customer

FN LN Education Occupation Income


John yang Bachelor Professional 90000
Rob johnson Bachelor Management 80000
Christy zhu Bachelor Professional 80000
John miller masters degree management 80000
John ruiz Bachelor Professional 70000
Christy carlson graduate degree management 70000
skilled
Rob hung high school manual 60000
skilled
Ruben thores partial college manual 50000
Christy mehta partial high clerical 50000
school
partial high
Rob yang school clerical 45000

Syntax:
rank() over (partition by order by clause)

Example 1:

select * ,rank() over (order by income desc) as rank from customer

FN LN Education Occupation Income rank


John yang Bachelor Professional 90000 1
Managemen
Rob johnson Bachelor t 80000 2
Christy zhu Bachelor Professional 80000 2
managemen
John miller masters degree t 80000 2
John ruiz Bachelor Professional 70000 5
managemen
Christy carlson graduate degree t 70000 5
skilled
Rob hung high school manual 60000 7
skilled
Ruben thores partial college manual 50000 8
partial high
Christy mehta school clerical 50000 8
partial high
Rob yang school clerical 45000 10

Example 2:
select * ,rank() over (partition by Occupation order by income desc) as rank from
customer
FN LN Education Occupation Income rank
partial high
Christy mehta school clerical 50000 1
partial high
Rob yang school clerical 45000 2
Managemen
Rob johnson Bachelor t 80000 1
managemen
John miller masters degree t 80000 1
managemen
Christy carlson graduate degree t 70000 3
John yang Bachelor Professional 90000 1
Christy zhu Bachelor Professional 80000 2
John ruiz Bachelor Professional 70000 3
skilled
Rob hung high school manual 60000 1
skilled
Ruben thores partial college manual 50000 2

Dense Rank:It will assign the rank number to each record present in a partition without
skipping the rank numbers

select * ,dense_rank() over (order by income desc) as rank from customer

FN LN Education Occupation Income rank


John yang Bachelor Professional 90000 1
Managemen
Rob johnson Bachelor t 80000 2
Christy zhu Bachelor Professional 80000 2
managemen
John miller masters degree t 80000 2
John ruiz Bachelor Professional 70000 3
managemen
Christy carlson graduate degree t 70000 3
skilled
Rob hung high school manual 60000 4
skilled
Ruben thores partial college manual 50000 5
partial high
Christy mehta school clerical 50000 5
partial high
Rob yang school clerical 45000 6

Row_Number: It will assign the sequential rank number to each unique record present in a
partition.

select * ,row_number() over (order by income desc) as rank from customer

FN LN Education Occupation Income rank


John yang Bachelor Professional 90000 1
Managemen
Rob johnson Bachelor t 80000 2
Christy zhu Bachelor Professional 80000 3
managemen
John miller masters degree t 80000 4
John ruiz Bachelor Professional 70000 5
managemen
Christy carlson graduate degree t 70000 6
skilled
Rob hung high school manual 60000 7
skilled
Ruben thores partial college manual 50000 8
partial high
Christy mehta school clerical 50000 9
partial high
Rob yang school clerical 45000 10

Find the 2nd ,3rd 4th ……….10th…nth salaries from emp:

Using Dense Rank 2nd ,3rd,4th,5th , Using Top keyword in sql server 2nd ,
6th highest salary 3rd,4th,5th ,6th highest salary Using Not In for 2nd highest salary
select * from select top 1 salary from SELECT MAX(salary) FROM emp
(select *,dense_rank() over (order by (select distinct top 2 salary from emp WHERE salary NOT IN (SELECT MAX(salary) FROM
salary desc) as rk from emp) as a order by salary desc) as temp emp )
where rk=2 order by salary

Lead And Lag:

This allows to access data from a subsequent row without using any self join.

Syntax:

Select lead([scalar_expr]),[offset],[Default] over (partition by clause order by


clause)from table

Scalar Expression:It can be a column ,subquery,or any expr that returns a


single value.

Offset: specify the umber of rows you want to forward

Default:you can specify default value or sql will write NULL.

FN LN Sales
rob ab 24.99
sham xy 59.43
sita fd 29.59

select FN,LN,Sales,lead(sales) over (order by FN) as RESULT from ANALY

FN LN Sales RESULT
rob ab 24.99 59.43
sham xy 59.43 29.59
sita fd 29.59 NULL

Lag:

It access the data from a previous row.

FN LN Sales RESULT
rob ab 24.99 NULL
sham xy 59.43 24.99
sita fd 29.59 59.43

select FN,LN,Sales,lag(sales) over (order by FN) as RESULT from ANALY

CTE:COMMON TABLE EXPRESSION

Used to create a temporary table that will only exist for duration of a query.

They are used to create a temporary table whose content you can reference
in order to simplify the query structure.

Example:

Display all products with greater than price 20.

prodid proddes price


c
1 biscuits 20
2 butter 30
3 milk 47

WITH CTE As
(select prodid,proddesc,price from products where price>20)

select * from CTE

Output:

proddes
prodid c price
2 Butter 30
3 Milk 47

What is refrential integrity?

Is every foreign key value must have corresponding primary key value.

STRING FUNCTIONS:

CHARINDEX: Returns the starting position of the specified expression in a


character string

Charindex(expressiontofind,expressiontosearch,start location)

Example: select charindex(‘t’,’TECHNOSOFT.com’)

Output:5

SUBSTRING:

Returns portion of the string.

SUBSTRING(expression,start,length)
Select name,substring(name,3,2) as sub

Substring(‘abcdef’,2,3)

Reverse: reverses the order of a string value.

Reverse(String)

Select FN,reverse(FN) as reverse from Person

REPLACE:

Replaces all occurenses of a specified string with another string value.

REPLACE(‘abcdefghij’,’cde’,’xxx’;

Op:abxxxfghij

LEN:

Returns the no of characters of specified string expression excluding trailing


blanks.

LEN(STRING)

SELECT LEN(‘Technosoft.com’)

13

ETL

ETL TRANSFORMATION TYPES:


Cleaning:Mapping null to o or male to m or female to f

Deduplication:identifying and renaming duplicate records.

Derivation:Applying rules to your data that derive new calculated values from
existing data.

Filtering: Select certain rows/columns

Joining:

ETL Testing Operations Include?

Verify whether data is transforming correctly according to business req.

Verify whether projected data is loaded into dw without any transformation


and data loss

Make sure that ETL application reports invalid data and replaces with default
values.

ETL BUGS:

Calculation.

User interface

Load Condition

Source

ETL TEST SCENARIOS:

Structure Validation

Validating Mapping Document


Constraint

Data Consistency check

Data completeness

Data transformation validation

Data quality

Null validation

Duplicate
CTE FUNCTION----Difficult
A Common Table Expression (CTE) is the result set of a query which exists
temporarily and for use only within the context of a larger query. Much like a
derived table, the result of a CTE is not stored and exists only for the duration of the
query. 

How to create a CTE


 Initiate a CTE using “WITH”
 Provide a name for the result soon-to-be defined query
 After assigning a name, follow with “AS”
 Specify column names (optional step)
 Define the query to produce the desired result set
 If multiple CTEs are required, initiate each subsequent expression with
a comma and repeat steps 2-4.
 Reference the above-defined CTE(s) in a subsequent query

Example:

WITH Employee_CTE (EmployeeNumber, Title)

AS
(SELECT NationalIDNumber,

JobTitle

FROM   HumanResources.Employee)

SELECT EmployeeNumber,

Title

FROM   Employee_CTE

Or
The SQL Server CTE, also called Common Table Expressions is used to
generate a temporary named set (like a temporary table) that exists for the
duration of a query. We can define this CTE within the execution scope of a
single SELECT, INSERT, DELETE, or UPDATE statement.

SQL Server CTE Syntax


The basic syntax behind the CTE in SQL Server is as shown below:

-- CTE SQL Syntax


WITH Expression_Name (Column_Name1, ColumnName2,.....ColumnNameN)
AS
(CTE Dfinition) -- Write a query

--Using SQL CTE


SELECT Column_Name1, ColumnName2,.....ColumnNameN
FROM Expression_Name -- Or, CTE Name

 Expression_Name: Please specify a valid and unique name to the


Common Table Expressions that you want to create. It must be different
from any other CTE name defined in the same WITH.
 Column_Name1, ColumnName2,…..ColumnNameN: Please specify
valid and unique Column names because CTE won’t allow any duplicate
names. The number of columns that you specify here should match the
result set of the CTE Definition
 CTE Definition: Write your own query

The basic rules to use this SQL Server CTE are:

1. A CTE must be followed by a single SELECT, INSERT, DELETE, or


UPDATE statement that use all or some of the CTE columns.
2. Using UNION, UNION ALL, INTERSECT, or EXCEPT we can define the
multiple CTE definition.
3. A CTE can be referenced itself, and also previously defined CTEs but it
cannot reference the next CTE (forward referencing)
4. We cannot reference the tables on a remote server.
5. Within the CTE Definition you cannot use the following clause:
1. You cannot use ORDER BY Clause unless you are using the TOP
Clause
2. INTO, FOR BROWSE, and OPTION clause with query hint.

For this SQL Common Table Expressions demonstration, We are going


to use [Employee table] and [Department] table present in our [SQL
Tutorial] Database.
From the below figure you can observe that [Employee table] table have
fourteen records

From the below figure you can observe that [Employee table] table have
fourteen records
And [Department] table have eight records.
SQL CTE Example
In this simple example, we will show you, How to write a simple CTE in SQL
Server.

-- Example for CTE SQL


USE [SQL Tutorial]
GO
WITH Total_Sale
AS
(
SELECT [Occupation]
,[Education]
,SUM([YearlyIncome]) AS Income
,SUM([Sales]) AS Sale
FROM [Employee Table]
GROUP BY [Education], [Occupation]
)
SELECT * FROM Total_Sale

OUTPUT

You might also like