SQL Server

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

1

SQL SERVER 2022


What is Data ?

Data is raw, unorganized facts that need to be processed .Data Can be


something simple and seemingly random and useless until it is organized
Ex—710000 -no meaning, unorganized

Database

A database is a collection of information that is organized so that it can be


easily accessed , managed and update

Database Table

A Database table is a tabular format and it is used to store the date of our
application , software , organization etc. Table is made of Rows and Columns.

Row is represent a Record


Column is represent a Field.

What is SQL

SQL is standard language for storing , manipulating and retrieving data in


database.
SQL is stand for Structure query language
SQL is an ANSI(American National Standards Institute) Standard.

What is RDBMS?

RDBMS stands for Relational Database Management System.


RDBMS is the basic for SQL and for all modern database system such as MS SQL
Server, IBM DB2, Oracle ,Mysql and Microsoft Access.

---create database
create database Student;

--use database------

use Student;
-----Create Table ---
create table MyStudents(S_id int Primary key,SName varchar(40) Not
Null,Address varchar(50),Class varchar(50),S_Age int);

-----insert table Values-----

insert into MyStudents values(1,'Rohan','Mumbai','12th',23);


2

insert into MyStudents values(2,'Mohini','Mulund','10th',20);


insert into MyStudents values(3,'Kumar','Chembur','MSC',25);
insert into MyStudents values(4,'Kartik','Ghatkor','15th',24);
insert into MyStudents values(5,'Amar','Mumbai','12th',23);
insert into MyStudents values(6,'Mohan','Borivali','10th',23);
insert into MyStudents values(7,'Suhana','KanjurMarg','12th',21);
insert into MyStudents values(8,'Komal','Dadar','15th',24);
insert into MyStudents values(9,'Jarina','Dombivali','13th',22);
insert into MyStudents values(10,'Nabrata','Diva','14th',22);

------or optional---
insert into MyStudents (S_id, SName) values(11,'Raju');

---Show data table-----


select * from MyStudents;
------------------Another Table -------------------
create table StudentFunctions(F_RollNo int ,SName varchar(40) Not Null,Address
varchar(50),Class varchar(50), S_id int);

insert into StudentFunctions values(1,'Arayan','Mumbai','12th',3);


insert into StudentFunctions values(2,'Manali','Mulund','10th',4);
insert into StudentFunctions values(3,'Kumari','Chembur','MSC',1);
insert into StudentFunctions values(4,'Kartika','Ghatkor','15th',2);
insert into StudentFunctions values(5,'Amarish','Mumbai','12th',5);

select * from StudentFunctions;

-------Constraintrs----------

1) Not Null :- Column cant not have a null value


create table MyStudents(S_id int not null ,SName varchar(40)not
null,Address varchar(50),Class varchar(50) not null,S_Age int);

2) Unique :- all values in a column are different.


create table MyStudents(S_id int not null unique ,SName varchar(40)not
null,Address varchar(50),Class varchar(50) not null,S_Age int);

3) Primary key :- Combination of not null and unique. Primary key show only
one at a table can’t show again in the table.
create table MyStudents(S_id int Primary key,SName varchar(40)not
null,Address varchar(50),Class varchar(50) not null,S_Age int);

4) Foreign Key :- unique identifies a row/record in another table.

create table MyStudents(S_id int Primary key,SName varchar(40) Not


Null,Address varchar(50),Class varchar(50),S_Age int default(18));
3

create table CollegeFunction(RollNo int Primary key,SName varchar(40)


Not Null,Address varchar(50),Class varchar(50),S_Age int,S_id int
foreign key references MyStudents(S_id));
insert into CollegeFunction values(1,'Arayan','Mumbai','12th',23,3);
insert into CollegeFunction values(2,'Manali','Mulund','10th',20,4);
insert into CollegeFunction values(3,'Kumari','Chembur','MSC',25,3);
insert into CollegeFunction values(4,'Kartika','Ghatkor','15th',24,2);
insert into CollegeFunction values(5,'Amarish','Mumbai','12th',23,1);

 Primary key cant’t null or duplicate.


 Foreign key can be null or duplicate .
 We can’t insert in order table with Id that is not present in customer
table.
 We Can’t delete primary table in foreign table directly
 You want to delete table you will have to delete first foreign key table
after deleted primary key table.
 We can’t perform operation delete or update.(using Cascading
referential)
---------How to delete Foreign key--------
alter table CollegeFunction drop
constraint[FK__CollegeFun__S_id__4E88ABD4] ;

*******************************************************************
---------How to add Foreign key--------
alter table CollegeFunction add foreign key( S_id) references
MyStudents( S_id) ;

------how to delete and update foreign key using Cascading


referential-------
create table MyStudents(S_id int Primary key,SName varchar(40) Not
Null,Address varchar(50),Class varchar(50),S_Age int default(18));

*******
create table CollegeFunction(RollNo int Primary key,SName varchar(40)
Not Null,Address varchar(50),Class varchar(50),S_Age int,S_id int
foreign key references MyStudents(S_id)on delete cascade on update
cascade);

*****************************************************************
4

----------delete or update primary key data using Cascading referential


---------
delete from MyStudents where s_id=4;

update MyStudents set Address='chunabhati', S_id=4 where S_id=3 ;

-----cascade referencial table for foreign key delete or update


dataset null-

create table MyStudents(S_id int Primary key,SName varchar(40) Not


Null,Address varchar(50),Class varchar(50),S_Age int default(18));

create table CollegeFunction(RollNo int Primary key,SName varchar(40)


Not Null,Address varchar(50),Class varchar(50),
S_Age int,S_id int foreign key references MyStudents(S_id)
on delete set null
on update set null
);
---set null value----
delete from MyStudents where s_id=3;
update MyStudents set S_id=7 where S_id=1 ;

-----cascade referencial table for foreign key delete or update dataset


default value(1) ---
create table MyStudents(S_id int Primary key,SName varchar(40) Not
Null,Address varchar(50),Class varchar(50),S_Age int default(18));

create table CollegeFunction(RollNo int Primary key,SName varchar(40) Not


Null,Address varchar(50),Class varchar(50),
S_Age int,S_id int foreign key references MyStudents(S_id)
on delete set default
on update set default
);
------------set default value in row-------
alter table CollegeFunction add default 1 for S_id;

---set default value----


delete from MyStudents where s_id=2;
update MyStudents set S_id=7 where S_id=3 ;

5) Check :-all values in a column satisfies a specific condition.


create table MyStudents(S_id int Primary key,SName varchar(40)not
null,Address varchar(50),Class varchar(50) not null,S_Age int
check(S_Age>=18));
5

6) Default :- set default value for a column when no value is given like serial
no.
create table MyStudents(S_id int Primary key,SName varchar(40) Not
Null,Address varchar(50),Class varchar(50),S_Age int default(18));

7) Index :-Use to create and retrieve data from the database very quickly.

------update row----------
update MyStudents set Address='chunabhati', Class='10th' where S_id=11
;
-----Delete Row-------
delete from MyStudents where s_id=11;

-----Delete table data ----


truncate table MyStudents;
------delete table----
drop table MyStudents;

----select table perticular data----


select S_id,SName from MyStudents;
--------Select table one row ------
select * from MyStudents where S_id=4;
------table data is asending order
select * from MyStudents order by SName asc;
------table data is desending order
select * from MyStudents order by SName desc;
------change database Name-----
alter database CutomerData modify name=MyCutomer;
---or---
execute sp_renamedb 'MyCutomer','CutomerData';

--------Chnage table name -----


execute sp_rename 'MyStudents','HelloStudents';

-------insert cloumn in table -----------


alter table MyStudents add StudentsSubject varchar(50) ;
-------Delete table Column-----
6

alter table MyStudents drop column StudentsSubject;


-----change Datatype of table -------
alter table MyStudents alter column StudentsSubject nvarchar(50);
-----change constraint of table -------
alter table MyStudents alter column Address varchar(50) not null;
alter table MyStudents alter column Address varchar(50) null;
----drop unique key constraint----
alter table MyStudents drop constraint [UQ__MyStuden__A3DCCCA448E257FB];

--------add primary key contraint inthe table--


alter table MyStudents alter column S_id int not null;
alter table MyStudents add primary key(S_id);

----drop primary key constraint in the table----


alter table MyStudents drop constraint
[PK__MyStuden__A3DCCCA5829212F5];
------add foregin key in table-----

create table StudentFunctions(F_RollNo int ,SName varchar(40) Not


Null,Address varchar(50),Class varchar(50), S_id int);

alter table StudentFunctions add foreign key (S_id) references Mystudents


(S_id);

insert into StudentFunctions values(1,'Arayan','Mumbai','12th',3);


insert into StudentFunctions values(2,'Manali','Mulund','10th',4);
insert into StudentFunctions values(3,'Kumari','Chembur','MSC',1);
insert into StudentFunctions values(4,'Kartika','Ghatkor','15th',2);
insert into StudentFunctions values(5,'Amarish','Mumbai','12th',5);

------delete foregin key in table-----


alter table StudentFunctions drop constraint
[FK__StudentFun__S_id__5629CD9C];
---add check constraint-------
alter table Mystudents add check(S_Age >= 18);
---delete check contraint-----
alter table MyStudents drop constraint [CK__MyStudent__S_Age__59FA5E80];
---add default constraint-------
7

alter table Mystudents add default 18 for S_Age ;

**********************************************************************************

-------HOW TO SHOW FULL ROW NAME---------


select S_id as Student_Id from MyStudents ;

And

select S_id as Student_Id, SName as Student_Name from MyStudents ;

**********************************************************************************

------Sql Join-----------
1) inner join
2) left join
3) Right join
4) Full Outer Join

*******************

1) inner join

select * from MyStudents as A inner join StudentFunctions as B on A.S_id=B.S_id;

-------Select particular data in two tables by inner join----------


select A.SName,A.Address,A.S_Age,B.F_RollNo,B.Class from MyStudents as A inner join
StudentFunctions as B on A.S_id=B.S_id;

********************************************************************************

------left Join-----------(Right table show Null value)

select * from MyStudents as A left join StudentFunctions as B on A.S_id=B.S_id;

-------Select particular data in two tables by left join----------


select A.SName,A.Address,A.S_Age,B.F_RollNo,B.Class from MyStudents as A left join
StudentFunctions as B on A.S_id=B.S_id;

***************************************************************************

------right Join-----------(left table show Null value)

select * from MyStudents as A left join StudentFunctions as B on A.S_id=B.S_id;

-------Select particular data in two tables by right join----------


select A.SName,A.Address,A.S_Age,B.F_RollNo,B.Class from MyStudents
as A right join StudentFunctions as B on A.S_id=B.S_id;

------full outer Join-----------(select data two tables extra row will


count null)
8

select * from MyStudents as A full outer join StudentFunctions as B on


A.S_id=B.S_id;

-------Select particular data in two tables by full outer


join----------
select A.SName,A.Address,A.S_Age,B.F_RollNo,B.Class from MyStudents
as A full outer join StudentFunctions as B on A.S_id=B.S_id;

------slef Join-----------
select A.SName as Student_Name,B.SName as StudentData from MyStudents
as A inner join StudentFunctions as B on A.S_id=B.S_id;

