7/31/2019 SQL Server Notes
1/75
SQL-SERVER DATA TYPES NOTES:-
1. BIGINT2. BINARY
3. BIT
4. CHAR5. DATETIME
6. DECIMAL
7. FLOAT
8. IMAGE9. INT
10. MONEY
11.NCHAR
12.NTEXT13.NUMERIC
14.NVARCHAR15. REAL
16. SMALLDATETIME
17. SMALLINT18. SMALLMONEY
19. SQL_VARIANT
20. TEXT
21. TIMESTAMP22. TINYINT
23. UNIQUEIDENTIFIER24. VARBINARY25. VARCHAR
7/31/2019 SQL Server Notes
2/75
*We can execute more than one command on the prompt usingterminator (;) in Oracle/MySQL/SQL-server and in SQL-server without
terminator too.
The Create Table Command
In Oracle
create table student
(roll number,
name varchar2(50))
In SQL Server
create table student
(roll integer,
name varchar(50))
Note:-Number or numeric datatype not allowed, varchar2 is not
allowed
In MYSQL
create table student
(roll integer,
name1 varchar(50));
Note:-Number datatype not allowed,varchar2 is not allowed
Insertion of data into table
In Oracle
insert into student values(1,'amit');
7/31/2019 SQL Server Notes
3/75
In SQL Server
insert into student values(1,'amit');
In MYSQL
insert into student values(1,'amit');
In Oracle
insert into student (name,roll) values('amit',2);
In SQL Server
insert into student (name,roll) values('amit',2);
In MYSQL
insert into student (name,roll) values('amit',2);
Viewing Data in the Table
# All Rows and all Column:-
In Oracle
select * from student;
In SQL Server
select * from student;
In MYSQL
7/31/2019 SQL Server Notes
4/75
7/31/2019 SQL Server Notes
5/75
select name from student where roll=1;
In SQL Server
select name from student where roll=1;
In MYSQL
select name from student where roll=1;
# Elimination of duplication from theSelectstatement:-
In Oracle
select distinct name from student;
select distinct roll,name from student;
select distinct * from student;
In SQL Server
select distinct name from student;
select distinct roll,name from student;
select distinct * from student;
In MYSQL
select distinct name from student;
select distinct roll,name from student;
select distinct * from student;
7/31/2019 SQL Server Notes
6/75
Note:-If distinct is applied with two or more column then union of
this column should be unique in the output of
Oracle/SQLServer/Mysql
# Sorting data in a table:-
Asending Order
In Oracle
select * from student order by roll;
select * from student order by roll,name;
In SQL Server
select * from student order by roll;
select * from student order by roll,name;
In MYSQL
select * from student order by roll;
select * from student order by roll,name;
Desending Order
In Oracle
select * from student order by roll desc;
select * from student order by roll,name desc;
7/31/2019 SQL Server Notes
7/75
select * from student order by name,roll desc;
In SQL Server
select * from student order by roll desc;
select * from student order by roll,name desc;
select * from student order by name,roll desc;
In MYSQL
select * from student order by roll desc;
select * from student order by roll,name desc;
select * from student order by name,roll desc;
Note:- In descending the records are descended by the right hand
side of the specified column;But in ascending the records are sorted
by left hand side of the specified columns;
############################################
In SQL Server
select roll,name,position=case roll
when 1 then 'FIRST'
when 2 then 'SECOND'
when 3 then 'THIRD'
else 'FAIL'
7/31/2019 SQL Server Notes
8/75
end from stud
############################################
Creating a table from a table
In Oracle
create table student1 as select * from student
create table student5 as select roll from student;
create table student9 (roll) as select (roll) from student
create table student2 (roll,name) as select roll,name from student
create table student4(roll_no) as select roll from student;
NOTE-
(1) It will create a table as student where data is also transffered in
another command(2) Afterselectcommand the column name should not be in
parenthesis if it contaion more than one column;
(3) We can create a new table using existing table with changed
column name.
In SQL Server
************************************************
In MYSQL
create table student1 as select * from student
7/31/2019 SQL Server Notes
9/75
7/31/2019 SQL Server Notes
10/75
insert into student select roll from student1;
(Not Working, not enough values(because of no of columns))
In my sql
insert into student select * from student1;
insert into student select roll,name from student1;
insert into student select roll from student1;
(Not Working, not enough values(because of no of columns))
DELETE
In oracle
delete student1;
delete from student1;
delete student where roll=2;
delete from student where roll=2;
in sql server
delete student1;
delete from student1;
delete student where roll=2;
delete from student where roll=2;
in mysql
delete student1;(not working)
delete from student1;
delete student where roll=2;(not working)
delete from student where roll=2;
7/31/2019 SQL Server Notes
11/75
Updation
Update
In oracle
update student set name='amit';
update student set name='amit' where roll=2;
in sqlserver
update student set name='amit';
update student set name='amit' where roll=2;
in mysql
update student set name='amit';
update student set name='amit' where roll=2;
Alter (verifying the structure of table)
In oracle
alter table student
add (address varchar2(50));
alter table student
add address varchar2(50);
Note: - the column name must not be as add in alter
command; as well as in create table command;
7/31/2019 SQL Server Notes
12/75
In sql server
alter table student
add (address varchar(50));(not working due to parenthsessis)
alter table student
add address varchar(50);
Note: - the column name must not be as add in altercommand; as well as in create table command;
In my sql
alter table student
add (address varchar(50));
alter table student
add address varchar(50);
Note: - the column name must not be as add in alter
command; as well as in create table command;
Modify:-
In oracle
alter table student
modify
address varchar2(75);
7/31/2019 SQL Server Notes
13/75
alter table student
modify
(name varchar2(60));
note:-we can increase the size of a column but we cant decease the size if
column is not empty.
Note:-we cant modiy the datatype of column if column is not empty
We cannot change the name of table and column, we canot drop a
column with modify
In sql server
alter table employee
alter column emp_name varchar(50)
In mysql
alter table student
modify
address varchar2(75)
note:-we can not use parenthesis after modify clause
note:-we can increase the size of a column but we can decease the size of
column until the maximum data size entered in a column.
Note:-we cant modiy the datatype of column if column is not empty
We cannot change the name of table and column using ALTER with
modify command,
Drop
7/31/2019 SQL Server Notes
14/75
In oracle
alter table student
drop column
sss;
note:- column keyword should be used;
note:-this sql will drop column in both conditions if data exists or not.
note:- you cannot drop all columns in a table with alter table drop
command.
note:- you cannot drop more than one column in a single statement in a
table with alter table drop command.
In sql server
ALTER TABLE student
DROP COLUMN address
In mysql
alter table student
drop column
sss;
alter table student
drop
sss;
note:-this sql will drop column in both conditions if data exists or not.
note:- you cannot drop all columns in a table with alter table drop
command.
7/31/2019 SQL Server Notes
15/75
note:- you cannot drop more than one column in a single statement in a
table with alter table drop command.
Renaming a Table
In oracle
rename student to s1;
note:-table keyword must not be used;
in sql server
sp_rename 'abc','student1'
note :-abc is old object name and student1 as new object
name;
sp_rename renames all object in the data base;
In my sql
rename table student to s1;
note:-table keyword should be used;
Dropping Table:-
In oracle
drop table student1;
7/31/2019 SQL Server Notes
16/75
In Sql server
drop table student1;
In Mysql
drop table student1;
FINDING OUT THE ALL TBALE ACCESSED BY A USER
IN ORALE
select * from tab;
NOTE:-TAB IS RESRVE KETYWORD
IN SQL SERVER
Sp_help
IN MYSQL
Show tables;
DESCRIBE A TABLE
In oracle
desc student;describe student;
in sql server
7/31/2019 SQL Server Notes
17/75
sp_help student;
in mysql
desc student;
describe student;
OPERATORS:-
Arithmetic
operator
Oracle SQL-
Server
MYSQL
Addition + + +
Multiplication * * *
Subtraction - - -
Division / / /
Exponentiation **
Enclosed
Operation
() () ()
Modulo Used Modfunction
% Used Modfunction,%
Assignment operator Oracle SQL-Server MYSQL
Assignment = = =
Bitwise operator Oracl
e
SQL-
Server
MYSQL
BITWISE AND & &
BITWISE OR | |
Bitwise
EXCLUSIVE OR
^ ^
7/31/2019 SQL Server Notes
18/75
Bitwise SHIFT
LEFT
>
BITWISE NOT ~ ~
Comparison
operator
Oracle SQL-
Server
MYSQL
Less Than < < > >
Equal To = = =
Not Equal !=, !=, !=,
Not Less Than !Greater Than
Equal To
>= >= >=
Less than Equal to
7/31/2019 SQL Server Notes
19/75
NOT BETWEENY
NOT IN Y Y
NOT LIKE Y
REGEXP Y
NOT REGEXP Y
Logical operator Oracle SQL-Server MYSQL
AND Y Y Y(&&)
OR Y Y Y(||)
XOR Y
NOT Y Y Y(!)
String operator Oracle SQL-Server MYSQL
CONCATENATION || +
Unary operator Oracle SQL-Server MYSQL
POSITIVE + + +
NEGATIVE - - -
Truncate table
In oracle
7/31/2019 SQL Server Notes
20/75
truncate table student;
in sql server
truncate table student;
in mysql
truncate table student;
note:-
1.Truncate operation drop and recreate the table which is muchfaster than deleting rows one by one.
2.truncate operation are not transaction safe and generate error if
and active transaction or an active table lock exitx.
3.the number of deleted rows are not returned;
Drop table (Destroying table)
In oracle
drop table student;
in sql server
drop table student9;
in mysql
drop table student9
Grouping data from tables in SQl
7/31/2019 SQL Server Notes
21/75
In oracle
select roll from student group by roll,name;
select sum(roll) from student group by name;
select sum(roll),name from student group by name;
select sum(roll),name from student group by name having
name='amit';
select sum(roll),name from student group by name having
sum(roll)>5
In sql server
select sum(roll) from student group by name
select sum(roll),name from student group by name
select sum(roll),name from student group by name having name='amit'
select sum(roll),name from student group by name having
sum(roll)>5
In mysql
select sum(roll) from student group by name1;
select sum(roll),name1 from student group by name1;
7/31/2019 SQL Server Notes
22/75
select sum(roll),name1 from student group by name1 having
name1='amit';
select sum(roll),name from student group by name having
sum(roll)>5
having clause:-
In oracle
select sum(roll),name from student group by name having
name='amit';
In sql_server
select sum(roll),name from student group by name having
name='amit'
In mysql
select sum(roll),name1 from student group by name1 having
name1='amit';
Notes for group by and having clause
7/31/2019 SQL Server Notes
23/75
1. Column listed in the select statement has to be listed in
group by clause
2. Column listed in group by clause need not be listed in select
statement
3. Only group function can be used in the having clause.
4. The group function listed in having clause needs not listed in
select statement.
Note:-function that act on the set of values is called group
function ex-sum, count etc.
*********************************Group by rollup
Group by cube
ALIAS
In oracle
In sql_server
SELECT roll as 'ROLL',name as 'STUDENT' FROM STUD
SELECT roll 'ROLL',name 'STUDENT' FROM STUD
SELECT roll "ROLL",name "STUDENT" FROM STUD
7/31/2019 SQL Server Notes
24/75
In mysql
7/31/2019 SQL Server Notes
25/75
To view the constraints applied on the table
sp_helpconstraint tablename
CONSTRAINTBUSINES RULES which are inforced on data being stored in a table are calledconstraints.
Types of data constraints:-
1.input out put constraints.
2.business rules constraints.
Input/out put constraints:-=
primary keya. It defines column as maindatory column that is the column cant be left blank.
as the not NULL attribute is active.
b. Primary is a column ar a set of column that uniquely identify a column. its
main purpose is to record uniqueness.
c. Primary key will also not allow null value.
d. Primary key helps to relating tables with one another.
e. Primary key cant be long or long row data type,f. Only one primary key is allowed per table.
g. Unique index is created automatically if there is a primary key.
h. One table can combined up to 16 column in a composite column
i. A single column primary key is called simple key.j. A multi column primary key is called a composite primary key.
Primary key constrained defined at column level
Syntax:- () primary key
create table testing_pk
(roll int not null primary key,n int identity,
name1 varchar(20))
Primary key constraint defined at table level
7/31/2019 SQL Server Notes
26/75
Syntax:-
Primary key (,)
create table testing_pk(id int not null ,
r_no int identity,
name1 varchar(20),
primary key (id,r_no))
Note:-table level uniqness depends on the combination of column values.
correct/wrong insertion are:-
insert into class values('r3','c3','amit'); ->correct
insert into class values('r3','c3','amit'); ->wrong
insert into class values('r4','c3','amit'); ->correct
insert into class values('r3','c4','amit'); ->correct
insert into class values('r5','c5','amit'); ->correct
Unique key(1) Unique key will not allow duplicate value.
(2)Unique index created automatically.
(3) A table can have more than one unique key which is not possible in primary key.
(4)unique key can combined upto 16 columns in a composite unique key.(6)The unique key constraint permits one entry of NULL in to the column.
Unique key constraint defined at column level
Syntax:- () unique
create table s1(
roll int identity,
name varchar(10) unique)
Unique key constraint defined at Table level
Syntax:- Unique (,)create table r1(
roll varchar(10),
class varchar(10),
7/31/2019 SQL Server Notes
27/75
name varchar(10),
unique(roll,class))
NULL Constraint defined at the column level only
By default Oracle store NULL,Data type of column does not matter.
NOT NULL Constraint defined at the column level only
SYNTAX:- () NOT NULL
create table r2(
roll varchar(10) not null)
Foreign key
Foreign Key is a column(s) that references a column(s) of a table and it can
be the same table also.
Parent that is being reference has to be unique or primary key.
Child may have duplicates and NULLs but unless it is specified.
Foreign Key Constraints can be specified on child but not on parent.
Parent record can be deleted provided no child records exists. Master table can not be updated if child record exists.
Records can not be inserted into a detail table if corresponding record in amaster table do not exists.
Records of the master table can not be deleted if corresponding records in the
detail table actually exists .
We can not drop a table if it is referenced by other child table.
Foreign key constraint defined at column level
Syntax:-
() references tablename(column name)
create table room(
r_id int foreign key references student,
room_id varchar(30)
)
7/31/2019 SQL Server Notes
28/75
create table room(
r_id int foreign key references student(roll),
room_id varchar(30))
create table room(
r_id int references student(roll),
room_id varchar(30))
Foreign key constraint defined at Table level
Syntax:-
foreign key (column name, column name) references tablename.(column name,column name)
create table continent(
c_id varchar2(10),r_id varchar2(10),
unique(c_id,r_id));
create table country3(
con_id varchar(10),
rd_id varchar(10),
cry varchar(10),
constraint u3
foreign key(con_id,rd_id) references continent(c_id,r_id))
On delete no action It is by default setting.In this setting ca not delete a record in master table if it
exists in detail table.
On update no action It is by default setting.In this setting ca not update a record in master table if
it exists in detail table.
On delete cascade
7/31/2019 SQL Server Notes
29/75
MASTER:
create table continent(c_id varchar(10) primary key,
c_name varchar(20))
DETAILED:
create table country(
con_id varchar(10) references continent(c_id) on delete cascade,
cry_id varchar(10),
con_name varchar(20))
NOTE:- When a row of Master table is deleted all rows of detail table referencing
the row of master table deleted.
On delete set NULL
Not available/working in sql server
On update cascade
create table continent(c_id varchar(10) primary key,
c_name varchar(20))
create table country(
con_id varchar(10) references continent(c_id) on update cascade,
cry_id varchar(10),con_name varchar(20))
NOTE:- When a row of Master table is updated all rows of detail table referencing
the row of master table updated.
CHECK (column level)
create table stud1(
roll int check(roll>1),
name varchar(15) check( name like 'A%'))
7/31/2019 SQL Server Notes
30/75
CHECK (Table level)
create table stud1(
roll int ,
name varchar(15),addr varchar(30),
sex varchar(6) default 'MALE',
check (roll >1), check( name like 'A%'))
DEFAULT VALUE CONCEPTS
Syntax:-
() DEFAULT ()
create table stud1(
roll int ,
name varchar(15),addr varchar(30),
sex varchar(6) default 'MALE',
check (roll >1), check( name like 'A%'))
CREATION OF USER CONSTRAINTSSYNTAX:-
Constraint
create table class1(roll int
constraint abc check(roll> 100))
Note:-always make constraint using constraint name for future alteration.It is a good
practice.
Alter Constraints
alter table class1
7/31/2019 SQL Server Notes
31/75
add constraint abc primary key(roll),check(roll
7/31/2019 SQL Server Notes
32/75
INNER JOIN(equi join)
Table-> emp_master;
create table emp_master(emp_no int not null,
fname varchar(25),
dept varchar(25),desig varchar(25),
branch_no int)
Table->branch_master;
create table branch_master(name varchar(10),
branch_no int not null)
insert into emp_master values(1,'amit','computer','programmer',1)insert into emp_master values(2,'balram','computer','programmer',1)
insert into emp_master values(3,'verma','computer','programmer',2)
insert into emp_master values(4,'verma','computer','programmer',3)
select * from emp_master
Emp_no fname dept design branch_no
1 amit computer programmer 1
2 balram computer programmer 13 verma computer programmer 24 verma computer programmer 3
insert into branch_master values('patna',1)insert into branch_master values('delhi',2)
insert into branch_master values('gaya',3)
select * from branch_master
name branch_nopatna 1
delhi 2
gaya 3
select e.emp_no,e.fname,b.name,e.dept,e.desigfrom emp_master e, branch_master b
7/31/2019 SQL Server Notes
33/75
where b.branch_no=e.branch_no
or
select e.emp_no,e.fname,b.name,e.dept,e.desig
from emp_master e inner join branch_master b on
b.branch_no=e.branch_no
emp_no fname name dept desig
1 amit patna computer programmer
2 balram patna computer programmer
3 verma delhi computer programmer4 sanjay gaya bts guide
Outer join
Table emp_master
create table emp_master(emp_no int not null,
fname varchar(25),
dept varchar(25),desig varchar(25),
branch_no int)
insert into emp_master values(1,'amit','computer','programmer',1)insert into emp_master values(2,'balram','computer','programmer',1)
insert into emp_master values(3,'verma','computer','programmer',2)
insert into emp_master values(4,'verma','computer','programmer',3)insert into emp_master values(5,'krisna','bialogy','teacher',4)
insert into emp_master values(6,'babloo','math','reader',5)
select * from emp_master
Emp_no fname dept design branch_no
1 amit computer programmer 1
2 balram computer programmer 1
3 verma computer programmer 24 verma computer programmer 3
7/31/2019 SQL Server Notes
34/75
5 krisna bialogy teacher 4
6 babloo math reader 5
Table branch_master
create table branch_master(name varchar(10),
branch_no int not null)
insert into branch_master values('patna',1)
insert into branch_master values('delhi',2)
insert into branch_master values('gaya',3)insert into branch_master values('england',10)
select * from branch_master
name branch_no
patna 1
delhi 2gaya 3
england 10
Left join
select e.fname,e.dept,b.name from branch_master b,emp_master e
where e.branch_no*=b.branch_no
Note:-In this syntax we will see all rows of emp_master because in where clouse
emp_master field is left side.
or
select e.fname,e.dept,b.name from emp_master e left outer join branch_master b on
7/31/2019 SQL Server Notes
35/75
b.branch_no=e.branch_no
Note:-In this syntax we will see all rows of emp_master because with from clouseemp_master field is left side.
fname dept nameamit computer patna
balram computer patna
verma computer delhisanjay computer gaya
krishna biology NULL
babloo math NULL
Right joinselect e.fname,e.dept,b.name from branch_master b,emp_master e
where e.branch_no=*b.branch_no
Note:-In this syntax we will see all rows of branch_master because in where clouse
branch_master field is right side.
or
select e.fname,e.dept,b.name from emp_master e right outer join branch_master b on
e.branch_no=b.branch_no
Note:-In this syntax we will see all rows of emp_master because with from clouse
emp_master field is left side.
fname dept name
amit computer patna
balram computer patna
verma computer delhisanjay computer gaya
NULL NULL england
Full join
7/31/2019 SQL Server Notes
36/75
select e.fname,e.dept,b.name from branch_master b,emp_master e
where e.branch_no*=b.branch_no
union
select e.fname,e.dept,b.name from branch_master b,emp_master ewhere e.branch_no=*b.branch_no
/
OR
select e.fname,e.dept,b.name from emp_master e full join branch_master b on
e.branch_no=b.branch_no
fname dept name
amit computer patnababloo math NULL
balram computer patnakrishna biology NULL
sanjay computer gaya
verma computer delhiNULL NULL england
Cross join
Table--student;
create table student(
roll int not null,
name varchar(20))
insert into student values(1,'amit')insert into student values(2,'verma')
select * from student
roll name 1 amit
7/31/2019 SQL Server Notes
37/75
2 verma
Table-class
create table class(
roll int,c_name varchar(20))
insert into class values(1,'nursery')insert into class values(2,'ukg')
select * from class
roll c_name
1 nursery
2 ukg
select s.roll , s.name,c.c_name,c.roll from student s, class c order by s.roll
or
select s.roll , s.name,c.c_name,c.roll from student s cross join class c order
by s.roll
roll name c_name roll1 amit nursery 1
1 amit ukg 2
2 verma nursery 1
2 verma ukg 2
Cross join:- out put of two table is cartesin product;
7/31/2019 SQL Server Notes
38/75
SELF JOIN
TABLEEMPLOYEE
create table employee(
employee_no varchar(25) not null,
employee_name varchar(25),manager_no varchar(25))
insert into employee values('E01','BASU','E02')
insert into employee values('E02','RUKMANI','E05')
insert into employee values('E03','KAROL','E04')insert into employee(EMPLOYEE_NO,EMPLOYEE_NAME) values('E04','BAROS')
insert into employee(EMPLOYEE_NO,EMPLOYEE_NAME) values('E05','IVAN')
employee_no employee_name manager_no
E01 BASU E02
E02 RUKMANI E05
E03 KAROL E04
E04 BAROS NULLE05 IVAN NULL
SELECT E.EMPLOYEE_NAME,M.EMPLOYEE_NAME "MANAGER"
FROM EMPLOYEE E, EMPLOYEE M WHEREE.MANAGER_NO=M.EMPLOYEE_NO;
EMPLOYEE_NAME MANAGER
-------------------- --------------------
BASU RUKMANI
RUKMANI IVANKAROL BAROS
NOTE:-In some situation it is necessary to join a table ot it self as though two separate
tables this is referred as self join;
7/31/2019 SQL Server Notes
39/75
UNION
Retrive the name of all clients and sales man in the city of Mumbai
from the tables client_master and sales_master.
TABLE CLIENT_MASTER
create table client_master(
c_id varchar(20),
c_name varchar(20),c_city varchar(20))
c_id c_name c_city
C01 ASRAF MUMBAIC02 VISHAL DELHI
C03 AJAY MUMBAI
C04 ROHIT KOLKATA
C05 NALINI MUMBAI
C06 PREM DELHI
TABLE:-SALESMAN_MASTER
create table salesman_master(
s_id varchar(20),
s_name varchar(20),
s_city varchar(20))
S_ID S_NAME S_CITY
S01 MANISH MUMBAIS02 KIRAN DELHI
S03 NITESH MUMBAI
S04 MAHESH KOLKATA
SELECT S_ID ,S_NAME FROM SALESMAN_MASTER WHERE S_CITY ='MUMBAI'
7/31/2019 SQL Server Notes
40/75
UNION
SELECT C_ID,C_NAME FROM CLIENT_MASTER WHERE C_CITY='MUMBAI'
S_ID S_NAMEC01 ASRAFC03 AJAY
C05 NALINIS01 MANISH
S03 NITESH
NOTE:-
1. NO OF COLUMN AND TYPES OF BOTH THE TABLES SHOULD BE SAME;
2. UNION CANT BE USED IN SUB QUERIES;
3. AGREEGATE FUNCTION CANT BE USED WITH UNION CLAUSE
INTERSECTION
Retrive the sales man name in Mumbai whose affords have resulted into at list one
sale transaction.
create table salesman_master(
s_id varchar(20),
s_name varchar(20),
s_city varchar(20))
TABLE-> salesman_master
select * from salesman_master
S_ID S_NAME S_CITY
S01 MANISH MUMBAI
S02 KIRAN DELHI
S03 NITESH MUMBAIS04 MAHESH KOLKATA
create table sale_order(
o_no varchar(10),o_date datetime,
s_id varchar(20))
insert into sale_order values('o01','12-apr-97','s01')
insert into sale_order values('o02','25-apr-97','s03')
7/31/2019 SQL Server Notes
41/75
insert into sale_order values('o03','03-oct-97','s01')
insert into sale_order values('o04','18-june-97','s04')
insert into sale_order values('o05','20-aug-97','s02')
insert into sale_order values('o06','12-jan-97','s02')
TABLE_>sale_order;
O_NO O_DATE S_ID
o01 1997-04-1200:00:00.000 s01
o02 1997-04-2500:00:00.000 s03
o03 1997-10-0300:00:00.000 s01
o04 1997-06-1800:00:00.000 s04
o05 1997-08-2000:00:00.000 s02
o06 1997-01-1200:00:00.000 s02
SELECT DISTINCT s_id,s_nameFROM salesman_master
WHERE EXISTS
(select sm.s_id,sm.s_name from salesman_master sm ,sale_order so where
lower(sm.s_id)=lower(so.s_id))
or
SELECT DISTINCT sm.s_id,sm.s_name
FROM salesman_master sm INNER JOIN sale_order so
ON sm.s_id = so.s_id order by sm.s_id
S_id s_name
SO1 MANISH
SO2 KIRAN
SO3 NITESH
SO4 MAHESH
MINUS
Retrive all the product No of non moving item from the product_master table.
create table sales_order(
o_no varchar(20),
p_no varchar(20))
insert into sales_order values('o01','p01')
7/31/2019 SQL Server Notes
42/75
insert into sales_order values('o01','p04')
insert into sales_order values('o01','p06')
insert into sales_order values('o02','p02')
insert into sales_order values('o02','p05')
insert into sales_order values('o03','p03')insert into sales_order values('o04','p01')
insert into sales_order values('o05','p04')insert into sales_order values('o06','p06')
select * from sales_order
o_no p_no
o01 p01
o01 p04
o01 p06
o02 p05
o02 p02o03 p03
o04 p01
o05 p06
o05 p04
o06 p06
create table product_master(
p_no varchar(20),
description varchar(20))
insert into product_master values('p01','1.44 floppies')
insert into product_master values('p02','monitor')
insert into product_master values('p03','mouse')insert into product_master values('p04','1.22 floppies')
insert into product_master values('p05','key board')
insert into product_master values('p06','cd drive')insert into product_master values('p07','hdd')
insert into product_master values('p08','1.44 drive')
insert into product_master values('p09','1.22 drive')
select * from product_master
p_no description
p01 1.44 floppies
p02 monitor
p03 mouse
7/31/2019 SQL Server Notes
43/75
p04 1.22 floppies
p05 key board
p06 cd drive
p07 hdd
p08 1.44 drivep09 1.22 drive
SELECT DISTINCT p_no
FROM product_master
WHERE not EXISTS
(select * from sales_order where sales_order.p_no=product_master.p_no)
Or
SELECT DISTINCT p_no
FROM product_master
WHERE p_no NOT IN
(SELECT p_noFROM sales_order where sales_order.p_no=product_master.p_no)
P_no
p07
p08
p09
7/31/2019 SQL Server Notes
44/75
BLOCK
The first block:-
begin
declare
end
(1)
begin
declare @roll int
declare @name varchar(20)end
O/P
(2)
begindeclare @roll int
set @roll=100
print @roll
end
declare @roll int
begin
set @roll=100print @roll
end
O/P
100
7/31/2019 SQL Server Notes
45/75
(4)
begin
declare @name varchar(20),@name2 varchar(20)set @name='amit'
set @name2='verma'
print @name
print @name2
print @name + @name2
end
O/P
amit
verma
amitverma
Note:-print is used to output the text or variable;
Note:-+ is used to for concanate
(3)
begin
insert into student values(10,'asd')
print 'successfully entered'
end
O/P
successfully entered
Note:-we can insert values in the table like this
7/31/2019 SQL Server Notes
46/75
if
(4)
begin
declare @a int
set @a=200
if @a=100
begin
print 'a=100'end
print 'a=?'
end
O/P
a=?
if
else
(5)
begin
declare @num1 int
7/31/2019 SQL Server Notes
47/75
declare @num2 int
set @num1 = 100
set @num2 = 200
if @num1 > @num2
print 'num1 greater than num2'else
print 'num2 greater than num1'
print 'successfully executed'
end
O/P
num2 greater than num1
successfully executed
if
else if
else
(6)
begin
declare @num1 int
declare @num2 int
set @num1=100
7/31/2019 SQL Server Notes
48/75
set @num2=200
if @num1>@num2
begin
print 'num1 greater than num2'
endelse if @num1
7/31/2019 SQL Server Notes
49/75
set @j=1
while @j
7/31/2019 SQL Server Notes
50/75
set @i=@i+1
end
end
O/P
1
11
Continue:-
begindeclare @i int
set @i=1
while @i3 and @i< 7begin
set @i=@i+1
continue
endprint @i
set @i=@i+1
end
end
O/P
1
2
37
8
9
10
7/31/2019 SQL Server Notes
51/75
Commit
begin transaction
insert into stud values(17,'raj')
commit transaction
This commits the transaction(insert)
Rollbackbegin transaction
insert into stud values(18,'raj')
rollback transaction
This rollbacks the transaction(insert) last commit.
SAVE POINT
begin transaction t1
insert into stud values(8,'raj')
save transaction t1
insert into stud values(9,'raj')
save transaction t2
insert into stud values(10,'raj')
save transaction t3
rollback transaction t1
7/31/2019 SQL Server Notes
52/75
NOTE:-Save transaction is just lika a book mark in our TSQL,thats
reference we can use to tell sql server to rollback transaction upto.
begin transaction t1
insert into stud values(18,'raj')
save transaction t1
insert into stud values(19,'raj')
save transaction t2
insert into stud values(10,'raj')
save transaction t3
commit transaction
NOTE:- It finally save the transaction in memory.
begin transaction t1
insert into stud values(118,'raj')
save transaction t1
insert into stud values(119,'raj')save transaction t2
insert into stud values(1110,'raj')
save transaction t3
rollback transaction
7/31/2019 SQL Server Notes
53/75
ERROR TRAPPING
select * from sysmessages
Table sysmessages in master message shows all errors numbers with description
(1)
begin transaction MYTRNS
declare @error int
save transaction t1
insert into stud values(6,'raj')select @error=@@error
IF @error 0
begin
print 'ERROR OCCURED'rollback transaction T1
endELSE
BEGIN
print 'INSERTION SUCCESS'
commit transactionEND
(2)
begin transaction MYTRNS
declare @error int
save transaction t1insert into stud values(7,'raj')
select @error=@@error
IF @error = 2627begin
print 'ERROR OCCURED'rollback transaction T1
endIF @error =0
BEGIN
print 'INSERTION SUCCESS'
commit transaction
7/31/2019 SQL Server Notes
54/75
END
Function
SIMPLE FUNCTIO THAT EXCEPTS TWO PARAMETERS AND
RETURN A VALUE
CREATE FUNCTION TEST_FUNC(@A INTEGER,@B INTEGER) RETURNS INTEGER
AS
BEGINRETURN (@A+@B)
END
--------------------------------
BEGINDECLARE @C AS INTEGER
EXECUTE @C=TEST_FUNC 1,2
PRINT @C
END
Function WITHOUT PARAMETER AND REATURN A VALUE
ALTER FUNCTION TEST_FUNC() RETURNS INTAS
BEGIN
RETURN 100
END
BEGIN
DECLARE @C AS INTEGER
EXECUTE @C=TEST_FUNC
PRINT @C
END
7/31/2019 SQL Server Notes
55/75
SIMPLE FUNCTIO THAT EXCEPTS NO PARAMETERS AND
RETURN A TABLE
CREATE FUNCTION TEST_FUNC1() RETURNS TABLE
ASRETURN (SELECT * FROM STUDENT)
BEGIN
SELECT * FROM TEST_FUNC1()END
Overloaded FunctionALTER FUNCTION TEST_FUNC(@A INTEGER=100,@B INTEGER=200) RETURNS INTEGERAS
BEGIN
RETURN (@A+@B)
END--------------------------------
BEGIN
DECLARE @C AS INTEGER
EXECUTE @C=TEST_FUNC
PRINT @C
END
7/31/2019 SQL Server Notes
56/75
STORED PROCEDURE
select * from student
Roll Name
1 amit2 raj
3 ruppu
4 ajnabi
Without parameter
create procedure proc_studas
select * from student
execute proc_stud
Roll Name
1 amit
2 raj3 ruppu
4 ajnabi
With two input parameter And Alter Procedure
alter procedure proc_stud
@rn int,
@nm varchar(25)as
insert into student values(@rn,@nm)
execute proc_stud 5,'basu'
select * from student
Roll Name
1 amit2 raj
7/31/2019 SQL Server Notes
57/75
3 ruppu
4 ajnabi
5 basu
With one input and one output parameter And AlterProcedure
alter proc proc_stud
@rn int,@nm varchar(25) output
as
select @nm=name from student where roll=@rn
DECLARE
@name varchar(30)execute proc_stud
@rn=4,
@nm=@name outputprint @name
output
ajnabi
alter proc proc_stud
@rn int,
@nm varchar(25) output
as
if @rn=1
begin
select @nm=name from student where roll=1
end
else
begin
select @nm=name from student where roll=@rn
end
DECLARE
@name varchar(30)
execute proc_stud
@rn=3,
@nm=@name output
7/31/2019 SQL Server Notes
58/75
print @name
output
ruppu
create proc proc_logincheck
@user_name varchar(25),
@pass_word varchar(25),
@flag int output
as
if exists(select * from tab_login where user_name=@user_name and pass_word=@pass_word)
set @flag=1
else
set @flag=0
DECLARE@abc int
execute proc_logincheck
@user_name='amit',
@pass_word='verma',@flag=@abc output
print @abc
using Return keyword
ALTER proc proc_test_returnas
declare @mymessage varchar(20)
declare @myothermessage varchar(20)
select @mymessage='i am amit'
print @mymessage
return 2
select @myothermessage='i am amit verma'
print @myothermessage
return
declare @return int
exec @return=proc_test_returnprint @return
outputi am amit
2
7/31/2019 SQL Server Notes
59/75
CURSOR WITHIN PROCEDURE
alter proc proc_studas
DECLARE @name varchar(25)declare mycursor cursor
local
scroll
dynamic
optimistic
type_warning
for select name from student
open mycursor
fetch next from mycursor into @name
print @namewhile @@fetch_status=0
begin
fetch next from mycursor into @name
print @nameend
close mycursor
deallocate mycursor
execute proc_stud
output
amit
raj
ruppu
ajnabibasu
basu
7/31/2019 SQL Server Notes
60/75
Trigger
Trigger on insertion
create trigger stud_ins
on stud
for insert
as
declare @name varchar(20)
select @name=name from insertedif @name='verma'
begin
print 'can''t insert the name verma'
rollback
print 'trigger fired'
end
Trigger on deletion
alter trigger del_stud
on stud
for delete
as
declare @roll1 int
declare @name1 varchar(30)select @roll1=roll,@name1=name from deleted
if @name1 ='chintu'
begin
print 'can''t delete '
7/31/2019 SQL Server Notes
61/75
rollback
end
trigger for update
alter trigger del_stud
on stud
for update
as
declare @roll1 int
declare @name1 varchar(30)select @roll1=roll,@name1=name from deleted
insert into delstud values(@roll1,@name1)
if @name1 ='chintu'
begin
print 'can''t be updated '
rollback
end
select @roll1=roll,@name1=name from inserted
if @name1 ='taj mahal'
begin
print 'can''t be inserted '
rollbackend
7/31/2019 SQL Server Notes
62/75
note:-DELETED ,INSERTED are system table and we
have to use these tables in trigger as when we insert any
record first it goes in INSERTED table ,and when wedelete the deleted record goes in DELETED table,and for
update we have to use combination of INSERTED and
DELETED table because in updation two actions takes
place first DELETION then INSERT
DROP TRIGGER
drop trigger stud_ins
7/31/2019 SQL Server Notes
63/75
CursorIn Access or Visual Basic we have worked on record set ,cursor is just like record set but it
is server side.The cursor is set of rows to gather with a pointer that identify a current row.
Steps for cursor:-
1. Declare cursor
2. Open cursor
3. Fetch records
4. Close cursor
5. Deallocate cursor
declare cursorname cursor
[ local | global ][ forword_only | scroll ]
[ Static | Keyset | dynamic | fast_forward ]
[ Read_only | Scroll_Locks | optimistic]
[ Type_warning]
FOR select_statement
[ For update [ of column_names ] ]
Local:-The local keyword limits the use of the cursor to the batch ,stored
procedure,trigger where it was declared.
Global:-The global keyword makes the cursor available to any statement to
the current connection.
Forward_only :- Forward_only specifies that only the next option of the
Fetch(keyword) statement is supported.
Scroll:-Scroll specifies that the option of the Fetch (keyword) should besupported like:- Fetch next | Fetch prior | Fetch First | Fetch Last.If you specify
scroll you can not specify Fast_Forward..
Static:-Static causes the cursor to return a set of rows that reflects(shows) the stateof the data base when the cursor is opened and that is never updated.
(The database will be updated not the cursor)
7/31/2019 SQL Server Notes
64/75
Keyset:-Keyset specifies that the cursor should be updatable,both by theconnection and by other user.However new rows added by other user will not be
reflacted.Dynamic:-Dynamic specifies that cursor should be fully updateble and that it
should reflact new rows. (The database and cursor will be updated)
Fast_forward:-
Read_only:-It specifies Cursor should be read only.
Scroll_Locks:-It specifies that update or deletion made thrugh the cursor
should always succeed.Sql server ensures this by locking the rows as soon as
they are read into the cursor.
Optimistic:-Optimistic uses optimistic locking when you attempt to change
a row through the cursor.
Type_warning:-Type_warning tells sql server to send a warning if the
selected cursor options can not all be ful filled
For select statement:- The select statement argument is a standard T-SQL
select statement that supply the rows for the cursor.This statement can not
use the COMPUTE,COMPUTE BY,FOR BROWSE ,INTO.options
FOR UPDATE:-FOR UPDATE specifies explicitly that the cursor should
allow updating if you use update of with a list of column name only data in
those columns can be updated.
@@cursor_rows
declare mycursor cursor
local
scroll
static
optimistic
type_warning
for select name from student
open mycursor
print @@cursor_rows
close mycursor
7/31/2019 SQL Server Notes
65/75
deallocate mycursor
output
4
@@Cursor_rows :- may return one of the follwing values
A Negative number indicates that the cursor is being populated asynchronously and
shows the number of rows retrive sofar.The value -57, for example ,indicates that the
cursor have 57 rows,but the sql server has not finished populating cursor.
declare mycursor cursor
local
scroll
dynamic
optimistic
type_warningfor select name from student
open mycursor
print @@cursor_rows
close mycursordeallocate mycursor
output
-1
The value -1 is a special case that is always returned for dynamic cursors because other
users can be adding or deleting data,Sql server can not be sure about the number of rowsin a dynamic cursor or whether it is fully populated.
Select * from student
Roll name
1 amit verma
2 raj
3 ruppu
5 ajnabi
@@FETCH_STATUS-returns the status of the last cursor FETCH statement issued
against any cursor currently opened by the connection.
Return value Description
0 FETCH statement was successful.
-1 FETCH statement failed or the row was beyond the result set.
-2 Row fetched is missing
7/31/2019 SQL Server Notes
66/75
forward_only,Fetch ,@@FETCH_STATUS
DECLARE @name varchar(25)
declare mycursor cursorlocal
forward_only
dynamic
optimistic
type_warning
for select name from student
open mycursor
fetch next from mycursor into @name
print @name
while @@fetch_status=0
begin
fetch next from mycursor into @nameprint @name
end
close mycursor
deallocate mycursor
outputamit verma
raj
ruppu
ajnabi
ajnabi
scroll,Fetch, @@FETCH_STATUS
DECLARE @name varchar(25)
declare mycursor cursor
local
scrolldynamic
optimistictype_warning
for select name from student
open mycursor
fetch next from mycursor into @name
print @name
while @@fetch_status=0
begin
fetch next from mycursor into @name
7/31/2019 SQL Server Notes
67/75
print @name
end
close mycursor
deallocate mycursor
output
amit verma
raj
ruppu
ajnabi
ajnabi ->repeate data solved innext example
DECLARE @name varchar(25)declare mycursor cursor
local
scroll
dynamic
optimistic
type_warning
for select name from student
open mycursor
fetch next from mycursor into @name
print @name
while @@fetch_status=0begin
set @name=nULL
fetch next from mycursor into @name
if @name='raj'
beginset @name='abc'
end
print @name
end
close mycursor
deallocate mycursor
output
amit verma
abc
7/31/2019 SQL Server Notes
68/75
ruppu
ajnabi
DECLARE @name varchar(25)declare mycursor cursor
local
scroll
dynamic
optimistic
type_warning
for select name from student
open mycursor
fetch last from mycursor into @name
print @name
while @@fetch_status=0begin
set @name=nULL
fetch prior from mycursor into @name
print @nameend
close mycursor
deallocate mycursor
outputajnabi
ruppu
rajamit verma
static
DECLARE @name varchar(25)
declare mycursor cursorlocal
forward_only
static
optimistic
type_warning
for select name from student
open mycursor
insert into student values(9,'sohan')
7/31/2019 SQL Server Notes
69/75
fetch next from mycursor into @name
print @name
while @@fetch_status=0
begin
set @name=null
fetch next from mycursor into @name
print @nameend
close mycursor
deallocate mycursor
outputamit verma
raj
ruppu
ajnabi
kamal
goldi
krisna
raju
DECLARE @name varchar(25)
declare mycursor cursor
local
forward_only
static
optimistic
type_warning
for select name from student
open mycursor
update student set name='rohan' where roll=4
fetch next from mycursor into @name
print @name
while @@fetch_status=0
begin
set @name=null
fetch next from mycursor into @name
print @name
end
close mycursor
deallocate mycursor
outputamit verma
raj
ruppu
ajnabi
rohan
goldi
krisna
7/31/2019 SQL Server Notes
70/75
raju
dynamic
DECLARE @name varchar(25)
declare mycursor cursor
local
forward_only
dynamic
optimistic
type_warning
for select name from student
open mycursorinsert into student values(6,'goldi')
fetch next from mycursor into @name
print @name
while @@fetch_status=0
begin
set @name=null
fetch next from mycursor into @name
print @name
end
close mycursor
deallocate mycursor
output
amit verma
raj
ruppu
ajnabi
golu
goldi
keyset
DECLARE @name varchar(25)
declare mycursor cursor
local
forward_only
keyset
7/31/2019 SQL Server Notes
71/75
optimistic
type_warning
for select name from student
open mycursor
update student set name='rohan kumar' where roll=4
fetch next from mycursor into @name
print @namewhile @@fetch_status=0
begin
set @name=null
fetch next from mycursor into @name
print @name
end
close mycursor
deallocate mycursor
outputamit verma
raj
ruppu
ajnabi
rohan kumar
goldi
krisna
raju
sohan
7/31/2019 SQL Server Notes
72/75
VIEW
SYNTAX:-
CREATE VIEW VIEWNAME
AS
SELECT-STATEMENT;
Eg:create view view1
as
select * from student;
VIEW ON SINGLE TABLE:-
ADD->allowed
UPDATE-> allowed
DELETE-> allowed
NOTE:-(1) View created on a single table supports all DML(INSERT,UPDATE,DELETE,SELECT)
operations, and will affect the base table as well.
(2) If the user wants to insert with the help of the view then they primary key column and all the
not null column must be included in the view.
(3)Any DML operation on view need base table constraints to be followed
MULTIPLE TABLE WITH RELATION
ADD->allowed in master
ADD->allowed in detailADD->not allowed in both detail and master
Update->can update in master
Update->can update in detail
7/31/2019 SQL Server Notes
73/75
Update-> not allowed in both detail and master
Delete->not allowed
MULTIPLE TABLE WITHOUT RELATION BUT JOIN(without key field)
ADD-> allowed in master
ADD-> allowed in detailADD->not allowed in both detail and master
Update->can update in masterUpdate->can update in detail
Update-> not allowed in both detail and master
Delete->can not delete from view in detail and master.
MULTIPLE TABLE WITHOUT RELATION BUT JOIN(between unique key field)
ADD-> allowed in master
ADD-> allowed in detail
ADD->not allowed in both detail and master
Update->can update in master
Update->can update in detail
Update-> not allowed in both detail and master
Delete->can not delete from view in detail and master.
NOTE:-After this observation we can make a concept that using
view we can do insert,update opration on invidual tables of the view
not on the both at a time.Delete operation is not supported using
view .
To DROP A VIEW
drop view viewname
7/31/2019 SQL Server Notes
74/75
Creating Indexing
create index ind_stud on student (name)
DATEDIFFReturns the number of date and time boundaries crossed between two specified dates.
Syntax
DATEDIFF ( datepart,startdate ,enddate )
Arguments
datepartIs the parameter that specifies on which part of the date to calculate the difference. The
table lists dateparts and abbreviations recognized by Microsoft SQL Server.
Datepart Abbreviations
Year yy, yyyy
quarter qq, q
Month mm, m
dayofyear dy, y
Day dd, d
Week wk, ww
Hour hh
minute mi, n
second ss, s
millisecond ms
7/31/2019 SQL Server Notes
75/75
Eq:-
print datediff(dd,'10/09/2006','10/11/2006')
O/P
2