---------------------Identity increment-------------(Auto id count)


create table MyStudents(S_id int Primary key identity,SName varchar(40) Not
Null,Address varchar(50),Class varchar(50),S_Age int);

or identity(100,5)

create table MyStudents(S_id int Primary key identity(100,5),SName varchar(40) Not


Null,Address varchar(50),Class varchar(50),S_Age int);

insert into MyStudents values('Rohan','Mumbai','12th',23);


insert into MyStudents values('Mohini','Mulund','10th',20);
insert into MyStudents values('Kumar','Chembur','MSC',25);

----------Union and union All-------(Make sure column will be same two’s tables)

select * from MyStudents


union
select * from StudentFunctions;

or

select * from MyStudents


union all
select * from StudentFunctions;

----------intersect ------(match same data row in two tables)

select * from MyStudents


intersect
select * from StudentFunctions;

---------- Except operator------(remove Match data row in two tables)


select * from MyStudents
9

except
select * from StudentFunctions;

---------Aggregate function ---------


SQL server aggregate function perform a calculation on a set of values
and return a single value.
1) Sum
2) Max
3) Min
4) Avg
5) Count
----------Sum aggregate function------

select sum(S_Age) from MyStudents;

or

select sum(S_Age) as Student_Age from MyStudents;

----------Max aggregate function------

select Max(S_Age) as Student_Age from MyStudents;

----------Min aggregate function------

select Min(S_Age) as Student_Age from MyStudents;

----------Average aggregate function------

select Avg(S_Age) as Student_Age from MyStudents;

----------count aggregate function------(count rows)

select Count(S_Age) as Student_Age from MyStudents;

Group By Commond
The GROUP By statement is used with aggregate function
(Count,Max,Min,Sum,Avg) to group the result-set by one or more column.
We Can used one or more than one column in agroup By clause
---------Group by Count---------------(Same rows count and it’s sum)

select Class,Sum(S_Age) as [Total Sum of Age Students] from MyStudents group by


Class;

And
10

select Address,Class,Sum(S_Age) as [Total Sum of Age Students According Address] from


MyStudents group by Address, Class;

Having Clause
 Having Clause is used to specify like where Clause.
 but Having clause is used with Group By Command.
 We can’t use Where Clause With Group By Command.
 Where Clause is used for filtering rows and having clause is
used to filtering groups.
 Where Clause Does not work with aggregate function like Sum,
Min, Max, Count, Avg…
 We Can use Having Clause with Aggregate Functions.
-------------------Having Clause------------

select Class, Sum(S_Age) as [Total Sum of Age Students According Address] from
MyStudents group by Class having Class in ('12th'); -----(apply on group)----

select Address, Sum(S_Age) as [Total Sum of Age Students According Address] from
MyStudents group by Address having Sum(S_Age) >= 23 ;

or ---------------Where Clause-------------

select Class, Sum(S_Age) as [Total Sum of Age Students According Address] from
MyStudents where Class in ('12th')group by Class ; ------(apply on Select
statement)---

select Address, Sum(S_Age) as [Total Sum of Age Students According Address] from
MyStudents wher eAddress in ('Borivali','Mulund','Mumbai') group by Address having
Sum(S_Age) >= 23 ;

ORDER BY KEYWORD
 The order by keyword is used to sort the result-set in
ascending or descending order.
 The order By keyword sorts the records in ascending
order by default.
 To sort the records in descending order use the DESC
Keywords.
-------------------Order by keyword Ascending order------------
select * from MyStudents order by SName asc;

-------------------Order by keyword descending order------------


select * from MyStudents order by SName desc;
11

View in Sql :-Table look like data different


create table MyStudents(S_id int Primary key,SName varchar(40) Not Null,SAddress
varchar(50),SClass varchar(50),S_Age int);

insert into MyStudents values(1,'Rohan','Mumbai','12th',23);


insert into MyStudents values(2,'Mohini','Mulund','10th',20);
insert into MyStudents values(3,'Kumar','Chembur','MSC',25);
insert into MyStudents values(4,'Kartik','Ghatkor','15th',24);
insert into MyStudents values(5,'Amar','Mumbai','12th',23);

create table StudentFunctions(F_RollNo int ,StdName varchar(40) Not Null,Address


varchar(50),Class varchar(50), Myid int);

insert into StudentFunctions values(1,'Arayan','Mumbai','12th',3);


insert into StudentFunctions values(2,'Manali','Mulund','10th',4);
insert into StudentFunctions values(3,'Kumari','Chembur','MSC',1);
insert into StudentFunctions values(4,'Kartika','Ghatkor','15th',2);
insert into StudentFunctions values(5,'Amarish','Mumbai','12th',5);

select * from MyStudents;


select * from StudentFunctions;

drop table MyStudents;


drop table StudentFunctions;

--------view in sql---------
create view vW_ForStudents as select * from MyStudents as A inner join
StudentFunctions as B on B.Myid=A.S_id;

select * from vW_ForStudents;


select * from vW_ForStudents11;

create view vW_ForStudents11 as select A.*,B.StdName from MyStudents as A inner join


StudentFunctions as B on B.Myid=A.S_id;

--------show single data view ---------


create view vW_ForStudents111 as select * from MyStudents as A inner join
StudentFunctions as B on B.Myid=A.S_id where SName='Kartik';

sp_helptext vW_ForStudents111;

select * from vW_ForStudents111;

-----Delete view------
drop view vW_ForStudents111;

---insert view dtata--


insert into vW_ForStudents111 values(6,'Queental','Nashik','14th');

*************************************************************************************
***
12

---Like Operator------
Like operator is used in a Where Clause to searchg for a specified patter in a column

There are Three wildcard used in conjunction with LIKE operator:


% :- The percent sign represent zero, one or multiple charaters
_ :- The underscore represents a signle character
[] :- for multiple characters

-----% operator---------

Where CustomerName LIKE ‘a%’ finds any value starts with “a”

select * from MyStudents where SName Like 'a%';

****************

Where CustomerName LIKE ‘%a’ finds any value ends with “a”

select * from MyStudents where SName Like '%i';

******************

Where CustomerName LIKE ‘%or%’ finds any value have “a” in any position

select * from MyStudents where SName Like '%ma%';

*********************

------------------ ___ operator -------------

Where CustomerName LIKE ‘_r%’ finds any value that have with “r” in the second
position

select * from MyStudents where SName Like 'a___';

---------------- [] operator---------
display same letter total record like(a)
select * from MyStudents where SName Like '[a,b,c]%';

or

select * from MyStudents where SName Like '[a-s]%';

Sub Query
 A subquery or inner query of a Nested is a query within SQL query
and embedded within the WHERE clause.
 A subquery is used return data that will be used in the main
query as a condition to further restrict the data to be
retrieved.
13

 There are a few rules that subqueries must follow


1. Subquery must be enclosed within parentheses.
2. A subquery can have only one column in the SELECT
clause ,unless, Multiple column are in the main query for
the subquery to compare its selected columns.
3. An ORDER BY command can’t be used in a subquery , although
the main query can use an ORDER BY.
4. Subqueries that return more than one row can only be used
with multiple value operators such as IN operator.
5. We can’t use subquery with two tables also.
6. We can update and delete with subquery.

create table MyStudents(S_id int Primary key,SName varchar(40) Not Null,Address


varchar(50),Class varchar(50),S_Age int);

insert into MyStudents values(1,'Rohan','Mumbai','12th',23);


insert into MyStudents values(2,'Mohini','Mulund','10th',20);
insert into MyStudents values(3,'Kumar','Chembur','MSC',25);
insert into MyStudents values(4,'Kartik','Ghatkor','15th',24);
insert into MyStudents values(5,'Amar','Mumbai','12th',23);

-----------sunquery is written in ()-----------


select * from MyStudents where S_id in (select S_id from MyStudents where S_Age >21)
;

-----------update subquery---------------
update MyStudents set S_Age=S_Age +10 where S_id in (select S_id from MyStudents
where S_Age = 25);

---------delete subquery----
delete from MyStudents where S_id in (select S_id from MyStudents where S_Age=35);

--subquery select perticular data --------


select * from MyStudents where S_id in (select S_id from MyStudents where S_Age>23);

--oder data can't assign in subquery they can found erros but order by assign outside
subquery --------
select * from MyStudents where S_id in (select S_id from MyStudents where S_Age>20
)order by S_id;

Type O subqueries

Sub-queries can be divided into two main categories :

 Scalar Subquery :- subquery that return one row to the outer SQL.
14

Statement : Operators:- = > >= < <= !=

select * from MyStudents where S_id = (select F_RollNo from StudentFunctions


where Address='Mumbai');

 MultiValued Subqueries:- subqueries that return more than one row


to the outer SQL statement.
Opetors : in,any and all.

---------in----
select * from MyStudents where S_id in (select S_id from MyStudents where
S_Age>21 );
----------any -------
select * from MyStudents where S_id < any (select S_id from MyStudents where
S_Age>21 or S_Age<25);
----all------------
select * from MyStudents where S_id < all (select S_id from MyStudents where
S_Age>21 or S_Age<26);

Between,Top ,Percent,Distinct and In Operator

--------Between operator----------(select only 20 to 23)


select * from MyStudents where S_Age between 20 and 23;

-------Top Operator-------(select first five rows)


select Top 5 * from MyStudents;

-------Percetage Operator-------(40% = 4 rows)


select Top 40 percent * from MyStudents;

-------Distinct Operator-------(unique name only find)


select distinct SName from MyStudents;

-------In Operator-------(select particular data )


select * from MyStudents where Address in ('Mumbai','Dadar');

-------Not In Operator-------(Don't show selected Address)


select * from MyStudents where Address not in ('Mumbai','Dadar');

Select into Statement


The select into statement in sql server selects the data from one
table and insert it into a new table
-------Copy table in another table name-----
Select * into StudentData_backup from MyStudents;
15

-Show table--
select * from StudentData_backup;

-------selct perticular column in another table-----


Select S_id,SName,Class into StudentColumn_backups from MyStudents;
--show table----
select * from StudentColumn_backups;

--delete table and make new eachtime table---

drop table StudentData_backup;

-------selct perticular rows in another table-----


Select * into StudentDatasss_backups from MyStudents where Address='mumbai';
--show table---
select * from StudentDatasss_backups;

----------insert into with select statement-----

--------select * from MyStudents;


---------select * from StudentFunctions;

Insert into StudentFunctions select * from MyStudents;

Store Procedure
A store procedure is a set of structure query language (SQL) statement with an assigned
name, which are stored in a relationship database management as group so it can be reused
and shared by multiple program.

Type of store Procedure

1 System store procedures.

2 User Defined Store Procedures.

How to work store Procedure

 Store Procedure with single parameter


 Store procedure with multiple parameter , changing the parameters order
 Alter with stored procedure
 Seeing the text pf the SP. SP_helptext
 Drop with stored procedure
 Microsoft used sp_prefix for system store procedures.
 Using WITH ENCRYPTION in stored procedures.

-----Create Store Procedure--------


create procedure spGetStudents as begin select SName,Address from MyStudents; end
16

*********************

--Execute Store procedure--------


spGetStudents;
or
execute spGetStudents;
or
exec spGetStudents;

****************

---------- Store Procedure with single parameter ---------------------

create procedure spGetStudentById @id int as begin select * from MyStudents where
S_id=@id; end

----Execute---(put on id number)
spGetStudentById 2;

-------- Store procedure with multiple parameter , changing the parameters order---

create procedure spGetStudentByIdandName @id int, @Name varchar(50) as begin


select * from MyStudents where S_id=@id and SName=@Name; end

---execute ------
execute spGetStudentByIdandName 2,'Mohini';
----- Alter with stored procedure-------------
alter procedure spGetStudentByIdAndName @id int, @Name varchar(50) as begin select
SName,SAddress from MyStudents where S_id=@id and SName=@Name; end

---execute ------
execute spGetStudentByIdandName 2,'Mohini';

--------Seeing the text pf the SP. SP_helptext----------

alter procedure spGetStudentByIdAndName @id int, @Name varchar(50) as begin select


SName,SAddress from MyStudents where S_id=@id and SName=@Name; end

---execute ------
execute spGetStudentByIdAndName 2,'Mohini';

sp_helptext spGetStudentByIdandName;

---------- Drop with stored procedure---------

Drop procedure spGetStudentByIdandName;

---------- Using WITH ENCRYPTION in stored procedures---------


17

alter procedure spGetStudentByIdAndName @id int, @Name varchar(50) with encryption as


begin select SName,SAddress from MyStudents where S_id=@id and SName=@Name; end

----execute---
sp_helptext spGetStudentByIdandName;

Function in Programming
 A Function is a Block of code that performs a specific
task.
 Function usually ‘take in’ data process it and return a
results.
 Once a function is written it can be used over and over
again it means function can be reused.
 A function accepts input in the form of parameter and
returns a value.
 SQL Server comes with a set of built-in functions that
perform a variety of tasks.

In T-SQL a function is considered an object. Here are


some of rules when creating function in SQL Server.
1. A function Must have a name and a function name can
never start with a special character such as @,$,#
and so on .
2. Function only select with Select Statement.
3. Function can be used anywhere in SQL like
AVG,COUNT,SUM,MIN,DATE and so on with select
Statement.
4. Function compile every time.
5. Function must return a value and result.
6. Try and catch statement are not used in functions.

SQL SERVER FUNCTION


i. User Define
ii. System Defined
18

 User Define function


Ther are three types of user defined function in sql server
 Scalar Functions
 Inline Table Valued Functions
 Multi -Statement

I. Scalar Functions
 SQL Server scalar function takes one or more
parameters and returns a single(scalar) value.
 The return value can be any data type ,except
text, ntext, image, cursor and timestamp
 Scaler function can use logic such as IF blocks or
While loops.
 Scaler function can’t update data. They can
access data but this is not a good practice.
 Scaler function call the other functions.

------Create function without parameter-----


create function ShowMessage() returns varchar(100) as begin return 'Welcome To
Function' end ;
------show function---
select dbo.ShowMessage(); -- Notes:bdo Means Database owner---

------Create function with single parameter-----


create function TakeNumber(@num as int) returns int as begin return (@num * @num)
end;

------show function---
select dbo.TakeNumber(2);
-------Create function with Multiple parameter---
create function Addition(@num1 as int ,@num2 as int) returns int as begin
return(@num1+@num2) end;

--show function---
select dbo.Addition(5,6);
---reused function---
select dbo.Addition(23,34);
19

------alter function with single parameter---


alter function TakeNumber(@num as int) returns int as begin return (@num *
@num * @num) end;
select dbo.TakeNumber(2);
-----Drop Function----
drop function dbo.TakeNumber;

-----------Scalar function if -esle function ---


create function CheckVoterAge(@age as int ) returns varchar (100)
as
begin
declare @str varchar(100)
if @age >=18 begin set @str='you are eligible to vote'end
else begin set @str='You are no eligible to vote' end
return @str end;

select dbo.CheckVoterAge(20);
select dbo.CheckVoterAge(16);

---scalar function Return other function---


create function GetMyDate() --main function---
returns datetime
as
begin return getdate() --another function--
end

-----show function---
select dbo.GetMyDate();

II. Inline Table Valued Functions


 Contains a single TSQL statement and returns a
table set.
 We have to specify TABLE as the return
type ,instead of any scalar data type like
int ,varchar etc.
 There is no BEGIN and END Block.
 The table that gets returns is determined by the
SELECT command within the function

---inline function with parameter----


create function fn_GetStudentsWithAge(@age int)returns table as return
(select * from MyStudents where S_Age>=@age);

select * from fn_GetStudentsWithAge(17);


select * from fn_GetStudentsWithAge(23);
20

---inline function without parameter----


create function fn_GetStudents() returns table as return (select * from
MyStudents);

select * from MyStudents;


select * from fn_GetStudents();
select * from dbo.fn_GetStudents();
---------------- inline function inner join-------------
select * from fn_GetStudents();
select * from fn_GetStudentsWithAge(23);

select * from fn_GetStudentsWithAge(23) as A inner join fn_GetStudents() as B


on A.S_id=B.S_id;
****************************************************************************************

1. Multi -Statement
o A multi Statement table-valued function is a table-
valued function that returns the result of multiple
statements.
o The multi-statement-valued function is very useful
because you can execute multiple queries within the
function and aggregate result into the returned
table.
o To defined a multi-statement table-valued function
you used a table variable as the return value. Inside
the function you execute one or more queries and
insert data into this table variable

---Multi statement table------


create function fn_GetStudentsByAddress(@address varchar(20)) returns
@MyTable table(std_id int,Std_Name varchar(50), Address varchar(50)) as begin
insert into @MyTable select S_id,SName,Address from MyStudents where
Address=@address return end

select * from [dbo].[fn_GetStudentsByAddress]('Mumbai');

or

---inline statement table------


21

create function fn_GetStudentsByAddress2(@address varchar(20)) returns table


as return (select S_id,SName,Address from MyStudents where Address=@address)

select * from [dbo].[fn_GetStudentsByAddress2]('Mumbai');

Inline table statement Multiple table statement

 In this the return clause can’t In this we specify the structure


Contain the structure of the table. of the table with return clause.

 In this there are no BEGIN and END In this we have to use BEGIN and
Blocks END blocks.
 Inline table-valued function are Ther is no performance advantages
better in performance as compared in multi statement table-valued
to multi statement table valued functions.
functions.

 Internally inline table valued Internally multi-statement table-


function much like it would a valued function much like would a
view stored procedured

 Similaries

 Inline statement table-valued function and multiple statement table-


valued function both are table-valued functions.
 Inline statement table-valued functions and multi statement table-value
functions both are located in table-valued function folder in SSMS.
 Both are the types of user defined function in Sql serve .

Show the inner join of Three Tables


-----Create Table ---
create table MyStudents(S_id int Primary key,SName varchar(40) Not Null,Address
varchar(50),Class varchar(50),S_Age int);

-----insert table Values-----

insert into MyStudents values(1,'Rohan','Mumbai','12th',23);


insert into MyStudents values(2,'Mohini','Mulund','10th',20);
insert into MyStudents values(3,'Kumar','Chembur','MSC',25);
insert into MyStudents values(4,'Kartik','Ghatkor','15th',24);
22

insert into MyStudents values(5,'Amar','Mumbai','12th',23);

------------------ Table2 -------------------


create table StudentFunctions(F_RollNo int ,SName varchar(40) Not Null,Address
varchar(50),Class varchar(50), S_id int);

insert into StudentFunctions values(1,'Arayan','Mumbai','12th',3);


insert into StudentFunctions values(2,'Manali','Mulund','10th',4);
insert into StudentFunctions values(3,'Kumari','Chembur','MSC',1);

---------------------table3-----------
create table StudentFunctions222(F_RollNo int ,SName varchar(40) Not Null,Address
varchar(50),Class varchar(50), S_id int);

insert into StudentFunctions222 values(1,'Arayan','Mumbai','12th',3);


insert into StudentFunctions222 values(2,'Manali','Mulund','10th',4);
insert into StudentFunctions222 values(3,'Kumari','Chembur','MSC',1);

select * from MyStudents;


select * from StudentFunctions;
select * from StudentFunctions222

------Show the joint three table-----


select * from MyStudents as A
inner join StudentFunctions as B
on A.S_id=B.S_id
inner join StudentFunctions222 as C
on B.S_id=C.S_id;

--------Select perticular data in table-----


select A.SName,A.S_Age,B.Address,C.Class from MyStudents as A
inner join StudentFunctions as B
on A.S_id=B.S_id
inner join StudentFunctions222 as C
on B.S_id=C.S_id;

Trigger
 A trigger is a special kind of stored procedure that automatically execute when an
event occurs in the database server.
 There are three types of triggers
 DML triggers (Data Manipulation language) Insert,Update ,Delete
 DDL Triggers (Data Definition Language) Create ,Alter
 Logon Triggers

DML triggers (Data Manipulation language)


23

 DML Triggers are fried automatically in respose to DML Events


(Insert,Update,And Delete).

 DMl Triggers can be two types


A. After Triggers (Also called for triggers)
B. Instead triggers

1.After Triggers (Also called for triggers)

-----Create Table ---


create table MyStudents(S_id int Primary key,SName varchar(40) Not Null,Address
varchar(50),Class varchar(50),S_Age int);

-----insert table Values-----

insert into MyStudents values(1,'Rohan','Mumbai','12th',23);


insert into MyStudents values(2,'Mohini','Mulund','10th',20);
insert into MyStudents values(3,'Kumar','Chembur','MSC',25);
insert into MyStudents values(4,'Kartik','Ghatkor','15th',24);
insert into MyStudents values(5,'Amar','Mumbai','12th',23);
insert into MyStudents values(10,'Nabrata','Diva','14th',22);

select * from MyStudents;

----DDL insert ---------


create trigger tr__StudentsInsert on MyStudents after insert as begin print ' something
happend to the students table'; end

--------when DDL insert after the insert value in table


insert into MyStudents values(11,'Suresh','Diva','12th',21);

-show table-
select * from MyStudents;

----DDL alter ---------


alter trigger tr__StudentsInsert on MyStudents after insert as
begin
select * from inserted
end

---------insert value in students table ----


insert into MyStudents values(11,'Suresh','Diva','12th',21);

---show table-
select * from MyStudents;

----DDL delete ---------


create trigger tr__StudentsDelete on MyStudents after delete as
begin
select * from deleted
end
24

---delete student table row-----


delete from MyStudents where S_id = 7;

---show table-
select * from MyStudents;

---delete student table row-----


delete from MyStudents where S_id = 7;
delete from MyStudents where S_id = 8;
delete from MyStudents where S_id = 9;

-----insert table Values-----

insert into MyStudents values(1,'Rohan','Mumbai','12th',23);


insert into MyStudents values(2,'Mohini','Mulund','10th',20);
insert into MyStudents values(3,'Kumar','Chembur','MSC',25);
insert into MyStudents values(4,'Kartik','Ghatkor','15th',24);
insert into MyStudents values(5,'Amar','Mumbai','12th',23);

select * from MyStudents;

select * from MyStudents;

------Create another table for inserting values through DDL insert----

create table Students_Audit(Audit_id int primary key identity , Audit_info varchar(max));


select * from Students_Audit;

----DDL isert one table to another table automatically inserted values ---------
create trigger tr__StudentsAuditInsert on MyStudents after insert as
begin
Declare @id int
select @id=S_id from inserted

insert into Students_Audit


values('Student with id'+ Cast (@id as varchar(50)) + ' is added at' + Cast(GetDate()
as varchar(50)));
end

-----------insert values in MyStudents;---------

insert into MyStudents values(7,'Suhana','KanjurMarg','12th',21);


insert into MyStudents values(8,'Komal','Dadar','15th',24);

---------show otput------------

select * from Students_Audit;

********************************

------another table---------
25

create table Students_Audit(Audit_id int primary key identity , Audit_info varchar(max));


select * from Students_Audit;

----DDL delete one table row to another table automaticalyy deleted values print
---------
create trigger tr__StudentsAuditDelete on MyStudents after delete as
begin
Declare @id int
select @id=S_id from deleted
insert into Students_Audit
values('Existing Student with id'+ Cast (@id as varchar(50)) + ' is deleted at' +
Cast(GetDate() as varchar(50)));
end

Note :- Cast used for change datatype

---delete student table row-----


delete from MyStudents where S_id = 7;
delete from MyStudents where S_id = 8;

------show message to delete row-----

select * from Students_Audit

*****************************************

----DDL update one table row to another table automaticalyy update and delete values
print ---------
create trigger tr__StudentsAuditUpdated on MyStudents after update as
begin
select * from inserted
select * from deleted
end

-----update MyStudents id ----

update MyStudents set S_id=12,SName='Shubham Gaivad' where S_id=7;

------show message to delete row-----

select * from MyStudents;

*****************************************************************************************

2.Instead triggers
 Instead of triggers is executed in place of the insert ,update, or delete
operators
 We can view the definition triggers by using sp_helptext system stored procedure.
 We can use Alter (create) Statement with Triggers.
 Modifying DML triggers by using Drop and Recreate or Alter trigger statement.
26

 A DML Trigger can be Encrypted to HIDE its Definition or Query By Using With
Encryption command.

create table MyStudents(S_id int Primary key,SName varchar(40) Not Null,Address


varchar(50),Class varchar(50),S_Age int);

-----insert table Values-----

insert into MyStudents values(1,'Rohan','Mumbai','12th',23);


insert into MyStudents values(2,'Mohini','Mulund','10th',20);
insert into MyStudents values(3,'Kumar','Chembur','MSC',25);
insert into MyStudents values(4,'Kartik','Ghatkor','15th',24);
insert into MyStudents values(5,'Amar','Mumbai','12th',23);
insert into MyStudents values(6,'Mohan','Borivali','10th',23);
insert into MyStudents values(7,'Suhana','KanjurMarg','12th',21);
insert into MyStudents values(8,'Komal','Dadar','15th',24);

----show table---
select * from MyStudents;

for insert
--------Insted of insert trigger-----
create trigger tr_CustomerIntedTr on MyStudents
instead of insert as
begin
print 'you are not allow insert data in this table !!'
end

----show table---(there will be show data is not insert in the table)---


select * from MyStudents;
****************
--------Insted of update trigger-----
create trigger tr_CustomerIntedUpdate on MyStudents
instead of update as
begin
print 'you are not allow update data in this table !!'
end

--update row---
update MyStudents set SName='sudhakar matre' ,S_Age=44 where S_id=6;

----show table---(there will be show data is not update in the table)---


select * from MyStudents;
*************************************
--------Insted of update trigger-----
create trigger tr_CustomerIntedDelete on MyStudents
instead of delete as
begin
print 'you are not allow delete data in this table !!'
end

--delete row---
delete from MyStudents where S_id=5;

----show table---(there will be show data is not delete in the table)---


select * from MyStudents;
27

****************************************************
Insert table one to another table

-----create another table----------------


create table CustomerAudit(Audit_id int primary key identity , Audit_information
varchar(max));

---drop trigger------
drop trigger tr_CustomerIntedTr;

create trigger tr_CustomerIntedTrAudit on MyStudents


instead of insert as
begin
insert into CustomerAudit values('Some one tries to insert data in customer table
at:'+ Cast(GETDATE() as varchar(50)));
end

----show table data---


select * from CustomerAudit;

---inser row---
insert into MyStudents values(8,'Komal','Dadar','15th',24);
----show table data---
select * from CustomerAudit;
***********************************************
for Update
-----create another table----------------
create table CustomerAudit(Audit_id int primary key identity , Audit_information
varchar(max));

---drop trigger------
drop trigger [tr_CustomerIntedUpdate];

---update data-
create trigger tr_CustomerAuditUpdate on MyStudents
instead of update as
begin
insert into CustomerAudit values('Some one tries to updatet data in customer table at:'+
Cast(GETDATE() as varchar(50)));
end

---update Mystudents data---------


update MyStudents set SName='Lakshmi boob' where S_id=12;

----show table data---


select * from CustomerAudit;
**************************************

For delete

-----create another table----------------


create table CustomerAudit(Audit_id int primary key identity , Audit_information
varchar(max));
28

---drop trigger------
drop trigger [tr_CustomerIntedDelete] ;

---delete data----
create trigger tr_CustomerAuditDelete on MyStudents
instead of delete as
begin
insert into CustomerAudit values('Some one tries to delete data in customer table at:'+
Cast(GETDATE() as varchar(50)));
end

---update Mystudents data---------


delete from MyStudents where S_id=12;

----show table data---


select * from CustomerAudit;

We can view the definition of trigger but using sp_helptext system stored
procedure.

---view trigger---
sp_helptext tr_CustomerAuditDelete;
**************************************************
Encryption and decryption trigger
-----create another table----------------
create table CustomerAudit(Audit_id int primary key identity , Audit_information
varchar(max));

---drop trigger------
drop trigger [tr_CustomerAuditDelete] ;

---encripyted data----
create trigger tr_CustomerAuditDeleteEncryption on MyStudents with encryption
instead of delete as
begin
insert into CustomerAudit values('Some one tries to delete data in customer table at:'+
Cast(GETDATE() as varchar(50)));
end

----show table data---


select * from CustomerAudit;

---view trigger---
sp_helptext [tr__StudentsAuditUpdated];

-------with descripted-------
alter trigger tr_CustomerAuditDeleteEncryption on MyStudents
instead of delete as
begin
insert into CustomerAudit values('Some one tries to delete data in customer table at:'+
Cast(GETDATE() as varchar(50)));
end
---view trigger---
sp_helptext [tr__StudentsAuditUpdated]
;
29

DML INSTEAD OF DELETED TRIGGER WITH VIEW


create table MyStudents(S_id int Primary key,SName varchar(40) Not Null,Address
varchar(50),Class varchar(50),S_Age int);

-----insert table Values-----

insert into MyStudents values(1,'Rohan','Mumbai','12th',23);


insert into MyStudents values(2,'Mohini','Mulund','10th',20);
insert into MyStudents values(3,'Kumar','Chembur','MSC',25);
insert into MyStudents values(4,'Kartik','Ghatkor','15th',24);
insert into MyStudents values(5,'Amar','Mumbai','12th',23);

----show table---
select * from MyStudents;

create table StudentFunctions(F_RollNo int ,SName varchar(40) Not Null,Address


varchar(50),Class varchar(50), S_id int);

insert into StudentFunctions values(1,'Arayan','Mumbai','12th',3);


insert into StudentFunctions values(2,'Manali','Mulund','10th',4);
insert into StudentFunctions values(3,'Kumari','Chembur','MSC',1);
insert into StudentFunctions values(4,'Kartika','Ghatkor','15th',2);
insert into StudentFunctions values(5,'Amarish','Mumbai','12th',5);

select * from StudentFunctions;


select * from MyStudents;

create view vw_StudentsDetail as select A.S_id,A.SName,B.Address,B.Class from MyStudents


as A inner join StudentFunctions as B on A.S_id=B.S_id;

select * from vw_StudentsDetail;

delete from vw_StudentsDetail where S_id =4;

----instead of trigger----------
create trigger tr_insteadOfTrigger on vw_StudentsDetail
instead of delete as
begin
delete from MyStudents where S_id in
(select S_id from deleted)
delete from StudentFunctions where S_id in
(select S_id from deleted)
end

select * from vw_StudentsDetail;

--------delete row from the table-------


delete from vw_StudentsDetail where S_id =4;

select * from vw_StudentsDetail;


select * from StudentFunctions;
select * from MyStudents;
30

*****************************************************************************************
DDL Triggers
DDL (Data Definition language) triggers execute stored procedures when DDL
events such as CREATE,ALTER and DROP statement occurs in the database or
server.

What is the use of DDL Triggers?


 DDL triggers can be used to prevent modifications in the database
Schema .A schema is a collection of objects such as tables , views and
so forth in a database.
 If you want to execute some code or message in response to a specific
DDL event.
 To prevent certain changes that to your database schema .
 Audit or check the changes that the users are making to the database
structure.
 DDL trigger scope DDL trigger can be in a specific database or at
server level.
 We c an used ROLLBACK command to prevent for creating ,altering and
dropping something in the database or server.
 We can use With Encryption with DDL triggers to hide the code
definition .
 We can use drop and after command with DDL triggers.
 We can Enable or disable trigger for a time being as per requirement.
 Rename event is used in the DDL trigger when we invoke the system store
procedure sp_rename.

-----Create Table ---


create table MyStudents(S_id int Primary key,SName varchar(40) Not Null,Address
varchar(50),Class varchar(50),S_Age int);

-----insert table Values-----

insert into MyStudents values(1,'Rohan','Mumbai','12th',23);


insert into MyStudents values(2,'Mohini','Mulund','10th',20);
insert into MyStudents values(3,'Kumar','Chembur','MSC',25);
insert into MyStudents values(4,'Kartik','Ghatkor','15th',24);
insert into MyStudents values(5,'Amar','Mumbai','12th',23);

----show table---
select * from MyStudents;

----Create new trigger---------------


create trigger tr_DDLCreatetable on database for CREATE_TABLE as
begin
print'New table created !!';
end

create table Test(id int);

----alter trigger---
alter trigger tr_DDLCreatetable on database for ALTER_TABLE as
begin
31

print'You have just alter table !!';


end

alter table Test add Address varchar(50);

select * from Test;

create trigger tr_DDLCreatetable_Drop on database for DROP_TABLE as


begin
print'You have just drop table !!';
end
---drop trigger-------
drop table Test;
*****************************
-----created ,alter, drop table in one table --------------
create trigger MyDatabase on database for CREATE_TABLE,ALTER_TABLE,DROP_TABLE as
begin
print 'You have just created ,alter, drop table !!';
end

create table ShowData(id int);

alter table ShowData add Name varchar(50);

drop table ShowData;

select * from ShowData;

***************

---- CREATE_PROCEDURE in table---

create trigger tr_ddl_sp_Create on database for CREATE_PROCEDURE as


begin
Rollback
print 'you are not allow to create a store procedure !!';
end

Note : Rollback can't create a procedure in the table

create procedure sp_myProcedure as


begin
print'This is my store procedure !!'
end

sp_helptext tr_ddl_sp_Creat;

---disabled trigger-------
disable trigger tr_ddl_sp_Create on database;

create table test2(id int);

---------rename procedure--------
create trigger tr_ddl_REname on database for RENAME as
32

begin
print ' you have just rename table column ';
end

select * from Test2;

sp_rename 'Test2','Test4';

----------drop trigger on database----


drop trigger [tr_ddl_sp_Create] on database;

Scope of DDL Triggers


 DDL trigger are invoked by sql statements executed either in the current database
or on the current server
 Scope of the DDL trigger depends on whether the trigger executes for database
events or server events.

 Database Scoped DDL Triggers:


o Are invoked by the events that modify the database schema .
o Stores the triggers in the database and execute on DDL events, except
those related to temporary tables.

 Server-Scoped DDL Trigger:


a) Are invoked by DDL events at the server level.
b) Are stored in the master database.

 We can also use with encryption command with server scoped DDL
triggers.
 We can also Enable And Disable Trigger ON server Scope DDL Triggers.

-----create scope trigger----


create trigger tr_MyDatabaseTrigger on database for CREATE_TABLE as
begin
print 'you have just created a table '
end

create table My_table(id int);

-----drop trigger----
drop trigger [tr_MyDatabaseTrigger] on database;

-------Server scope trigger----------


create trigger tr_MyServerScopeTrigger on All Server for CREATE_TABLE as
begin
print 'you have just created a table '
end

create table Server_table(id int);

-------Alter With ROLLBACK Server scope trigger----------


33

alter trigger tr_MyServerScopeTrigger on All Server for CREATE_TABLE as


begin
ROLLBACK
print 'you are not allow to create table '
end

create table Server_table1(id int);

-------Server scope trigger with view----------


create trigger tr_MyServerScopeTrigger_ForView on All Server for CREATE_TABLE as
begin
ROLLBACK
print 'you are not allow to create view !! '
end

select * from MyStudents;

create view vw_ForStudents as select S_id,SName from MyStudents;

---disabled trigger
disable trigger [tr_MyServerScopeTrigger] on All server;

create table Server_table2(id int);

---enabled trigger
enable trigger [tr_MyServerScopeTrigger] on All server;

--------show trigger----------
create table Server_table2(id int);

*********************************************************************
Execution order of DML Triggers
 Sql server 2012 allows users to specify which AFTER trigger is to be
executed first and which is to be executed last.
 SP_SetTriggersOrder
 @Triggername :-is the name of the DML or DDL trigger and the
schema to which it belongs and whose order needs to be
specified.
 @Order :specified the execution order of the trigger as
FIRST ,LAST or NONE . if First is specified then trigger is fired
first
 @StmtType(Statement type):specified the type of SQL statement
(Insert, Update, Delete)that invoke the DML trigger.

---Show data table-----


select * from MyStudents;

-----setting execution trigger----


create trigger tr_MyDatabaseTrigger1 on MyStudents After insert as
begin
print'1rd thrigger is fire !!'
end
34

create trigger tr_MyDatabaseTrigger2 on MyStudents After insert as


begin
print'2rd thrigger is fire !!'
end

create trigger tr_MyDatabaseTrigger3 on MyStudents After insert as


begin
print'3rd thrigger is fire !!'
end

---insert table value-


insert into MyStudents values(6,'Mohan','Borivali','10th',23);

execute sp_settriggerorder
@triggername ='tr_MyDatabaseTrigger1',
@order ='first',
@stmttype = 'insert';

---insert table value-


insert into MyStudents values(7,'Suhana','KanjurMarg','12th',21);

execute sp_settriggerorder
@triggername ='tr_MyDatabaseTrigger3',
@order ='last',
@stmttype = 'insert';

insert into MyStudents values(8,'Komal','Dadar','15th',24);

*********************************************
GUID(globaly Unique Identifire) note this is used for big data sizing

A GUID is a 16 byte binary data type that is globally unique

How to create a GUID


 To Create a GUID in sql server use NEWID() function.

Advantages
 A guid is unique across tables, database and servers.
 Usefull if you are consulting records from multiple SQL server into a
single table
DisAdvantages

 Size is 16 bytes with as int is only 4 bytes.


 One of the Largest Datatypes in SQL server.
 An Index built on a GUID is largest and slower.
 Hard to read compared to INT.

-----------GUID created table-----------

create table Customer2 (id uniqueidentifier primary key default newid(),Name


varchar(50));

insert into Customer2 values(default,'Rohan');


35

insert into Customer2 values(default,'Kumar');


insert into Customer2 values(default,'Angali');
insert into Customer2 values(default,'Mohsan');

select newid();
select * from Customer2;

-----create another table -----


create table Customer3 (id uniqueidentifier primary key default newid(),Name
varchar(50));

insert into Customer3 values(default,'Mayur');


insert into Customer3 values(default,'Kumar');
insert into Customer3 values(default,'Rameshwar');
insert into Customer3 values(default,'Madhu');

select * from Customer2;


select * from Customer3;

-----create another table -----


create table Customers (id uniqueidentifier primary key default newid(),Name
varchar(50));

----insert values one table from table 1 and table2-------


insert into Customers
select * from Customer2
union all
select * from Customer3;

--show table data


select * from Customers;
***************************************************************************

Composite Key and Composite Primary key


 Composite Key (two primary key can be used one table)
 Composite key or composite primary key refers to case where more than
one column is used to specific the primary key of a table .
 In such case all foreign keys will also need to include all the column
in the composite key.
 Note that the columns that make a composite key can be of different data
types .

--------primary key put two column in the table ---------


create table MyStudents(S_id int,SName varchar(40) Not Null,Address
varchar(50),Class varchar(50),S_Age int, primary key(S_id,Address));

-----insert table Values-----


36

insert into MyStudents values(1,'Rohan','Mumbai','12th',23);


insert into MyStudents values(2,'Mohini','Mulund','10th',20);
insert into MyStudents values(3,'Kumar','Chembur','MSC',25);
insert into MyStudents values(4,'Kartik','Ghatkor','15th',24);
insert into MyStudents values(5,'Amar','Mumbai','12th',23);

select * from MyStudents;

NORMALIZATION
 Database Normalization is the process of organizing data to minimize
data redundancy (data duplication)which lea to data inconsistency.
 Data normalization is the step by step process. There are 6 Normal
Forms.

Disadvantages of data redundancy


1. Disk space wastage
2. Data Inconsistency
3. DML (Data Manipulation) insert update delete queries can become slow

FIRST NORMAL FORM


A table said to be in first Normal Form.

1) The Data in each should be atomic ,no multiple values separated by


comma.
2) The table does not contain any repeating column groups
3) Identify each record uniquely using primary key.

SECOND NORMAL FORM (2NF)


The table is said to be in 2NF if
a. The table meets all the condition of first normal form.
b. There are no partial dependencies in the table.
 Partial dependency means a non-key attribute should not be
partially dependent on more thane on key attribute.

c. Move redundant data to a separate table .


d. Create relationships between these tables using Foreign keys.

Third Normal form


A table is said to be in third normal form.
1) Meets all conditions of first normal form and second normal form.
2) The table should not have Transitive Dependencies in them.
37

 Does not contain column (Attribute ) that are not fully dependent
on the Primary key.
 If an attribute can be deteremind by another Non-key attribute it
is called a transitive dependency.
 To make it simpler every non-key attribute should be determined
by the key attribute only.
 If a Non -key attribute can be determinded by another non-key
attribute it needs to put into another table.

***********************************************************************
String Functions
 Ascii() :-Returns the ASCII code of the given character.
select ascii('A');
select ascii('Z');
select ascii('a');

 CHAR() :- Convertsan int ASCII code to a character.The integer should be


between 0 and 255.

select char(65);

declare @start int set @start= 65


while(@start <=90)
begin
print char(@start)
set @start=@start + 1
end

 LTRIM() :-Removes blank on the left hand side of the given character
expression.

select ' hello';

select ltrim(' hello');

 RTRIM() :- Removes blank on the right hand side of the given character
expression.
select 'hello ';

select ltrim('hello ');

 Lower() :- Convert all the character to lowercase letters.

select lower(SName) as StudentsName from MyStudents;

 Upper() :-Covert all the character to the uppercase letter.

select upper(SName) as StudentsName from MyStudents;

 Reverse() :- Reverse the all character int the given string.



select reverse(SName) as StudentsName from MyStudents;
38

 LEN() :-Returns the count (int) of total character int a string excluding the
blanks at the end of the expression.

select SName, len(SName) as StudentsName from MyStudents;

select ltrim(SName), len(ltrim(SName)) as StudentsName from MyStudents;

*****************************************************************************************

INDEXES

 To facility quick retrieval of the data from a database SQL


server 2012 provides the indexing feature .
 An index in Sql server 2012 database contains information
that allows you to find specific data without scanning
through the entire table.
 Indexes are created on tables and views .
 Index om a tables or a view is very similar to an index that
we find in a book .
 If you don’t have index in a book y and I ask you to locate
a specific character in the book you will have to look at
every page starting from the first page of the book.

 On the other hand if you have the index in a book you lookup
the page number of the character in the index and then
directly go the that page number to locate the character .

 Obviously the book index is helping to reduce the time takes


to find the character .
 In fact the book index is helping to reduce the time it
takes to find the chapter.
 In fact the Existence of the right indexes can improve the
performance of the query . if there is no index to help the
query ,then query engine ,checks every row in the table from
the beginning to end .this is called as table scan .table
scan is very bad for performance.
create table MyStudents(S_id int Primary key,SName varchar(40) Not Null,Address
varchar(50),Class varchar(50),S_Age int);

-----insert table Values-----

insert into MyStudents values(1,'Rohan','Mumbai','12th',23);


insert into MyStudents values(2,'Mohini','Mulund','10th',20);
insert into MyStudents values(3,'Kumar','Chembur','MSC',25);
insert into MyStudents values(4,'Kartik','Ghatkor','15th',24);
insert into MyStudents values(5,'Amar','Mumbai','12th',23);
insert into MyStudents values(6,'Mohan','Borivali','10th',23);

select * from MyStudents;


39

create index FullTimeStudents on MyStudents(S_Age asc);

sp_helpindex MyStudents;

select * from MyStudents where S_Age >=18 and S_Age<18;

drop index MyStudents.FullTimeStudents;


********************************************************
CLUSTER AND NON-CLUSTER INDEX

CLUSTER INDEX

 A cluster index clause records to be physically store in a stored or


sequential order.
 A clustered index determines the actual order in which data is stored
in the database hence you can create only one clustered index in a
table.
 Uniqueness of a values in a clustered index is maintained explicitly
using the unique keyword or implicitly using an internal unique
identifier.
 Clustered index is as same as dictionary where the data is arranged by
alphabetical order.
 Clustered index can be use only one time in the table (like a primary
key)
 SP_helpindex system stored procedure to view the index on a table.
 We can have only one clustered index in one table ,but we can have one
clustered index on multiple columns and that type of index is called
composite index.

create table MyStudents(S_id int Primary key,SName varchar(40) Not Null,Address


varchar(50),Class varchar(50),S_Age int);

-----insert table Values-----

insert into MyStudents values(1,'Rohan','Mumbai','12th',23);


insert into MyStudents values(2,'Mohini','Mulund','10th',20);
insert into MyStudents values(3,'Kumar','Chembur','MSC',25);
insert into MyStudents values(4,'Kartik','Ghatkor','15th',24);
insert into MyStudents values(5,'Amar','Mumbai','12th',23);
insert into MyStudents values(6,'Mohan','Borivali','10th',23);

select * from MyStudents;

----we can't delete clustered this methon-------

drop index MyStudents.[PK__MyStuden__A3DCCCA55DC74147];

NON-CLUSTER INDEX
40

 A non-clustered index is as to an index of a book.


 The data is stored in one place and index is stored in another place
 Since the non-clustered index is stored separately from the actual data .a table
can have more than one non-clustered index.
 Just like how a book can have index by chapters at the beginning and another
index by common term at the end.

create table MyStudents(S_id int Primary key,SName varchar(40) Not Null,Address


varchar(50),Class varchar(50),S_Age int);

-----insert table Values-----

insert into MyStudents values(1,'Rohan','Mumbai','12th',23);


insert into MyStudents values(2,'Mohini','Mulund','10th',20);
insert into MyStudents values(3,'Kumar','Chembur','MSC',25);
insert into MyStudents values(4,'Kartik','Ghatkor','15th',24);
insert into MyStudents values(5,'Amar','Mumbai','12th',23);
insert into MyStudents values(6,'Mohan','Borivali','10th',23);

select * from MyStudents;

create nonclustered index newNon_clustered on MyStudents (Address asc);

---How to add non- clusered index------

create clustered index my_clustered on MyStudents(S_id asc);

---How to multiple add non- clusered index------


create nonclustered index newNon_clustered on MyStudents (SName Asc,Address asc);

sp_helpindex MyStudents;

**************************************************************

Computed Columns

create table Employee(EmpId int identity, EmpName varchar(50),Degignation varchar(50),


[BasicPay] int,
[House Rent Allowance] int ,[Convenece Allowance] int,[Medical Allowance] int,
[Gross pay] as [BasicPay] + [House Rent Allowance]+[Convenece Allowance] +[Medical
Allowance]);

select * from Employee;

insert into Employee values('Rohan','Manager',25000,7000,4000,6000);


insert into Employee values('Kumar','Manager',2000,4000,2000,6000);
insert into Employee values('Surendra','Incharge',20000,6000,2000,6000);
insert into Employee values('Pawan','employee',15000,1500,2000,6000);

Drop table Employee;


41

***************************************************************************************

Cube And RollUp


Cube
 Cube is a aggerate operate that produce a super-aggregate row.
 The summary row is displayed for every possible combination of group
in the result set.
 Cube() in sql server procedure the result set by generating all
combinations of columns specified in the GROUP BY CUBE().
 Write a query to receive Sum of salary grouped by all possible
combinations of 2 column (City and Gender) as well GRAND TOTAL.

create table EmlpoyyesDB(id int, EmpName varchar(50), Gender varchar(50),Address


varchar(50) , Salary int);

drop table EmlpoyyesDB;

insert into EmlpoyyesDB values(1,'Kumar','Male','Dadar',23000);


insert into EmlpoyyesDB values(2,'Reshma','Female','Pawai',25000);
insert into EmlpoyyesDB values(3,'Ramesh','Male','Dadar',23000);
insert into EmlpoyyesDB values(4,'Sukanya','Female','Thane',20000);
insert into EmlpoyyesDB values(5,'Hari','Male','Mulund',30000);
insert into EmlpoyyesDB values(6,'Rohini','Female','Dombivli',20000);
insert into EmlpoyyesDB values(4,'devanand','Male','Thane',25000);
insert into EmlpoyyesDB values(5,'Sukhdev','Male','Mulund',20000);

select * from EmlpoyyesDB;

select Address, sum(Salary) as Total_Salary from EmlpoyyesDB group by Address;

-----------cube----------
select Address,Gender, sum(Salary) as Total_Salary from EmlpoyyesDB group by
cube(Address,Gender);

************************************

ROLLUP
 In additions to the usual rows that are generated by the GROUP BY
clause , it also introduced summary rows into the result set.
 It arrange the groups from the lowest to the highest.
 It is similar to CUBE operator but generates a result set that shows
groups arranged in a hierarchical order.
 Group hierarchy in the result is dependent on the order in which the
columns that are grouped are specified.

-----------rollup (showing seperate data like male and female in Thane)----------


select Address,Gender, sum(Salary) as Total_Salary from EmlpoyyesDB group by
Address,Gender with rollup;
42

or
select Address,Gender, sum(Salary) as Total_Salary from EmlpoyyesDB group by
rollup(Address,Gender);

Grouping set
 The grouping set operator allows us to you group together multiple
grouping of columns followed by an optional grand total row denoted by
parentheses().

 It is more efficient to used GROUPING SET operators instead of multiple


GROUP BY with UNION clauses the letter adds more processing overheads
on the database server.

-----------groupind set (showing seperate data like adress and gender)----------


select Address,Gender, sum(Salary) as Total_Salary from EmlpoyyesDB group by grouping
sets(( Address,Gender),(Address),(Gender),());

or
select Address,Gender, sum(Salary) as Total_Salary from EmlpoyyesDB group by grouping
sets(( Address,Gender),(Address),(Gender),()) order by grouping
(Address),grouping(Gender);

Marge Statements
 The marge statement introduced in sql server 2008.
 The marge Statement allows us to perform insert, updates and delete in
one statement. This means we have no longer have to use multiple
statement to perform insert, update ,delete.
 The merge statement allow you to maintain a target based on certain
join conditions on a source table using a single statement.
 With merge statement we required 2 tables
1. Source Table: Contains the charges that need to be applied to
the target table.
2. Target Table: The table that required changes (insert , Update
and Delete)
 Merge statement joins the target table to the source table by using a
command column in both the tables. Base on the how the rows match up
we can perform insert, update and delete on the target table.

 You can now perform the following actions in the Merge statement :
i. Insert a new row from the source if the row is missing in the
target table.
ii. Update a target row if a record already exist in the source
table.
43

iii. Delete a target row if the row is missing in the source table .

create table EmlpoyyesDB(id int, Name varchar(50), Gender varchar(50),Address varchar(50)


, Salary int);

drop table EmlpoyyesDB;

insert into EmlpoyyesDB values(1,'Kumar','Male','Dadar',23000);


insert into EmlpoyyesDB values(2,'Reshma','Female','Pawai',25000);
insert into EmlpoyyesDB values(3,'Ramesh','Male','Dadar',23000);
insert into EmlpoyyesDB values(4,'Sukanya','Female','Thane',20000);
insert into EmlpoyyesDB values(5,'Hari','Male','Mulund',30000);
insert into EmlpoyyesDB values(6,'Rohini','Female','Dombivli',20000);
insert into EmlpoyyesDB values(4,'devanand','Male','Thane',25000);
insert into EmlpoyyesDB values(5,'Sukhdev','Male','Mulund',20000);

create table MyStudents(id int Primary key,Name varchar(40) Not Null,Address


varchar(50),Class varchar(50),S_Age int);

-----insert table Values-----

insert into MyStudents values(1,'Rohan','Mumbai','12th',23);


insert into MyStudents values(2,'Mohini','Mulund','10th',20);
insert into MyStudents values(3,'Kumar','Chembur','MSC',25);
insert into MyStudents values(4,'Kartik','Ghatkor','15th',24);

drop table MyStudents

select * from EmlpoyyesDB;


select * from MyStudents;

merge MyStudents as T
using EmlpoyyesDB as S
on T.id=S.id
when matched then
update set T.Name=S.Name, T.Address=S.Address
when not matched by target then
insert(id,name,address)values(S.id,S.Name,S.Address)
when not matched by source then Delete;

----------show table------------
select * from EmlpoyyesDB;
select * from MyStudents;

*****************************************************************************

Transaction
 A Transaction is
o A single until of work .
44

Is successful only when all data modification that are ,add in a


o
transaction are committed and saved in the database permanently.
 If the transaction is rolled back or cancelled then it means that the
transaction has encountered errors and there are no changes made to the
contents of the database.
 A transaction can be either committed or rolled back.

 TCL (TRANSFER CONTROL LANGUAGE) commit,Rollback,savepoint.

-----Create Table ---


create table MyStudents(S_id int Primary key,SName varchar(40) Not Null,Address
varchar(50),Class varchar(50),S_Age int);

-----insert table Values-----

insert into MyStudents values(1,'Rohan','Mumbai','12th',23);


insert into MyStudents values(2,'Mohini','Mulund','10th',20);
insert into MyStudents values(3,'Kumar','Chembur','MSC',25);
insert into MyStudents values(4,'Kartik','Ghatkor','15th',24);
insert into MyStudents values(5,'Amar','Mumbai','12th',23);
insert into MyStudents values(6,'Mohan','Borivali','10th',23);
insert into MyStudents values(7,'Suhana','KanjurMarg','12th',21);

select * from MyStudents;

-------------when updated and we want to undo/return data then used transation----


begin transaction ---explicit transaction
update MyStudents set SName='Shamlal' where S_id=6; ---implicit transaction
delete MyStudents where S_id=6;

------want to return data undo----


rollback transaction;

------permantaly data then used transation----------


commit transaction;

Defination of transactions
A logical unit of work must exhibit four properties called the
atomicity consistency ,isolation and durability (ACID) properties to
qualify as a transaction.

1. Atomicity : If the transaction has many operations then all


should be committed .it means ALL or NONE.it manages by
transaction manager. Ex of 2 accounts.

2. Consistency : The sequence of operations must be consistent.

A=3000, B=4000=7000 -before transaction


45

A=3000 – 1000 =2000


B=4000 + 1000 =5000 7000 after transaction

3. Isolation : The operations that are performed must be isolated


from the other operations on the same server or on the same
database. It means each transaction must be executed without
knowing what is happing to other transactions.

--show uncommited data----------


set transaction isolation level read uncommitted;

4. Durability : The operations that are performed on the database


must be saved and stored in the database permanently.

5. When a transaction is started on a connection. all transact SQL


statements are executed on the same connection and are a part of
the connection until the transaction ends.

6. Transactions are managed at the connection ends.

********************************************************************
TRY CATCH
o Implements error handline for transact-SQL that is similar to the
exception handling in the Microsoft visual c# and java languages.

o A group of transact-SQL statements can be enclosed in a TRY


block. if an error occurs in the TRY block, control is passe to
another group of statements that is enclosed in a CATCH block.

o If there is no error occurred in TRY block then CATCH block will


not be executed .

o In TRY block when error occur on the line then after that line no
lines will be executed.

begin try
select 10/0
select * from MyStudents;
end try
begin catch
print 'You canot divided a number by zero '
end catch

begin try
update MyStudents set SName='shital' where s_id=3
46

end try

begin catch
print 'You canot insert string value '
end catch

RETRIVING ERROR INFORMATION


In the scope of CATCH block the following system functions can be used
to obtain information about the errors that caused the CATCH block to
be executed:

 Error_Number() returns the number of the error.


 Error_Severity() returns the severity.
 Error_State() return the error state number.
 Error_Procedure() returns the name of the stored procedure or
trigger where the error occurred.
 Error_Line() returns the line number inside the routine that
caused the error.
 Error_Message() return the complete text of the error message.

These functions return NULL if they called outside the scope of the
CATCH block.Error information can be retrieved by using these
functions from anywhere within the scope of CATCH block.

begin try
update MyStudents set SName='abc' where s_id=3
end try
begin catch
select
ERROR_NUMBER() as [Error Number],
ERROR_SEVERITY() as [Error Severity],
ERROR_STATE() as [Error State Number],
ERROR_PROCEDURE() as [SP Name],
ERROR_LINE() as [Error Line],
ERROR_MESSAGE() as [Error Message]
end catch

**********************************************************************

TRANSACTION WITH TRY CATCH


begin try
47

begin transaction
insert into MyStudents values(7,'Suhana','KanjurMarg','12th',21)
insert into MyStudents values(8,'Shobhana','dadar','12th',21)
commit transaction
print 'Transaction sucefully done';
end try

begin catch
rollback transaction
print 'Tranaction fail';
select ERROR_MESSAGE() as [Error Message]
end catch
***************************************************************************************
TEMPORARY TABLE
 Temporary tables are very similar t the permanent tables .
 A temporary tables in SQL server as the name suggest is a database table that
exist temporarily on the database server.
 Temporary table are created in TempDb.
 Temporary resides in system database in SSMS.
 Temporary tables are very useful when we need to store temporary data.
 Two types of temporary table
i. Local temporary tables
ii. Global temporary tables

 Local temporary tables


 A Local temporary table is available only for the connection that has
created the table.
 A local temporary table is automatically dropped when the connection is
closed
 We have Single # Symbol before the name of local temporary table.
 We can explicitly drop the temporary table by using DROP Table #TableName.
 If the temporary table is create inside the SP (stored Procedure) then it
gets dropped automatically when Stored Procedure completes its execution.

-----temporary table create-------


create table #EmpData( name varchar(50), gender varchar(50));

----how to see temporary table--


select name from tempdb..sysobjects where name like '%EmpData%';

insert into #EmpData values('Rohan','Male');


insert into #EmpData values('Manali','Female');
insert into #EmpData values('Nayana','Female');
insert into #EmpData values('Minar','Male');

select * from #EmpData;


drop table #EmpData;

---------store procedure local table-----


create procedure spEMPData as
begin
-----temporary table create-------
create table #EmpData( name varchar(50), gender varchar(50));
48

insert into #EmpData values('Rohan','Male');


insert into #EmpData values('Manali','Female');
insert into #EmpData values('Nayana','Female');
insert into #EmpData values('Minar','Male');

select * from #EmpData;

end
execute spEMPData;

select * from #EmpData;


drop table #EmpData;
************************************
 GLOBAL TEMPORARY TABLE
i. To create the global temporary table use 2(##) hash symbols
Before the name of the table.
ii. Global temporary tables are accessible or visible in all the
connections.
iii. Global temporary tables destroyed when the last connection
referencing the table is closed.
iv. If you close the connection that has created the global
temporary table the that global temporary table will
automatically deleted.
v. We can create the local temporary table with same name in
different connections but a global temporary table name has
to be unique it means we can’t create the global temporary
table with sane name in different connections.
vi. In the object explore there will be no random numbers
suffixed at the end of the table name.

-----Global temporary table create-------


create table ##GlobalEmpData( name varchar(50), gender varchar(50));

insert into ##GlobalEmpData values('Rohan','Male');


insert into ##GlobalEmpData values('Manali','Female');
insert into ##GlobalEmpData values('Nayana','Female');
insert into ##GlobalEmpData values('Minar','Male');

select * from ##GlobalEmpData;

*****************************************************************
COALESCE() FUNCTION
Return the first non-null value in a list.

----return first value-------------


select coalesce(Null,Null,'Rohan',Null,'This is sql');
----return first value-------------
select coalesce(Null,Null,Null,Null,'This is sql');
49

----isNull check where null value is not-----------


select isnull(Null,Null,'Rohan',Null,'This is sql');
***********************************************************************

CAST() FUNCTION
The cast() function convert a value (of any type) into a
specified datatype.
select cast(23.34 as int )as value;
select cast('2021-05-04' as datetime);

-----table sName and S-id convert dataype using cast----


select SName + ' -' + cast(S_id as varchar) from MyStudents;
select * from MyStudents where cast(S_Age as varchar) = '25';

*****************************************************************************************
CONVERT() FUNCTION
 Convert() function converts a value (of any datatype) into a
specified datatype.

 The Convert() function can be used to display date/time date in


various formats.

 The Convert() function is mostly used to show date time in


different format.

-----same datatype----------
select cast(23.34 as int )as value;
select convert( int ,23.34 )as value;

-----declare datatype----------
declare @num1 decimal=24.5;
select cast(@num1 as int );
select @num1;

declare @num2 decimal=26.456;


select convert( int ,@num2 );
select @num2;

---datetime convert-----
select cast('2021-05-04' as datetime);
select convert( datetime,'2021-05-04');

----current datetime-----
select getdate();

select convert(varchar,getdate());
select convert(varchar,getdate(),0);
select convert(varchar,getdate(),1);
select convert(varchar,getdate(),101);
50

select convert(varchar,getdate(),102) as Todaydate;

*****************************************************************************************

CURSOR
 Cursor is a temporary memory or temporary work station.
 A SQL cursor is a database object that is used to retrieved data
from a result set one row at a time.
 It is allocated by database server at the time of performing DML
operation on table by user.
 Cursor are used to store Database tables.
 It allows you to process individual row returned by query.
 Type of cursors
i. Implicit cursor
 Implicit cursor are also known as default cursor of
sql server.
 These cursor are allocated by sql server when the user
performs DML operations.

ii. Explicit cursor


 Explicit cursor are created by users whenever the user
requires them .
 Explicit cursor are used for Fetching data from Table
in Row-by-Row manner.

 Methods of cursors
 Next
 Prior
 First
 Last
 Absolute n
 Relative n

 The following step are involved in sql cursor life cycle:


A. Declaring cursor
 A cursor is declared by defining the SQL statement.
 declare myCursor cursor scroll for select * from MyStudents

B. Opening cursor
 A cursor is opened for storing data retrieved from
the result set.
 open myCursors

C. Fetching cursor
51

 When a cursor is opened ,rows can be fetched from


the cursor one by one or in a block to do data
manipulation.
 fetch first from myCursors

D. Closing cursor
 The cursor should be closed explicitly after data
manipulation.
 close myCursors

E. De-allocating cursor
 Cursor should be deallocated to delete cursor
definition and release all the system resource
associated with the cursor.
 deallocate myCursors;

 We can use cursor in 2 ways


1. With cursor variables

------with cursor--------------
declare myCursors cursor scroll for select * from MyStudents
open myCursors
fetch first from myCursors
fetch next from myCursors
fetch last from myCursors
fetch prior from myCursors
fetch absolute 4 from myCursors
fetch relative 3 from myCursors
fetch relative -1 from myCursors
close myCursors
deallocate myCursors;

2. Without cursor variables

------with cursor--------------
declare myCursors cursor scroll for select S_id,SName from MyStudents
declare @Std_id int, @Std_Name varchar(50)
open myCursors
fetch first from myCursors into @Std_id ,@Std_Name
print'Student is :' + cast(@Std_id as varchar(50))+' ' +@Std_Name

fetch next from myCursors into @Std_id ,@Std_Name


print'Student is :' + cast(@Std_id as varchar(50))+' ' +@Std_Name

fetch last from myCursors into @Std_id ,@Std_Name


print'Student is :' + cast(@Std_id as varchar(50))+' ' +@Std_Name
52

fetch prior from myCursors into @Std_id ,@Std_Name


print'Student is :' + cast(@Std_id as varchar(50))+' ' +@Std_Name

fetch absolute 4 from myCursors into @Std_id ,@Std_Name


print'Student is :' + cast(@Std_id as varchar(50))+' ' +@Std_Name

fetch relative 3 from myCursors into @Std_id ,@Std_Name


print'Student is :' + cast(@Std_id as varchar(50))+' ' +@Std_Name

fetch relative -1 from myCursors into @Std_id ,@Std_Name


print'Student is :' + cast(@Std_id as varchar(50))+' ' +@Std_Name
close myCursors
deallocate myCursors;
*************************************************************************************
OVER CLAUSE WITH PARTITION

 The over clause with partition by is used to split data into


partition . The specified function operates for each partition.

 Any of the following functions can be used.


Sum(), Avg(), Count(), Min(), Max(), Row_Number(), Rank(),
Dense_Rank() etc.

 Windowing in SQL server is done by the over clause that was


introduce in SQL server 2005.

 Windowing of the data in SQL Server or the window function is


applied to a set of rows (Partitioned data based upon some column
known as the a window ) to rank or aggregate values in that
window or partition set.

 Windowing basically creates a window of records for every record.


That window is then used for making computations.

 The difference is With GROUP BY you can only have the aggregate
values for the column that are not include in GROUP By.

 In contrast using windowing aggregate functions instead of GROUP


BY you can retrieve both aggregated and non-aggregated values

create table Employee(id int ,Name varchar(50), Gender varchar(50), salary int,Age int);

drop table Employee;


insert into Employee values(1,'Kumar','male',20000,35);
insert into Employee values(2,'Rashmi','female',22000,25);
insert into Employee values(3,'rajan','male',25000,30);
insert into Employee values(4,'Kumari','female',20000,25);
53

insert into Employee values(5,'Manohar','male',15000,24);

select * from Employee;

select gender,count(*) as Gender_Total from Employee group by gender;

---subquery---(--inner join--)
select name,salary ,Employee.gender ,genders.Gender_Total from Employee
inner join
(select gender,count(*) as Gender_Total from Employee group by gender)as genders
on Employee.gender=genders.gender;

----over clause----
select name,gender,salary,count(gender) over (partition by gender)as Gendet_Total from
Employee;

---Min/Max/Average--------------
select gender,count(*) as Gender_Total,
Max(salary) as Max_salary ,
Min(salary) as Min_Salary,
avg(salary) as Avg_SAlary
from Employee group by gender;

-----partition by--------
select name,gender,salary,
count(gender) over (partition by gender) as Gender_Total,
Max(Salary) over (partition by gender) as Max_Salary,
Min(Salary) over (partition by gender) as Min_salary,
Avg(Salary) over (partition by gender) as Avg_Salary
from Employee;

**********************************************************************
RETRIVING LAST GENERATED IDENTITY VALUE

 There are 3 functions to get last generated identity column value


in SQL server.
i. Scope_Identity() -> Function
ii. @@identity -> Global variable
iii. Ident_Current() -> Function

 The scope_identity() function returns the last identity created


in the same session and the same scope.

 The @@identity returns the last identity created in the same


session and in any scope.

 The ident_current(table_name) return the last indentity created


for a specific table or view in my session.
54

create table Employee(id int ,Name varchar(50), Gender varchar(50), salary int,Age int);

drop table Employee;


insert into Employee values(1,'Kumar','male',20000,35);
insert into Employee values(2,'Rashmi','female',22000,25);
insert into Employee values(3,'rajan','male',25000,30);
insert into Employee values(4,'Kumari','female',20000,25);
insert into Employee values(5,'Manohar','male',15000,24);

select * from Employee;

create table customer_tbl( id int identity ,name varchar(50));

insert into customer_tbl values('Kumar');


insert into customer_tbl values('Sam');
insert into customer_tbl values('Manali');
insert into customer_tbl values('Sonali');
insert into customer_tbl values('Radha');

select * from customer_tbl;

select SCOPE_IDENTITY();
select @@IDENTITY;

create table customer_detail( id int identity ,date_time datetime);


insert into customer_detail values(getdate());

select * from customer_detail;

create trigger ForCustomerDetail on customer_tbl after insert as


begin
insert into customer_detail values(getdate());
end;

select IDENT_CURRENT ('customer_detail');

*********************************************************************
Row_Number function

 More specifically returns the sequential number of a row within a


partition of a result set , starting at 1 for the first row in
each partition.
 Row_Number is a temporary value calculated when the query is run
to persist numbers in a table use identity property.

create table Employee(Name varchar(50), Gender varchar(50), salary int,Age int);

drop table Employee;


insert into Employee values('Kumar','male',20000,35);
insert into Employee values('Rashmi','female',22000,25);
insert into Employee values('rajan','male',25000,30);
insert into Employee values('Kumari','female',20000,25);
55

insert into Employee values('Manohar','male',15000,24);

select * from Employee;

select *, ROW_NUMBER() over(order by name ) as Numbering from Employee;

select *, ROW_NUMBER() over(order by name desc) as Numbering from Employee;

----partition by gender---------
select *, ROW_NUMBER() over(partition by gender order by name desc) as Numbering from
Employee;

---partition by Age-----
select *, ROW_NUMBER() over(partition by Age order by name desc) as Numbering from
Employee;

***************************************************************

Rank & Dense_Rank


 The Rank, Dense_Rank and row_Number functions are used to
retrieved an increasing integer value.

 They start with a value require the ORDER BY clause to function


properly However by clause is option.

 In case of the partition data the integer counter is reset to 1


for each partition.

-----rank order by Age- here skip number after same no----


select name,gender,age,salary, rank() over (order by age desc) as Rabk from Employee;

---rank partition by gender----


select name,gender,age,salary, rank() over (partition by gender order by age desc) as
Rabk from Employee;

----dense rank- here not skip any number-----


select name,gender,age,salary, dense_rank() over (order by age desc) as Rabk from
Employee;

---apply rank and dense_rank one sentence----


select name,gender,age,salary,rank() over (order by age desc) as [Rankkkk],dense_rank()
over (order by age desc) as [Denssse_Rank] from Employee;

**********************************************************************
CROSS APPLY & OUTER APPLY
56

 Sql Server 2005 introduced the apply operator.

 There are 2 forms of apply operator.

A. Cross Apply

B. Outer Apply

 Appy operator is like a join clause and it allow joining between


two table expression i.e joining a left table expression.
 But if you want to use cross or outer Apply then right table
expression should be table valued function.
 It is use to joint with a table-valued function.
 The different between the joint and Apply operator becomes
evident when you have a table-valued expression on the right side
row from the left table expression.
 The apply operator allows you to join two table expression the
right table expression is processed every time for each row from
the left table expression.
 The left table expression is evaluate first and right table
expression is evaluated against each row of the left table
 The left table expression is evaluated first then the right table
expression is evaluated against each row of the table expression
for the final result set.
 Cross Apply is just like inner join.
 Outer Apply is just like left join.
 Cross Apply returns only matching rows.
 Outer Apply returns both matching and non-matching rows the
unmatched column of the table valued function will be set to
NULL.
 If you want to use joins then you have to use tables as a result-
set on both left or right but if you want to used table valued
function as a result-set then you have to use Cross Apply or
Outer Apply.
57

-----Create Table ---


create table MyStudents(S_id int Primary key,SName varchar(40) Not Null,Address
varchar(50),Class varchar(50),S_Age int);

-----insert table Values-----

insert into MyStudents values(1,'Rohan','Mumbai','12th',23);


insert into MyStudents values(2,'Mohini','Mulund','10th',20);
insert into MyStudents values(3,'Kumar','Chembur','MSC',25);
insert into MyStudents values(4,'Kartik','Ghatkor','15th',24);
insert into MyStudents values(5,'Amar','Mumbai','12th',23);
insert into MyStudents values(6,'Mohan','Borivali','10th',23);

------------------Another Table -------------------


create table StudentFunctions(F_RollNo int ,SName varchar(40) Not Null,Address
varchar(50),Class varchar(50), t_id int);

insert into StudentFunctions values(1,'Arayan','Mumbai','12th',3);


insert into StudentFunctions values(2,'Manali','Mulund','10th',4);
insert into StudentFunctions values(3,'Kumari','Chembur','MSC',1);
insert into StudentFunctions values(4,'Kartika','Ghatkor','15th',2);
insert into StudentFunctions values(5,'Amarish','Mumbai','12th',5);

---Show data table-----


select * from MyStudents;
select * from StudentFunctions;

---inner join------
select * from MyStudents inner join StudentFunctions on
MyStudents.S_id=StudentFunctions.t_id;

---inner join selected column------


select s.SName,s.Class,t.SName,t.Address
from MyStudents as s
inner join StudentFunctions as t
on s.S_id=t.t_id;

---left join----
select s.SName,s.Class,t.SName,t.Address
from MyStudents as s
left join StudentFunctions as t
on s.S_id=t.t_id;

Create function Fn_GetStudentDetail(@Student_id int) returns table as return ( select *


from MyStudents where S_id=@Student_id);

select * from Fn_GetStudentDetail(2);

---Cross apply selected column------


select s.SName,s.Class,t.SName,t.Address
from MyStudents as s
cross apply Fn_GetStudentDetail(s.S_id) as t
---on s.S_id=t.t_id;---
58

****************************************************************
CTE (Common Table Expression)
 CTE stands for common table expression
 CTE is introduced in SQL Server-2005.
 A CTE allow you to defined a temporary result set that can be
linked immediately with the select, insert, update or delete
statement.
 CTE is similar to a temporary resultset defined within the
execution scope of the single SELECT, INSERT, UPDATE, DELETE or
CREATE VIEW statement.
 The CTE can also used in the view
 A CTE is defined at the start of a query and can be referenced
several times in the outer query.
 Key advantages Of CTEs are improved readability and ease in
maintenance of complex queries.
 Syntax: With expression_name(Column1, column2,…)
As ( CTE_definition )
 CTE exist in memory only while the query is running .After the
query is run CET is discarded it can’t be used for the next SQL
query unless we defined it against .Still the same CTE might be
reference several times in the main query and any subqueries.
 A view is a stored SQL query that is execute each time you
reference it in another query .Note that a view doesn’t store the
output of a particular query -it stores the query itself.
 The key thing to remember about SQL view is that in contrast to a
CTE a view is a physical object in database and is stored on a
disk .However views store the query only not the data returned by
the query .The data is computed each time you reference the view
in your query.
59

 CTEs are limited in scope to the execution of the outer


query .Hence when the outer query ends the lifetime of the CTE
will end.
 You need to defined a name for a CTE and also defined unique
names for each of the columns reference in the SELECT clause of
the CTE.

create table Employee(id int ,Name varchar(50), Gender varchar(50), salary int,Age int);

drop table Employee;


insert into Employee values(1,'Kumar','male',20000,35);
insert into Employee values(2,'Rashmi','female',22000,25);
insert into Employee values(3,'rajan','male',25000,30);
insert into Employee values(4,'Kumari','female',20000,25);
insert into Employee values(5,'Manohar','male',15000,24);

select * from Employee;

with New_CTE as (select * from Employee where Gender='Male')


----select * from New_CTE--
select count(*) from New_CTE

with New_CTE as (select * from Employee where Gender='Male')


---select 'Hello World'--
---number of males---
select * from New_CTE where Age>=25

---column of CTE---
with New_CTE(E_id,E_Name,E_salary) as (select id,Name,salary from Employee where
Gender='Male')
select E_id,E_Name from New_CTE

---all employee table in CTE---


with New_CTE as (select * from Employee)
select * from New_CTE

---all employee table in insert row CTE---


with New_CTE as (select * from Employee)
insert New_CTE values(1,'Ronak','Male',230000,26);

---all employee table in update row CTE---


with New_CTE as (select * from Employee)
update New_CTE set id=6, Name='Pushparaj' where Age=26;

---all employee table in delete row CTE---


with New_CTE as (select * from Employee)
delete new_CTE where id=6;
60

---create view-----
create view vWMyNewView
as
with New_CTE as (select * from Employee where Age>=25)
select * from New_CTE

select * from vWMyNewView;

---combination of two CTE using union key----


with New_CTE as (select * from Employee where Age=25),
New_CTE2 as (select * from Employee where Age=30)

select * from New_CTE union all select * from New_CTE2

CTE Vs Sub Query


 CTE is create before the outer query.
 Sub query is created after the outer query.
*********************************************************************
Date & Time Functions
 The most difficult part when working with dates is to be sure
that the format of the date you are timing to insert, Matches the
format of the date column in the database.
 As long as your data containing only the date portion , your
queries will work as expected . However if a time portion is
involved it gets complicated.
 We will look at the most import
 Type of Date Function
1) GetDate() :-return current Date and Time
select GetDate();
---convert datetime----
select convert(varchar, getdate(),100);

2) SysDateTime() :- Return the current date and time , return 7


precision of second
select SysDateTime()

3) Current_TimeStamp :-Return the current date and time


61

select Current_TimeStamp;

4) DateName() :-Return the name of the day , year , month etc


from a given date.
select DateName(month,getdate());
select DateName(year,getdate());
select DateName(day,getdate());

5) DateDiff():-Return the difference between two dates.


select DateDiff(year, '02-01-2019',getdate());
select DateDiff(month, '02-01-2019',getdate());
select DateDiff(day, '02-01-2019',getdate());
select DateDiff(hour, '02-01-2019',getdate());

6) DateAdd():-Adds or subtract a specified time interval from a


date.
select DateAdd(day, 2, getdate());
select DateAdd(day, -3, getdate());
select DateAdd(month, 2, getdate());

7) DatePart() :- Returns a single part of adate/time


select DatePart(year,getdate()) as 'current year'; //alias for column name
select DatePart(month,getdate());
select DatePart(day,getdate());

8) Day() :-Return the day from the given date


select Day(getdate());

9) Month():-Return the month from the given date


select month(getdate());

10) Year() : -Return the year from the given date.


select year(getdate());

11) IsDate():- Cheack if the expression is a valid date.


62

 The isDate() function check an expression and returns 1


if it is a valid date, otherwise 0.
select IsDate('02-01-1999'); // 1
select IsDate('02-011999'); // 0

----------------------END-----------------------------

You might also like