0% found this document useful (0 votes)
13 views139 pages

BATCH2728

Uploaded by

Vikash Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views139 pages

BATCH2728

Uploaded by

Vikash Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 139

sql server :-

----------------

1 SQL (structured query language)


2 T-SQL (Transact-SQL)

Database :-
---------------

=> a db is a organized collection of interrelated data. For example


a bank db stores data related to cust,accounts,trans etc and
a univ db stores data related to students,courses and faculty etc.

bank db univ db
cust students
accounts courses
trans faculty
loans colleges
employees

Types of Databases :-
-----------------------------

1 OLTP DB (online transaction processing)


2 OLAP DB (online analytical processing)

=> organizations uses OLTP for storing day-to-day transactions


and OLAP for analysis.

=> OLTP is for running business and OLAP is for to analyze business

=> day-to-day operations on db includes

C create
R read
U update
D delete

DBMS :-
-----------

=> DBMS stands for Database Management System


=> DBMS is a software used to create and to manage database.
=> DBMS is an interface between user and db.

user-------------------dbms----------------db

Evolution of DBMS :-
----------------------------

1960 fms (file mgmt system)

1970 hdbms (hierarchical dbms)


ndbms (network dbms)

1980 rdbms (relational dbms)

1990 ordbms (object relational dbms)


RDBMS :-
-------------

=> Relational Database Management System


=> rdbms concepts are introduced by E.F.CODD (Edgar Frank)
=> E.F.CODD introduced 12 rules called codd rules.
=> a db software that supports all 12 rules called perfect rdbms

Information rule :-
----------------------

=> according to information rule data must be organized in tables


i.e. rows and columns

cust
cid name addr => columns / fields / attributes
10 sachin hyd
11 rahul del
12 vijay mum => row / record / tuple

=> every table must contain primary key to uniquely identify records.

ex :- accno,empid,aadharno,panno,voterid

RDBMS features :-
--------------------------

1 easy to access and manipulate data


2 less redundency (duplication of data)
3 more security
4 gurantees data quality
5 supports data sharing
6 supports transactions

emp
empid ename job sal projid name duration cost client
1 A SE 40K 100 ABC 5 600 TATA MOTORS
2 100 ABC 5 600 TATA
MOTORS

10 100 ABC 5 600 TATA MOTORS

projects
projid pname duration cost client
100 ABC 5 600 TATA MOTORS
101 KLM 4 300 KLM airlines

emp
empid ename job sal projid
1 A SE 40K 100
2 B SSE 60K 100

10 100

RDBMS softwares :-
----------------------------

SQL Databases :-
-------------------------
sql server from microsoft
oracle from oracle corp
mysql from oracle corp
postgresql from postgresql forum
rds from amazon

NoSQL Databases :-
---------------------------

1 mongoDB
2 cassandra

ORDBMS :-
---------------

=> object relational dbms


=> it is the combination of rdbms and oops

ordbms = rdbms + oops (reusability)

=> rdbms doesn't support reusability but ordbms supports reusability.


=> ordbms supports reusability by using UDT (user define type).

ordbms softwares :-
--------------------------

sql server
oracle
postgresql

summary :-

what is db ?
what is dbms ?
what is rdbms ?
what is ordbms ?

===================================================================

SQL SERVER
===========

=> sql server is basically a rdbms product from microsoft and also supports
ordbms features and used to create and to manage database.

versions of sql server :-


-------------------------------

version year

SQL SERVER 1.1 1991


SQL SERVER 4.2 1993
SQL SERVER 6.0 1995
SQL SERVER 6.5 1996
SQL SERVER 7.0 1998
SQL SERVER 2000 2000
SQL SERVER 2005 2005
SQL SERVER 2008 2008
SQL SERVER 2012 2012
SQL SERVER 2014 2014
SQL SERVER 2016 2016
SQL SERVER 2017 2017
SQL SERVER 2019 2019
SQL SERVER 2022 2022

CLIENT / SERVER Architecture :-


--------------------------------------------

1 server
2 client

server :-
-----------

=> server is a system where sql server is installed and running


=> inside the server sql server manages

1 DB
2 INSTANCE

=> DB is created in hard disk and acts as permanent storage


=> INSTANCE is created in ram and acts as temporary storage

client :-
----------

=> client is also a system from where users

1 connects to server
2 submit requests to server
3 receive response from server

client tool :-
----------------

SSMS (sql server mgmt studio)

user--------ssms-------------------------------sql server ------------db

user------sqlplus---------------------------------oracle------------------db

user------mysqlworkbench--------------------mysql-----------------db

20-NOV-24

SQL :-
----------

=> SQL stands for structured query language


=> It is a language used to communicate with sql server
=> user communicates with sql server by sending commands called queries.
=> a query is a command / instruction / question send to sql server to perform
operation over db.
=> sql is introduced by IBM and initial name of this language was " sequel " and
later it is
renamed to sql.
=> SQL is common to all relational database softwares

user-----------------------ssms-------------sql--------------------sql
server-------------db

user----------------------sqlplus--------------sql---------------------
oracle-----------------db

user------------------mysqlworkbench--------sql-----------------
mysql-------------------db

=> based on operations SQL is categorized into following 5 sublanguages.

DDL (DATA DEFINITION LANG)


DML (DATA MANIPULATION LANG)
DQL (DATA QUERY LANG)
TCL (TRANSACTION CONTROL LANG)
DCL (DATA CONTROL LANG)

SQL

DDL DML DQL TCL DCL

create insert select commit grant


alter update rollback revoke
drop delete save transaction
truncate merge

Data & Data Definition :-


---------------------------------

empid ename sal => data definition / metadata


1 A 5000 => data

How to connect to sql server :-


------------------------------------------

=> open ssms and enter following details

server type :- DB Engine


server name :- DESKTOP-G2DM7GI
authentication :- windows / sql server
login :- SA (system admin)
password :- 123

=> click connect

SERVER
DATABASE
TABLE
DATA

Creating Database :-
-----------------------------

=> In object explorer select Databases => New Database


Enter Database Name :- BATCH2728

=> click ok

command to create new database :-


--------------------------------------------------

Databases
system databases
master => New Query

=> enter the following command in query window

CREATE DATABASE NARESHIT

=> the following databases are created with installation of sql server are called
system databases

1 MASTER
2 MODEL
3 MSDB
4 TEMPDB

Download & install :-


----------------------------

download :-
----------------

sql server :- https://www.microsoft.com/en-in/sql-server/sql-server-downloads


ssms :- https://learn.microsoft.com/en-us/sql/ssms/download-sql-server-
management-studio-ssms?view=sql-server-ver16

step by step installation :-


------------------------------------

sql server :- https://www.mssqltips.com/sqlservertip/7313/install-sql-server-


2022/

21-nov-24

Datatypes in sql server :-


------------------------------------

=> a datatype specifies

1 what type of data allowed in a column


2 how much memory allocated for column

Datatypes

char integer float currency


date binary

Character types :-
------------------------
ASCII UNICODE

char nchar
varchar nvarchar
varchar(max) nvarchar(max)

char(size) :-
-----------------

=> allows character data upto 8000 chars

ex :- NAME CHAR(10)

SACHIN - - - -
wasted

RAVI- - - - - -
wasted

=> in char datatype extra bytes are wasted , so char is not recommended for
variable length fields and char is recommended for fixed length fields.

ex :- gender char(1)

m
f

state_code char(2)

AP
TG

country_code char(3)

ind
usa

varchar(size) :-
---------------------

=> varchar also allows character data upto 8000


=> it is recommended for variables length fields

ex :- NAME VARCHAR(10)

SACHIN - - - -
released

=> char /varchar allows ascii chars (256 chars) that includes a-z,A-Z,0-9,special
chars
i.e. char / varchar allows alphanumeric data.

ex :- panno char(10)
vehno char(10)
emailid varchar(20)

varchar(max) :-
----------------------
=> allows character data upto 2GB.

ex :- TEXT VARCHAR(MAX)

nchar/nvarchar/nvarchar(max) :- ( n => national)


---------------------------------------------

=> allows unicode chars (65536) that includes all ascii chars and chars of
different
languages.

Integer types :-
---------------------

=> allows integers i.e. numbers without decimal part.

TYPE MEMORY RANGE

TINYINT 1 0 TO 255
SMALLINT 2 -32768 TO 32767
INT 4 -2^31 TO 2^31-1
BIGINT 8 -2^63 TO 2^63-1

ex :- AGE TINYINT
EMPID SMALLINT

NUMERIC(p) :-
--------------------

=> allows numbers without decimal upto 38 digits

ex :- empid NUMERIC(4)

10
100
1000
10000 => not allowed

aadharno NUMERIC(12)

phone NUMERIC(10)

accno NUMERIC(11)

NUMERIC(P,S) / DECIMAL(P,S) :-
-----------------------------------------------

=> both allows numbers with decimal i.e. float

p => precision => total no of digits allowed


s => scale => no of digits allowed after decimal

ex :- SALARY NUMERIC(7,2)

5000
5000.55
50000.55
500000.55 => not allowed
5000.5678 => allowed => 5000.57
5000.5648 => allowed => 5000.56

SAVG NUMERIC(5,2)

Currency Types :-
------------------------

=> used for fields related to money

TYPES MEMORY RANGE

SMALLMONEY 4 -2,14,748.3648 to 2,14,748.3647


MONEY 8 -922337203685477.5808
to

922337203685477.5807

ex :- sal SMALLMONEY
bal MONEY

DATE & TIME :-


---------------------

DATE => allows only dates


TIME => allows only time
DATETIME => allows date & time

=> default date format in sql server is YYYY-MM-DD


=> default time format is HH:MI:SS

ex :- DOB DATE

2003-10-5

LOGIN TIME

9:30:00

TXNDT DATETIME

2024-11-21 10:00:00

22-nov-24

Creating tables in sql server db :-


---------------------------------------------

CREATE TABLE <tabname>


(
colname datatype(size) ,
colname datatype(size),
--------------------
)

Rules :-
-------------

1 name should start with alphabet


2 name should not contain spaces & special chars but allows _ # $
3 name can be upto 128 chars
4 table can have max 1024 cols
5 no of rows unlimited

ex :- 123emp invalid
emp 123 invalid
emp*123 invalid
emp_123 valid

ex :-

=> create table with following structure ?

EMP
EMPID ENAME JOB SAL HIREDATE DNO

CREATE TABLE emp


(
empid TINYINT,
ename VARCHAR(10),
job VARCHAR(10),
sal SMALLMONEY,
hiredate DATE,
dno TINYINT
)

=> above command created table structure/definition/metadata that includes


columns,
datatype and size.

SP_HELP :- ( SP => stored procedure)


------------------

=> command to see the structure of the table

SP_HELP <tabname>

Ex :-

SP_HELP emp

empid tinyint 1
ename varchar 10
job varchar 10
sal smallmoney 4
hiredate date 3
dno tinyint 1

inserting data into table :-


-----------------------------------

=> "insert" command is used to insert data into table.


=> "insert" command creates row
=> we can insert

1 single row
2 multiple rows
inserting single row :-
-----------------------------

INSERT INTO <tabname> VALUES(v1,v2,v3,------)

ex :-

INSERT INTO emp VALUES(100,'sachin','clerk',3000,'2024-11-22',20)


INSERT INTO emp VALUES(101,'arvind','manager',8000,getdate(),10)

inserting multiple rows :-


-----------------------------------

INSERT INTO emp


VALUES(102,'kumar','analyst',9000,'2020-05-10',30) ,
(103,'rahul','clerk',6000,'2018-10-5',30)

inserting nulls :-
----------------------

=> null means blank or empty


=> it is not equal to 0 or space
=> nulls can be inserted in two ways

method 1 :-
-----------------

INSERT INTO emp VALUES(104,'vijay',NULL,NULL,'2019-04-20',20)

method 2 :-
-----------------

INSERT INTO emp(empid,ename,hiredate,dno) VALUES(105,'ajay','2021-08-12',10)

remaining two fields job,sal are filled with nulls.

Operators in sql server :-


----------------------------------

1 Arithmetic operators => + - * / %

2 Relational operators => > >= < <= = <> !=

3 Logical Operators => AND OR NOT

4 Special Operators => BETWEEN


IN
LIKE
IS
ANY
ALL
EXISTS
PIVOT

5 Set Operators => UNION


UNION ALL
INTERSECT
EXCEPT
Displaying Data :-
------------------------

=> "SELECT" command is used to display data


=> we can display all rows and all columns
=> we can display specific rows and specific columns

SELECT columns / *
FROM <tabname>
[WHERE cond]

SQL = ENGLISH
QUERIES = SENTNECES
CLAUSES = WORDS

=> display employee names and salaries ?

SELECT ename,sal FROM emp

=> display names,jobs and hiredates ?

SELECT ename,job,hiredate FROM emp

=> display all the data from emp table ?

SELECT * FROM emp

* => all columns

23-nov-24

WHERE clause :-
-------------------------

=> where clause is used to get specific row/rows from table based on a condition

WHERE COLNAME OP VALUE

=> OP must be any relational operator like > >= < <= = <>
=> where cond is applied on each and every row
=> if cond = true row is selected otherwise row is not selected

Ex :-

=> display employee details whose id = 103 ?

SELECT *
FROM emp
WHERE empid = 103

=> employee details whose name = vijay ?

SELECT *
FROM emp
WHERE ename = 'vijay'

=> employee details earning more than 5000 ?


SELECT *
FROM emp
WHERE sal > 5000

=> employee details joined after 2020 ?

SELECT *
FROM emp
WHERE hiredate > 2020 => ERROR

SELECT *
FROM emp
WHERE hiredate > '2020-12-31'

=> employees joined before 2020 ?

SELECT *
FROM emp
WHERE hiredate < '2020-01-01'

compound condition :-
------------------------------

=> multiple conditions combined with AND / OR operators is called compound


condition

WHERE cond1 AND cond2 result


T T T
T F F
F T F
F F F

WHERE cond1 OR cond2 result


T T T
T F T
F T T
F F F

=> employees whose id = 103,105 ?

SELECT *
FROM emp
WHERE empid = 103 OR empid = 105

=> employees working as clerk and manager ?

SELECT *
FROM emp
WHERE job='clerk' OR job='manager'

=> employees working as clerk and earning more than 5000 ?

SELECT *
FROM emp
WHERE job='clerk' AND sal>5000

=> employees earning more than 5000 and less than 10000 ?

SELECT *
FROM emp
WHERE sal > 5000 AND sal < 10000

=> employees joined in 2020 ?

SELECT *
FROM emp
WHERE hiredate >= '2020-01-01' AND hiredate <= '2020-12-31'

=> employees working as clerk,manager and earning more than 5000 ?

SELECT *
FROM emp
WHERE job='clerk' OR job='manager' AND sal > 5000
-------------
----------------------------------------------

above query returns clerk records earning less than 5000 because operator
AND has got more priority than operator OR , so sal>5000 is applied only
to managers but not to clerks. To overcome this problem use ( )

SELECT *
FROM emp
WHERE ( job='clerk' OR job='manager' ) AND sal > 5000

=>

STUDENT
SID SNAME S1 S2 S3
1 A 80 90 70
2 B 30 60 50

create table student


(
sid int,
sname varchar(10),
s1 tinyint,
s2 tinyint,
s3 tinyint)

insert into student values(1,'A',80,90,70),(2,'B',30,60,50)

=> list of students who are passed ?

SELECT *
FROM student
WHERE s1>=35 AND s2>=35 AND s3>=35

=> list of students who are failed ?

SELECT *
FROM student
WHERE s1<35 OR s2<35 OR s3<35

IN operator :-
------------------

=> use IN operator for list comparision


=> use IN operator for "=" comparision with multiple values
WHERE COLNAME = V1,V2,V3,--- invalid

WHERE COLNAME IN (V1,V2,V3,--) valid

=> employees whose id = 100,103,105 ?

SELECT * FROM emp WHERE empid IN (100,103,105)

=> employees working as clerk,manager,analyst ?

SELECT * FROM emp WHERE job IN ('clerk','manager','analyst')

=> employees who are not working for dept 10,20 ?

SELECT * FROM emp WHERE dno NOT IN (10,20)

25-nov-24

BETWEEN operator :-
------------------------------

=> use BETWEEN opreator for range comparision

WHERE COLNAME BETWEEN V1 AND V2 ( col >= v1 AND col <= v2)

ex :-

=> employees earning between 5000 and 10000 ?

SELECT *
FROM emp
WHERE sal BETWEEN 5000 AND 10000

=> employees not joined in 2020 ?

SELECT *
FROM emp
WHERE hiredate NOT BETWEEN '2020-01-01' AND '2020-12-31'

=> employees working as clerk,manager and earning between 5000 and 10000
and working for dept 10,20 and not joined in 2020 ?

SELECT *
FROM emp
WHERE job IN ('clerk','manager')
AND
sal BETWEEN 5000 AND 10000
AND
dno IN (10,20)
AND
hiredate NOT BETWEEN '2020-01-01' AND '2020-12-31'

=> list of samsung,redmi,realme mobile phones price between 10000 and 20000 ?

products
prodid pname price category brand

SELECT *
FROM products
WHERE brand IN ('samsung','redmi','realme')
AND
price BETWEEN 10000 AND 20000
AND
category='mobiles'

COL = V1
OR
COL = V2 =========================> COL IN (V1,V2,V3)
OR
COL = V3

COL >= V1
AND ===========================> COL BETWEEN V1 AND V2
COL <= V2

LIKE operator :-
----------------------

=> use LIKE operator for pattern comparision

WHERE COLNAME LIKE 'pattern'

=> pattern contains alphabets,digits and wildcard chars

wildcard chars :-
----------------------

% => 0 or many chars

_ => exactly 1 char

=> employees name starts with 's' ?

SELECT *
FROM emp
WHERE ename LIKE 's%'

=> name ends with 'd' ?

WHERE ename LIKE '%d'

=> name contains 'n' ?

SELECT *
FROM emp
WHERE ename LIKE '%n%'

=> where 'a' is 4th char in their name ?

SELECT *
FROM emp
WHERE ename LIKE '___a%'

=> where 'a' is the 4th char from last ?

SELECT *
FROM emp
WHERE ename LIKE '%a___'

=> name starts with vowels ?

SELECT *
FROM emp
WHERE ename LIKE 'a%'
OR
ename LIKE 'e%'

SELECT *
FROM emp
WHERE ename LIKE '[aeiou]%'

=> name starts with consonants ?

SELECT *
FROM emp
WHERE ename NOT LIKE '[aeiou]%'

=> first char between 'a' and 'p' ?

SELECT *
FROM emp
WHERE ename LIKE '[a-p]%'

=> employees joined in oct month ? yyyy-mm-dd

SELECT *
FROM emp
WHERE hiredate LIKE '_____10___'

=> employees joined in 2020 ?

SELECT *
FROM emp
WHERE hiredate LIKE '2020%'

=>

SELECT *
FROM emp
WHERE job IN ('clerk','man%')

A ERROR
B returns clerk & manager
C only clerk
D none

ans :- C

WHERE job='clerk' OR job LIKE 'man%'

ans :- B

IS operator :-
-------------------

=> use IS operator for NULL comparision


WHERE COLNAME IS NULL
WHERE COLNAME IS NOT NULL

=> employees who are not earning salary ?

SELECT *
FROM emp
WHERE sal IS NULL

=> employees earning salary ?

SELECT *
FROM emp
WHERE sal IS NOT NULL

summary :-

WHERE COLNAME IN (V1,V2,V3,---)


WHERE COLNAME BETWEEN V1 AND V2
WHERE COLNAME LIKE 'PATTERN'
WHERE COLNAME IS NULL

ALIAS :-
-----------

=> alias means another name or alternative name


=> aliases are used to change column headings

colname / expr [AS] alias

Ex :-

=> display ENAME ANNUAL SAL ?

SELECT ename,sal*12 AS ANNSAL


FROM emp

SELECT ename,sal*12 AS [annual sal]


FROM emp

=> display ENAME SAL HRA DA TAX TOTSAL ?

HRA = 20% on sal


DA = 30% on sal
TAX = 10% on sal
TOTSAL = SAL + HRA + DA - TAX

SELECT ENAME,SAL,
SAL*0.2 AS HRA,
SAL*0.3 AS DA,
SAL*0.1 AS TAX,
SAL+(SAL*0.2) + (SAL*0.3) - (SAL*0.1) AS TOTSAL
FROM EMP

=> display SNO TOTAL AVG ?

STUDENT
SNO SNAME S1 S2 S3
1 A 80 90 70
2 B 30 60 50

SELECT SNO,
S1+S2+S3 AS TOTAL,
(S1+S2+S3)/3.0 AS AVG
FROM STUDENT

1 240 80
2 140 46.

26-nov-24

ORDER BY clause :-
----------------------------

=> order by clause is used to sort table data.


=> using order by we can sort either in ascending or in descending order
=> default order is ascending

SELECT columns
FROM tabname
[WHERE cond]
ORDER BY colname ASC / DESC , ------

=> arrange employee list name wise ascending order ?

SELECT *
FROM emp
ORDER BY ename ASC

=> arrange list sal wise desc ?

SELECT *
FROM emp
ORDER BY sal DESC

NOTE :-

=> in order by clause we can use column name or column number


=> order by number is not based on table it is based on select list

ex :-

SELECT empno,ename,hiredate,sal
FROM emp
ORDER BY 4 DESC

=> above query sorts data based on 4th column in the select list i.e. sal

=> arrange employee list dept wise asc and with in dept sal wise desc ?

SELECT empno,ename,sal,deptno
FROM emp
ORDER BY 4 ASC , 3 DESC

1 A 3000 20 6 F 7000 10
2 B 1000 30 3 C 4000 10
3 C 4000 10 ===========> 4 D 6000 20
4 D 6000 20 1 A 3000 20
5 E 5000 30 5 E 5000 30
6 F 7000 10 2 B 1000 30

=> display in each dept employee list based on hiredate ?

SELECT empno,ename,hiredate,deptno
FROM emp
ORDER BY 4 ASC , 3 ASC

=> arrange student list avg wise desc , m desc,p desc ?

STUDENT
SNO SNAME M P C
1 A 80 90 70
2 B 60 70 50
3 C 90 70 80
4 D 90 80 70

SELECT sno,sname,m,p,c,(m+p+c)/3
FROM student
ORDER BY (m+p+c)/3 DESC ,m DESC, p DESC

4 D 90 80 70 80
3 C 90 70 80 80
1 A 80 90 70 80
2 B 60 70 50 60

=> employees working as clerk,manager and arrange output sal wise desc ?

SELECT *
FROM emp
WHERE job IN ('clerk','manager')
ORDER BY sal DESC

DISTINCT clause :-
---------------------------

=> distinct eliminates duplicates in select stmt output

SELECT DISTINCT col


SELECT DISTINCT col1,col2
SELECT DISTINCT *

Ex :-

SELECT DISTINCT deptno FROM emp

10
20
30

SELECT DISTINCT job FROM emp

ANALYST
CLERK
MANAGER
PRESIDENT
SALESMAN

TOP clause :-
--------------------

=> used to display top n rows from table

SELECT TOP <n> columns/*


FROM tabname
[WHERE cond]
[ORDER BY ]

Ex :-

=> display first 5 rows from emp table ?

SELECT TOP 5 * FROM emp

=> display top 5 highest paid employees ?

SELECT TOP 5 *
FROM emp
ORDER BY sal DESC

=> display top 5 max salaries ?

SELECT DISTINCT TOP 5 sal


FROM emp
ORDER BY sal DESC

=> display top 5 employees based on experience ?

SELECT TOP 5 *
FROM emp
ORDER BY hiredate ASC

summary :-

WHERE => to select specific rows


ORDER BY => to sort table data
DISTINCT => to eliminate duplicates
TOP => to select top n row

27-nov-24

DML commands :- (Data Manipulation Lang)


-------------------------

INSERT
UPDATE
DELETE
MERGE

=> dml commands acts on table data


=> all dml commands are auto committed (saved)
=> to stop auto commit execute the following command

SET IMPLICIT_TRANSACTIONS ON
=> to save the operation execute COMMIT
=> to cancel the operation execute ROLLBACK

UPDATE command :-
-----------------------------

=> command used to modify the table data.


=> we can update all rows or specific rows
=> we can update single column or multiple columns

UPDATE <tabname>
SET colname = value , colname = value , ------
[WHERE cond]

ex :-

=> update all employees comm with 500 ?

UPDATE emp SET comm = 500

=> update employees comm with 500 whose comm = null ?

UPDATE emp SET comm = 500 WHERE comm IS NULL

=> update comm with null whose comm <> null ?

UPDATE emp SET comm = NULL WHERE comm IS NOT NULL

NULL assignment =
NULL comparision IS

=> update sal with 1000 and comm with 500 whose empno = 7369 ?

UPDATE emp
SET sal = 1000 , comm = 500
WHERE empno = 7369

=> increment sal by 20% and comm by 10% those working as salesman and joined in
1981 year ?

UPDATE emp
SET sal = sal + (sal*0.2) , comm = comm + (comm*0.1)
WHERE job='SALESMAN' AND hiredate LIKE '1981%'

=> increment all samsung , realme mobile phones price by 10% ?

products
prodid name price category brand

UPDATE products
SET price = price + (price*0.1)
WHERE category='mobiles'
AND
brand IN ('samsung','relame')

DELETE command :-
-----------------------------
=> command used to delete row/rows from table
=> we can delete all rows or specific rows

DELETE FROM <tabname> [WHERE cond]

ex :-

=> delete all rows from emp ?

DELETE FROM emp

=> delete employees whose id = 7369,7499 ?

DELETE FROM emp WHERE empno IN (7369,7499)

DDL commands :- (Data Definition Lang)


-------------------------

CREATE
ALTER
DROP
TRUNCATE

=> all DDL commands acts on table structure (columns,datatype and size)

ALTER command :-
---------------------------

=> command used to modify table structure


=> using alter command we can

1 add columns
2 drop columns
3 modify column
changing datatype
changing size

Adding column :-
------------------------

ALTER TABLE <tabname>


ADD colname datatype(size) , colname datatype(size), ---------

Ex :-

=> add column gender to emp table ?

ALTER TABLE emp


ADD gender char(1)

after adding by default the new column is filled with nulls , to insert data
into the
new column use update command.

UPDATE emp SET gender = 'M' WHERE empno = 7369

Droping columns :-
-------------------------
ALTER TABLE <tabname>
DROP COLUMN col1,col2,---------

Ex :-

=> drop column gender from emp ?

ALTER TABLE emp


DROP COLUMN gender

Modifying column :-
---------------------------

ALTER TABLE <tabname>


ALTER COLUMN colname datatype(size)

1 changing datatype
2 changing size

=> modify the empno datatype to int ?

ALTER TABLE emp


ALTER COLUMN empno INT

=> increase size of ename to 20 ?

ALTER TABLE emp


ALTER COLUMN ename VARCHAR(20)

ALTER TABLE emp


ALTER COLUMN ename VARCHAR(5) => ERROR => some names contains
more than 5 chars

DROP command :-
--------------------------

=> command used to drop table from db


=> drops table structure along with data

DROP TABLE <tabname>

Ex :-

DROP TABLE emp

TRUNCATE command :-
----------------------------------

=> deletes all rows from table but keeps structure


=> will empty the table
=> releases memory allocated for table

TRUNCATE TABLE <tabname>

=> when truncate command is executed sql server goer to memory and releases
all the pages allocate for table and when pages are released data stored in
pages are also deleted.
Ex :-

TRUNCATE TABLE emp

DELETE VS TRUNCATE :-
--------------------------------------

DELETE TRUNCATE

1 DML DDL

2 delete can delete can delete only all rows


all rows and specific but cannot delete specific
row
rows

3 where cond can be where cond can't be


used with delete used with truncate

4 deletes row-by-row deletes all rows at a time

5 slower faster

6 will not release memory releases memory

7 will not reset identity will reset identity

IDENTITY :-
----------------

=> used to generate sequence numbers


=> used to auto increment column values

IDENTITY(SEED,INCR)

Ex :-

SEED => start


default 1

INCR => increment


default 1

CREATE TABLE cust


(
cid int IDENTITY(100,1) ,
cname varchar(10)
)

INSERT INTO cust(cname) VALUES('A')


INSERT INTO cust(cname) VALUES('B')
INSERT INTO cust(cname) VALUES('C')

SELECT * FROM CUST

100 A
101 B
102 C
DELETE FROM cust TRUNCATE TABLE cust

INSERT INTO cust(cname) VALUES('K') INSERT INTO cust(cname) VALUES('P')

103 K 100 P

SP_RENAME :- ( SP => stored procedure)


---------------------

=> a stored procedure used to change tablename and also column name

SP_RENAME 'old name ' , ' new name'

Ex :-

=> rename table emp to employees ?

SP_RENAME 'emp','employees'

=> rename column comm to bonus in emp table ?

SP_RENAME 'employees.comm','bonus'

==========================================================================

Built-in Functions :-
----------------------------

=> a function accepts some input performs some calculation and returns one value

Types of functions :-
----------------------------

1 date
2 character
3 numeric
4 conversion
5 special
6 analytical
7 aggregate

DATE functions :-
-----------------------

GETDATE() :-
-----------------

=> returns current date,time and also milliseconds

SELECT GETDATE() => 2024-11-28 11:52:21.933


-------------- ----------- -----
DATE
TIME MS

DATEPART() :-
----------------------

=> used to get part of the date


DATEPART(INTERVAL,DATE)

Ex :-

SELECT DATEPART(YY,GETDATE()) => 2024


SELECT DATEPART(MM,GETDATE()) => 11
SELECT DATEPART(DD,GETDATE()) => 28
SELECT DATEPART(DY,GETDATE()) => 333 (day of the year)
SELECT DATEPART(DW,GETDATE()) => 5 (day of the week)
SELECT DATEPART(HH,GETDATE()) => 12
SELECT DATEPART(MI,GETDATE()) => 03
SELECT DATEPART(SS,GETDATE()) => 20
SELECT DATEPART(QQ,GETDATE()) => 4 (quarter)

=> display ENAME YEAR_OF_JOIN ?

SELECT ENAME,DATEPART(YY,HIREDATE) AS YEAR FROM EMP

=> display employee details joined in 1980,1983,1985 ?

SELECT *
FROM emp
WHERE DATEPART(YY,HIREDATE) IN (1980,1983,1985)

=> display employee details joined in leap year ?

SELECT *
FROM emp
WHERE DATEPART(YY,HIREDATE)%4 = 0

=> employee details joined in jan,apr,dec ?

SELECT *
FROM emp
WHERE DATEPART(MM,HIREDATE) IN (1,4,12)

=> employees joined on sunday ?

SELECT *
FROM emp
WHERE DATEPART(DW,HIREDATE) = 1

=> display ENAME DAY ?

SELECT ename,DATEPART(DW,hiredate) AS DAY


FROM emp

DATENAME() :-
----------------------

=> used to get part of the date

MM DW

DATEPART 11 5

DATENAME November Thursday


=> display ENAME DAY ?

SELECT ename,DATENAME(DW,hiredate) AS DAY


FROM emp

FORMAT() :-
-----------------

=> used to display dates in different formats

FORMAT(DATE,'format')

SELECT FORMAT(GETDATE(),'dd-MMMM-yyyy hh:mm:ss dddd')

o/p :- 28-November-2024 12:35:24 Thursday

MM => 11
MMM => Nov
MMMM => November

ddd => Thu


dddd => Thursday

=> display ENAME HIREDATE ? display hiredates in MM/DD/YYYY format ?

SELECT ENAME,FORMAT(HIREDATE,'MM/dd/yyyy') AS HIREDATE


FROM EMP

scenario :-
---------------

1 INSERT INTO emp(empno,ename,sal,hiredate)


VALUES(100,'A',4000,getdate())

2 display list of employees joined today ?

SELECT *
FROM emp
WHERE hiredate = getdate() => no rows

2024-11-29 = 2024-11-29 11:30:20.123

"=" comparision with getdate() always fails , to overcome this problem use
FORMAT function.

SELECT *
FROM emp
WHERE hiredate = FORMAT(getdate() ,'yyyy-MM-dd')

DATEADD() :-
-------------------

=> used to add / subtract days / months / years to a date / from a date

DATEADD(INTERVAL , INT , DATE)


EX :-

SELECT DATEADD(DD,10,GETDATE()) => 2024-12-09


SELECT DATEADD(MM,2,GETDATE()) => 2025-01-29
SELECT DATEADD(YY,1,GETDATE()) => 2025-11-29
SELECT DATEADD(MM,-2,GETDATE()) => 2024-09-29

scenario :-

GOLD_RATES
DATEID RATE
2020-01-01 ?
2020-01-02 ?

2024-11-29 ?

1 display today's gold rate ?


2 display yesterday's gold rate ?
3 dipslay last month same day gold rate ?
4 display last year same day gold rate ?
5 display last 1 month gold rates ?

SELECT *
FROM gold_rates
WHERE dateid = FORMAT(getdate(),'yyyy-MM-dd')

SELECT *
FROM gold_rates
WHERE dateid = FORMAT(DATEADD(dd,-1,getdate()),'yyyy-MM-dd')

SELECT *
FROM gold_rates
WHERE dateid = FORMAT(DATEADD(mm,-1,getdate()),'yyyy-MM-dd')

4
SELECT *
FROM gold_rates
WHERE dateid = FORMAT(DATEADD(yy,-1,getdate()),'yyyy-MM-dd')

5 SELECT *
FROM gold_rates
WHERE
dateid BETWEEN FORMAT(DATEADD(mm,-1,getdate()),'yyyy-MM-dd')
AND
FORMAT(getdate(),'yyyy-MM-dd')

DATEDIFF() :-
---------------------

=> calculates difference between two dates

DATEDIFF(INTERVAL , START DATE, END DATE)


Ex :-

SELECT DATEDIFF(DD,'2023-11-29',GETDATE()) => 366


SELECT DATEDIFF(MM,'2023-11-29',GETDATE()) => 12
SELECT DATEDIFF(YY,'2023-11-29',GETDATE()) => 1

=> display ENAM E EXPERIENCE in years ?

SELECT ENAME,
DATEDIFF(YY,HIREDATE,GETDATE()) AS EXPR
FROM EMP

=> display ENAME EXPERIENCE ?


M YEARS N MONTHS

experience = 40 months = 3 years 4 months

years = months/12 = 40/12 = 3

months = month%12 = 40%12 = 4

SELECT ENAME,
DATEDIFF(MM,HIREDATE,GETDATE())/12 AS YEARS,
DATEDIFF(MM,HIREDATE,GETDATE())%12 AS MONTHS
FROM EMP

EOMONTH() :-
---------------------

=> returns last day of the month

EOMONTH(DATE,INT)

Ex :-

SELECT EOMONTH(GETDATE(),0) => 2024-11-30


SELECT EOMONTH(GETDATE(),1) => 2024-12-31
SELECT EOMONTH(GETDATE(),-1) => 2024-10-31

Queries :-
---------------

1 display current month 1st day ?


2 display next month 1st day ?
3 display current year 1st day ?
4 display next year 1st day ?

character functions :-
-----------------------------

UPPER() :-
----------------

=> converts string to uppercase

UPPER(string)
Ex :-

SELECT UPPER('hello') => HELLO

LOWER() :-
----------------

=> converts string to lowercase

LOWER(string)

Ex :-

SELECT LOWER('HELLO') => hello

=> display EMPNO ENAME SAL ? display names in lowercase ?

SELECT EMPNO,LOWER(ENAME) AS ENAME,SAL FROM EMP

=> convert names to lowercase in table ?

UPDATE emp SET ename = LOWER(ename)

30-nov-24

LEN() :-
----------

=> returns string length i.e. no of chars

LEN(string)

Ex :-

SELECT LEN('HELLO WELCOME') => 13

=> employees name contains 4 chars ?

WHERE ename LIKE '____'

SELECT *
FROM emp
WHERE LEN(ename) = 4

LEFT() :-
----------

=> returns no of chars from left side

LEFT(string,no of chars)

Ex :-

SELECT LEFT('HELLO WELCOME',5) => HELLO

RIGHT() :-
--------------

=> returns no of chars from right side


RIGHT(string,no of chars)
Ex :-

SELECT RIGHT('HELLO WELCOME',7) => WELCOME

=> employees name starts with 'S' ?

SELECT *
FROM emp
WHERE LEFT(ename,1) = 's'

=> employees name ends with 's' ?

SELECT *
FROM emp
WHERE RIGHT(ename,1) = 's'

=> employees name starts and ends with same char ?

SELECT *
FROM emp
WHERE ename LIKE 'a%a'
OR
ename LIKE 'b%b'

SELECT *
FROM emp
WHERE LEFT(ename,1) = RIGHT(ename,1)

=> generate emailids for employees ?

empno ename emailid


7369 smith [email protected]
7499 allen [email protected]

SELECT empno,ename,
LEFT(ename,3) + LEFT(empno,3) + '@tcs.com' as emailid
FROM emp

=> store emailids in db ?

STEP 1 :- add emailid column to emp table

ALTER TABLE emp


ADD emailid VARCHAR(20)

STEP 3 :- update the column with emailids

UPDATE emp
SET emailid = LEFT(ename,3) + LEFT(empno,3) + '@tcs.com'

SUBSTRING() :-
----------------------

=> returns chars starting from specific position

SUBSTRING(string,start,no of chars)
ex :-

SELECT SUBSTRING('HELLO WELCOME',1,5) => HELLO


SELECT SUBSTRING('HELLO WELCOME',10,3) => COM
SELECT SUBSTRING('HELLO WELCOME',7,7) => WELCOME

CHARINDEX() :-
-----------------------

=> returns position of the char in a string

CHARINDEX(char,string,[start])

Ex ;-

SELECT CHARINDEX('O','HELLO WELCOME') => 5


SELECT CHARINDEX('K','HELLO WELCOME') => 0
SELECT CHARINDEX('O','HELLO WELCOME',6) => 11
SELECT CHARINDEX('E','HELLO WELCOME',10) => 13

=> display CID FNAME LNAME ?

CUST
CID CNAME
10 sachin tendulkar
11 virat kohli

SELECT cid,
SUBSTRING(cname,1,CHARINDEX(' ',cname)-1) AS FNAME ,
SUBSTRING(cname,CHARINDEX(' ',cname)+1 , LEN(cname)) AS LNAME
FROM cust

=> display CID FNAME MNAME LNAME ?

CUST
CID CNAME
10 sachin ramesh tendulkar
11 mahendra singh dhoni

REPLICATE() :-
----------------------

=> repeats the given char for given no of times

REPLICATE(char , length)

Ex :-

SELECT REPLICATE('*',5) => *****

=> display ENAME SAL ?


****
SELECT ename,
REPLICATE('*',LEN(sal)*10) as sal
FROM emp

=>

ACCOUNTS
ACCNO BAL
123456789523 10000

your a/c no XXXX9523 debited -----

REPLICATE('X',4) + RIGHT(accno,4)

credit card no :- 1234 5678 9012 3456

12xxx456

LEFT(credit_card_no , 2) + REPLICATE('x',3) + RIGHT(credit_card_no,3)

REPLACE() :-
-------------------

=> used to replace one string with another string

REPLACE(str1,str2,str3)

Ex :-

SELECT REPLACE('hello','ell','abc') => habco


SELECT REPLACE('hello','l','abc') => heabcabco
SELECT REPLACE('hello','ell','') => ho
SELECT REPLACE('hello','elo','abc') => hello

TRANSLATE() :-
-----------------------

=> translates one char to another char

TRANSLATE(str1,str2,str3)

Ex :-

SELECT TRANSLATE('hello','elo','abc') => habbc

e => a
l => b
o => c

=> translate function can be used to encrypt data i.e. converting plain text to
cipher text.

ex :-

SELECT ename,
TRANSLATE(sal,'0123456789.' , '$bT@g*#^&!%') as sal
FROM emp

jones 2975.00 T!^*%$$

=> remove all special chars from '@#he$%ll^&o*!' ?

output :- hello

SELECT
REPLACE(TRANSLATE( '@#he$%ll^&o*!' , '@#$%^&*!','********'),'*','')
----------------------------------------------------------------------
**he**ll**o**

02-dec-24

Numeric Functions :-
----------------------------

rounding numbers :-
-------------------------

ROUND
FLOOR
CEILING

ROUND:-
------------

=> rounds number to integer or to decimal places based on avg

ROUND(number,decimal places)

Ex :-

SELECT ROUND(38.45678,0) => 38

38-----------------------------------
38.5------------------------------------39

number < avg => rounded to lowest


number >= avg => rounded to highest

SELECT ROUND(38.55678,0) => 39

SELECT ROUND(38.45678,2) => 38.46

SELECT ROUND(38.45378,2) => 38.45

SELECT ROUND(38.45678,4) => 38.4568

SELECT ROUND(386,-2) => 400

300 ----------------------------350-------------------------------400

SELECT ROUND(386,-1) => 390

380-----------------------------385---------------------------------390

SELECT ROUND(386,-3) => 0

0---------------------------------500----------------------------------1000

SELECT ROUND(4567,-1) , ROUND(4567,-2) , ROUND(4567,-3)

o/p :- 4570 4600 5000


=> round all the employees salaries to hundreds in table ?

UPDATE EMP SET SAL = ROUND(SAL , -2)

FLOOR() :-
---------------

=> rounds number always to lowest

FLOOR(number)

Ex :-

SELECT FLOOR(3.9) => 3

CEILING() :-
---------------

=> rounds number always to highest

CEILING(number)

Ex :-

SELECT CEILING(3.1) => 4

Conversion functions :-
--------------------------------

CAST
CONVERT

CAST :-
--------------

CAST(source-value as target-type)

Ex :-

SELECT CAST(10.5 AS INT) => 10

=> display smith earns 1000


allen earns 1600 ?

SELECT ename + ' earns ' + CAST(sal AS VARCHAR)


FROM emp

=> display smith joined as clerk on 1980-12-17 ?

SELECT ename + ' joined as ' + job + ' on ' + CAST(hiredate as varchar)
FROM emp

CONVERT() :-
-------------------

CONVERT(TARGET-TYPE , SOURCE-VALUE)

Ex :-
SELECT CONVERT(INT,10.5) => 10

=> difference between CAST & CONVERT ?

1 using convert we can display dates in different styles but not possible
using cast
2 using convert we can display money in different styles but not possible
using cast

Date Styles :-
------------------

=> to display dates in different styles first convert date to char type

CONVERT(VARCHAR,DATE,style-number)

Ex :-

SELECT CONVERT(VARCHAR,GETDATE(),101) => 12/02/2024

104 =>
02.12.2024

110 => 12-02-2024

112 => 20241202

114
=> 12:11:58:420

display ENAME HIREDATE ? display hiredates in MM/DD/YYYY format ?

SELECT ename,
CONVERT(VARCHAR,hiredate,101) as hiredate
FROM emp

Money styles :-
--------------------

CONVERT(VARCHAR,MONEY,STYLE-NUMBER)

0
1 => displays number with thousand seperator
2

=> display ENAME SAL ?

display salaries with thousand seperator ?

SELECT ename,
CONVERT(VARCHAR,sal,1) as sal
FROM emp

Special functions :-
-------------------------

ISNULL() :-
----------------

=> used to convert null values

ISNULL(arg1,arg2)

=> if arg1 = null returns arg2


=> if arg1 <> null returns arg1 only

Ex :-

SELECT ISNULL(100,200) => 100

SELECT ISNULL(NULL,200) => 200

=> display ENAME SAL BONUS TOTSAL ?

TOTSAL = SAL + BONUS

SELECT ename,sal,bonus,sal+bonus as totsal FROM emp

smith 1000.00 500.00 1500.00


allen 1600.00 NULL NULL

SELECT ename,sal,bonus,sal+ISNULL(bonus,0) as totsal FROM emp

smith 1000.00 500.00 1500.00


allen 1600.00 NULL 1600.00

=> display ENAME SAL BONUS ?

if bonus = null display N/A ?

SELECT ename , sal, ISNULL(CAST(bonus AS VARCHAR),'N/A') as bonus


FROM emp

3-dec-24

Analytical Functions / Window Functions :-


-------------------------------------------------------

RANK & DENSE_RANK :-


------------------------------------

=> used to find ranks


=> ranking is based on some column
=> for rank functions data must be sorted

RANK() OVER (ORDER BY colname ASC/DESC)


DENSE_RANK() OVER (ORDER BY colname ASC/DESC)

Ex :-

=> find the ranks of the employees based on sal and highest paid
should get 1st rank ?

SELECT empno,ename,sal,
rank() over (order by sal desc) as rnk
FROM emp
SELECT empno,ename,sal,
dense_rank() over (order by sal desc) as rnk
FROM emp

=> difference between rank & dense_rank ?

1 rank function generates gaps but dense_rank will not generate gap

2 in rank function ranks may not be in sequence but in dense_rank


ranks are always in sequence.

SAL RNK DRNK


5000 1 1
4000 2 2
3000 3 3
3000 3 3
3000 3 3
2000 6 4
2000 6 4
1000 8 5

PARTITION BY clause :-
--------------------------------

=> used to find ranks with in group , for ex to find ranks with in dept
first divide the table dept wise using partition by clause and
apply rank/dense_rank functions on each partition (dept) .

SELECT empno,ename,sal,deptno,
dense_rank() over (partition by deptno order by sal desc) as
rnk
FROM emp

LAG & LEAD :-


---------------------

LAG(colname,INT) OVER (ORDER BY --) => returns previous value


LEAD(colname,INT) OVER (ORDER BY --) => returns next value

ex :-

SELECT empno,ename,sal,
LAG(sal,1) OVER (order by empno asc) as prev_sal
FROM emp

7369 smith 1000.00 NULL


7499 allen 1600.00 1000.00
7521 ward 1300.00 1600.00

=> display ENAME HIREDATE DAYS ?

SELECT ename,hiredate,
DATEDIFF(dd,lag(hiredate,1) over (order by hiredate asc),hiredate) as days
FROM emp

=> display year population growth_rate ?

population :-
-------------------

year population
2000
2001

2023
2024

Aggregate functions :-
-----------------------------

=> these functions process multiple rows and returns one value

MAX
MIN
SUM
AVG
COUNT
COUNT(*)

MAX() :-
------------

=> returns maximum value

MAX(arg)

Ex :-

SELECT MAX(SAL) FROM EMP => 5000


SELECT MAX(HIREDATE) FROM EMP => 1983-01-12

MIN() :-
-----------

=> returns minimum value

MIN(arg)

Ex :-

SELECT MIN(SAL) FROM EMP => 1000

SUM() :-
------------

=> returns total

SUM(arg)

Ex :-

SELECT SUM(SAL) FROM EMP => 29500

=> round total sal to thousands ?

SELECT ROUND(SUM(SAL) , -3) FROM EMP => 30000


29000-----------------29500----------------------30000

=> after rounding display total sal with thousand seperator ?

SELECT CONVERT(VARCHAR,ROUND(SUM(SAL) , -3) ,1)


FROM EMP

o/p :- 30,000.00

=> calculate total sal including bonus ?

SELECT SUM(SAL+ ISNULL(COMM,0)) FROM EMP

AVG() :-
------------

=> returns average value

AVG(arg)

Ex :-

SELECT AVG(SAL) FROM EMP => 2107.1428

=> round avg sal to highest integer ?

SELECT CEILING(AVG(SAL)) FROM EMP

2107--------------------------------------2108

NOTE :-

=> sum,avg cannot be applied on char,date columns , can be applied only on


numeric columns

COUNT() :-
-----------------

=> returns no of values in a column

COUNT(arg)

Ex :-

SELECT COUNT(EMPNO) FROM EMP => 14

SELECT COUNT(BONUS) FROM EMP => 1 => nulls are not counted

COUNT(*) :-
------------------

=> returns no of rows in a table.

SELECT COUNT(*) FROM EMP => 14

T1
F1
10
NULL
20
NULL
30

COUNT(F1) => 3
COUNT(*) => 5

=> no of employees joined in 1981 year ?

SELECT COUNT(*) FROM EMP WHERE DATEPART(YY,HIREDATE) = 1981

=> no of employees joined on sunday ?

SELECT COUNT(*) FROM EMP WHERE DATENAME(DW,HIREDATE) = 'SUNDAY'

=> no of employees joined in 2nd quarter of 1981 year ?

SELECT COUNT(*)
FROM EMP
WHERE DATEPART(QQ,HIREDATE) = 2
AND
DATEPART(YY,HIREDATE) = 1981

SELECT COL1,COL2 FROM TABNAME

no of values return by col1 = no of values return by col2

SELECT ENAME,COUNT(*) FROM EMP => ERROR


14 1

SELECT MIN(SAL) ,MAX(SAL) FROM EMP => EXECUTED


1 1

SUMMARY :-

DATE :- getdate() , datepart,datename,dateadd,datediff,eomonth


CHAR :-
upper,lower,len,left,right,substring,charindex,replicate,replace,translate
NUMERIC :- round,ceiling,floor
CONVERSION :- cast,convert
SPECIAL :- isnull
ANALYTICAL :- rank,dense_rank,lag,lead
AGGREGATE :- max,min,sum,avg,count,count(*)

===========================================================================

CASE statement :-
-------------------------

=> case statement is used to implement if-then-else


=> using case stmt we can return values based on condition
=> case statements are 2 types

1 simple case
2 searched case

simple case :-
--------------------

=> use simple case when conditions based on "=" operator

CASE colname
WHEN value1 THEN return expr1
WHEN value2 THEN return expr2
----------------
ELSE return expr
END

Ex :-

=> display ENAME DNAME ?

if deptno=10 display HR
20 IT
30 SALES
others UNKNOWN

SELECT ENAME,
CASE DEPTNO
WHEN 10 THEN 'HR'
WHEN 20 THEN 'IT'
WHEN 30 THEN 'SALES'
ELSE 'UNKNOWN'
END AS DNAME
FROM EMP

=> increment salaries as follows ?

if job = CLERK incr sal by 10%


SALESMAN 15%
MANAGER 20%
others 5%

UPDATE EMP
SET SAL = CASE JOB
WHEN 'CLERK' THEN SAL+(SAL*0.1)
WHEN 'SALESMAN' THEN SAL+(SAL*0.15)
WHEN 'MANAGER' THEN SAL+(SAL*0.2)
ELSE SAL + (SAL*0.05)
END

searched case :-
-----------------------

=> use searched case when conditions not based on "=" operator.

CASE
WHEN COND1 THEN RETURN EXPR1
WHEN COND2 THEN RETURN EXPR2
-----------------
ELSE RETURN EXPR
END

Ex :-

=> display ENAME SAL SALRANGE ?


if sal>3000 display HISAL
sal<3000 display LOSAL
else AVGSAL

SELECT ENAME,SAL,
CASE
WHEN SAL>3000 THEN 'HISAL'
WHEN SAL<3000 THEN 'LOSAL'
ELSE 'AVGSAL'
END AS SALRANGE
FROM EMP

=> display SNO TOTAL AVG RESULT ?

STUDENT
SNO SNAME S1 S2 S3
1 A 80 90 70
2 B 30 60 50

SELECT SNO,
(S1+S2+S3) AS TOTAL,
(S1+S2+S3)/3 AS AVG,
CASE
WHEN S1>=35 AND S2>=35 AND S3>=35 THEN 'PASS'
ELSE 'FAIL'
END AS RESULT
FROM STUDENT

===================================================================================
=====

05-dec-24

GROUP BY clause :-
-----------------------------

=> GROUP BY clause is used to group rows based on one or more columns
to calculate min,max,sum,avg,count for each group. For ex to calculate
dept wise no of employees first group the rows based on dept and
apply count function on each dept

emp
empno ename deptno
1 A 20
2 B 10 group by 10
2
3 C 30 ================> 20 2
4 D 20 30 1
5 E 10

detailed data summarized data

=> group by clause converts detailed data to summarized data which is useful for
analysis.

SELECT columns
FROM tabname
[WHERE cond]
GROUP BY colname
[HAVING cond]
[ORDER BY col ASC/DESC]

Execution :-

FROM
WHERE
GROUP BY
HAVING
SELECT
ORDER BY

ex :-

=> display dept wise no of employees ?

SELECT deptno,COUNT(*) as cnt


FROM emp
GROUP BY deptno

FROM emp :-
------------------

emp
empno ename deptno
1 A 20
2 B 10
3 C 30
4 D 20
5 E 10

GROUP BY deptno :-
----------------------------

10 2 B
5 E

20 1 A
4 D

30 3 C

SELECT deptno,COUNT(*) as cnt :-


------------------------------------------------

10 2
20 2
30 1

=> display job wise min sal,max sal,tot sal,no of employees ?

SELECT job, min(sal) as minsal,


max(sal) as maxsal,
sum(sal) as totsal,
count(*) as cnt
FROM emp
GROUP BY job
=> display year wise no of employees joined ?

SELECT DATEPART(yy,hiredate) as year,COUNT(*) as cnt


FROM emp
GROUP BY DATEPART(yy,hiredate)

1980 1
1981 10
1982 2
1983 1

=> display day wise no of employees joined ?

SELECT DATENAME(DW,hiredate) as day,COUNT(*) as cnt


FROM emp
GROUP BY DATENAME(DW,hiredate)

=> month wise no of employees in the year 1981 ?

SELECT DATENAME(MM,hiredate) as MONTH,COUNT(*) as cnt


FROM emp
WHERE DATEPART(YY,hiredate) = 1981
GROUP BY DATENAME(MM,hiredate)

=> find the dept having more than 3 employees ?

SELECT deptno,COUNT(*) as cnt


FROM emp
WHERE COUNT(*) > 3
GROUP BY deptno => ERROR

sql server cannot calculate dept wise count before group by and it can calculate
only
after group by , so apply the condition COUNT(*) > 3 after group by using HAVING
clause

SELECT deptno,COUNT(*) as cnt


FROM emp
GROUP BY deptno
HAVING COUNT(*) > 3

20 5
30 6

WHERE VS HAVING :-
-------------------------------

WHERE HAVING

1 selects specific rows selects specific groups

2 conditions applied conditions applied


before group by after group by

3 use where clause use having clause


if cond doesn't if cond contains
contain aggregate functions aggregate functions
=> display the southern states having more than 5cr persons ?

PERSONS
ADHAARNO NAME GENDER CITY STATE

SELECT state,COUNT(*) as cnt


FROM persons
WHERE state IN ('AP','TG','TN','KA','KL')
GROUP BY states
HAVING COUNT(*) > 5000000

=> display job wise no of employees for the jobs clerk,manager and display only
the
jobs where no of emps > 3 ?

SELECT job,count(*) as cnt


FROM emp
WHERE job IN ('CLERK','MANAGER')
GROUP BY job
HAVING COUNT(*) > 3

=> display dept wise and with in dept job wise no of employees ?

SELECT deptno,job,count(*)
FROM emp
GROUP BY deptno,job
ORDER BY deptno ASC

10 CLERK 1
MANAGER 1
PRESIDENT 1

20 ANALYST 2
CLERK 2
MANAGER 1

30 CLERK 1
MANAGER 1
SALESMAN 4

=> display year wise and with in year quarter wise no of employees joined ?

SELECT DATEPART(yy,hiredate) as year,DATEPART(qq,hiredate) as qrt,count(*) as cnt


FROM emp
GROUP BY DATEPART(yy,hiredate),DATEPART(qq,hiredate)
ORDER BY 1 ASC

GROUP BY year => INVALID


ORDER BY year ASC => VALID

note :-

=> column alias cannot be used in group by clause because group by clause is
executed
before select

=> column alias can be used in order by clause because order by clause is executed
after select
==========================================================================

INTEGRITY CONSTRAINTS
========================

=> integrity constraints are rules to maintain data integrity i.e data quality
or data consistency
=> used to prevent users from entering invalid data .
=> used to enforce rules like min bal must be 1000.

Types of constraints :-
-------------------------------

1 NOT NULL
2 UNIQUE
3 PRIMARY KEY
4 CHECK
5 FOREIGN KEY
6 DEFAULT

=> above constraints can be declared in two ways

1 column level
2 table level

column level :-
----------------------

=> if constraints are declared immediately after declaring column then it is


called column level

CREATE TABLE <tabname>


(
colname datatype(size) constraint ,
---------------------------
)

NOT NULL :-
-------------------

=> NOT NULL constraint doesn't accept null values

ex :-

CREATE TABLE emp11


(
empno INT ,
ename VARCHAR(10) NOT NULL
)

INSERT INTO emp11 VALUES(100,NULL) => ERROR


INSERT INTO emp11 VALUES(101,'A')

UNIQUE :-
----------------

=> unique constraint doesn't accept duplicates


CREATE TABLE emp12
(
empno INT ,
ename VARCHAR(10) NOT NULL,
emailid VARCHAR(20) UNIQUE
)

INSERT INTO emp12 VALUES(100,'A','[email protected]')


INSERT INTO emp12 VALUES(101,'B','[email protected]') => ERROR
INSERT INTO emp12 VALUES(102,'C',NULL)
INSERT INTO emp12 VALUES(103,'D',NULL) => ERROR

NOTE :- unique constraint allows one null

PRIMARY KEY :-
-----------------------

=> primary doesn't accept duplicates and nulls.

=> primary key is the combination of unique & not null/

=> In tables one column must be there to uniquely identify the records and
into that column duplicates and nulls are not allowed , so declare that
column with primary key.

ex :-

CREATE TABLE emp13


(
empno INT PRIMARY KEY ,
ename VARCHAR(10) NOT NULL,
sal MONEY
)

INSERT INTO emp13 VALUES(100,'A',5000)


INSERT INTO emp13 VALUES(100,'B',6000) => ERROR
INSERT INTO emp13 VALUES(NULL,'C',6000) => ERROR

NOTE :-
----------

=> only one primary key is allowed per table , if we want multiple primary keys
then declare one column with primary key and others columns with UNIQUE
NOT NULL.

CREATE TABLE cust


(
CUSTID INT PRIMARY KEY,
CNAME VARCHAR(20) NOT NULL,
ADHAARNO NUMERIC(12) UNIQUE NOT NULL ,
PANNO CHAR(100 UNIQUE NOT NULL
)

difference between UNIQUE & PRIMARY KEY ?

UNIQUE PRIMARY KEY


1 allows one null doesn't allow nulls

2 a table can have multiple unique constraints a table can have only one
primary key

3 sql server creates a non clustered index sql server creates a


clustered index on primary key
on unique column column

07-DEC-24

CHECK constraint :-
---------------------------

=> use check constraint when rule based on condition

CHECK(condition)

Ex 1 :- sal must be min 3000

CREATE TABLE emp14


(
empno INT PRIMARY KEY,
ename VARCHAR(10) NOT NULL ,
sal MONEY CHECK(sal>=3000)
)

INSERT INTO emp14 VALUES(100,'A',1000) => ERROR


INSERT INTO emp14 VALUES(101,'B',5000) => accepted
INSERT INTO emp14 VALUES(102,'C',NULL) => accepted

NOTE :- check constraint allows nulls

ex 2 :- gender must be 'M','F' ?

GENDER CHAR(1) CHECK(GENDER IN ('M','F'))

ex 3 :- amt must be multiple of 100 ?

AMT MONEY CHECK(AMT%100=0)

ex 4 :- pwd mut be min 6 chars ?

PWD VARCHAR(15) CHECK(LEN(PWD) >= 6)

ex 5 :- emailid must contain '@'


must end with '.com' or '.co' or '.in'

EMAILID VARCHAR(20) CHECK(EMAILID LIKE '%@%'


AND
(
EMAILID
LIKE '%.com'
OR
EMAILID
LIKE '%.co'
OR
EMAILID
LIKE '%.in'
))

FOREIGN KEY :-
-------------------------

=> foreign key is used to establish relationship between two tables

=> To establish relationship between two tables , take primary key of


one table and add it to another table as foreign key and
declare with references constraint.

ex :-

projects
projid pname duration cost client
1000 ABC 5 300 TATA MOTORS
1001 KLM 4 200 KLM Airlines

emp
empno ename job sal projid REFERENCES projects(projid)
1 A SE 30 1000
2 B SSE 40 1001
3 9999 => not accepted
4 1000
5 null

=> values entered in fk column should match with values entered in pk column

=> fk allows duplicates & nulls.

=> after declaring fk a relationship is established between the tables called


parent / child relationship.

=> pk table is parent and fk table is child

ex :-

CREATE TABLE projects


(
projid INT PRIMARY KEY,
pname VARCHAR(10) NOT NULL
)

INSERT INTO projects VALUES(1000,'ABC')


INSERT INTO projects VALUES(1001,'KLM')

CREATE TABLE emp_proj


(
empno INT PRIMARY KEY,
ename VARCHAR(10) NOT NULL,
sal MONEY CHECK(sal>=3000),
projid INT REFERENCES projects(projid)
)

INSERT INTO emp_proj VALUES(100,'A',4000,1000)


INSERT INTO emp_proj VALUES(101,'B',3000,9999) => error
INSERT INTO emp_proj VALUES(102,'C',4000,1000)
INSERT INTO emp_proj VALUES(103,'D',3000,NULL)
DEFAULT :-
-----------------

=> a column can be declared with default value as follows

ex :- HIREDATE DATE DEFAULT GETDATE()

=> while inserting if we skip hiredate then sql server inserts default value

ex :-

CREATE TABLE emp15


(
empno INT ,
ename VARCHAR(10),
hiredate DATE DEFAULT GETDATE()
)

INSERT INTO emp15(empno,ename) VALUES(100,'A')


INSERT INTO emp15 VALUES(101,'B','2024-01-01')
INSERT INTO emp15 VALUES(102,'C',NULL)

SELECT * FROM emp15

empno ename hiredate


100 A 2024-12-07
101 B 2024-01-01
102 C NULL

Question :-

ACCOUNTS
ACCNO ACTYPE BAL OPEN_DT

Rules :-
-------------

1 accno should not be duplicate & null


2 actype must be 'S' OR 'C'
3 bal must be min 1000
4 open_dt must be always system date

TRANSACTIONS
TRID TTYPE TDATE TAMT ACCNO

Rules :-
-------------

1 trid must be automatically generated


2 ttype must be 'W' OR 'D'
3 tdate must be always system date
4 tamt must be multiple of 100
5 accno should match with accounts table accno

10-dec-24

Relationship types :-
-----------------------------
1 one to one (1:1)
2 one to many (1:m) DEFAULT
3 many to one (m:1)
4 many to many (m:n)

=> by default sql server creates one to many relationship between two tables

How to establish one to one relationship :-


----------------------------------------------------------

=> to establish one to one (1:1) relationship between two tables declare foreign
key with
unique constraint.

ex :-

projects
projid pname duration cost
1000
1001

manager
mgrno mname start_date end_date projid REFERENCES
projects(projid) UNIQUE
100 A / / 1000
101 B / / 1001

How to establish many to many relationship :-


------------------------------------------------------------

=> to establish many to many relationship then create 3rd table and
add primary keys of both tables as foreign keys

ex :-

course student
cid cname sid sname
10 .NET 1 A
11 SQL SERVER 2 B

registrations
sid cid dor fee
1 10 ?? ??
1 11 ? ?
2 10 ? ?

composite primary key :-


-----------------------------------

=> if combination of columns uniquely identifies the records then that combination
is declared as primary key.

=> if combination of columns declared primary key then it is called composite


primary key.

CREATE TABLE course


(
cid INT PRIMARY KEY,
cname VARCHAR(10) NOT NULL
)

INSERT INTO course VALUES(10,'.net') , (11,'sql server)

CREATE TABLE student


(
sid INT PRIMARY KEY,
sname VARCHAR(10) NOT NULL
)

INESRT INTO student VALUES(1,'A') , (2,'B')

CREATE TABLE registrations


(
sid INT RERFERENCES student(sid) ,
cid INT REFERENCES course(cid) ,
dor DATE ,
fee MONEY,
PRIMARY KEY (sid,cid)
)

INSERT INTO registrations VALUES(1,10,getdate(),5000)


INSERT INTO registrations VALUES(1,11,getdate(),5000)
INSERT INTO registrations VALUES(2,10,getdate(),5000)
INSERT INTO registrations VALUES(1,10,getdate(),5000) => error

=> in composite primary key combination should not be duplicate

Ex 2 :-

CUST PRODUCTS
CID CNAME PRODID PNAME PRICE
10 A 100 A 80
11 B 101 B 120

SALES
DATEID PRODID CID QTY
2024-12-09 100 10 3
2024-12-09 101 10 2
2024-12-09 100 11 2
2024-12-10 100 10 2

11-dec-24

=> which of the following constraint cannot be declared at table level ?

A UNIQUE
B CHECK
C NOT NULL
D FOREIGN KEY
E PRIMARY KEY

ANS :- C

Declaring check constraint at table level :-


----------------------------------------------------------

products
prodid pname price mfd_dt exp_dt
100 AAA 80 2024-12-01 2024-11-01 INVALID

Rule :- exp_dt > mfd_dt

CREATE TABLE products


(
prodid INT PRIMARY KEY,
pname VARCHAR(10) NOT NULL ,
price SMALLMONEY,
mfd_dt DATE ,
exp_dt DATE ,
CHECK(exp_dt > mfd_dt)
)

Which statements are true regarding constraints ?

A a foreign key cannot contain NULL value F


B a column with UNIQUE constraint can contain NULL value T
C a constraint is enforced only for the INSERT operation on a table F
D all constraints can be defined at column level and table level. F

Which CREATE TABLE statement is valid?

A. CREATE TABLE ord_details


(ord_no INT PRIMARY KEY,
item_no INT PRIMARY KEY,
ord_date DATE NOT NULL);

B. CREATE TABLE ord_details


(ord_no INT UNIQUE, NOT NULL,
item_no INT,
ord_date DATE DEFAULT GETDATE() NOT NULL);

C. CREATE TABLE ord_details


(ord_no INT ,
item_no INT,
ord_date DATE DEFAULT NOT NULL,
UNIQUE (ord_no),
PRIMARY KEY (ord_no));

D. CREATE TABLE ord_details


(ord_no INT,
item_no INT,
ord_date DATE DEFAULT GETDATE() NOT NULL,
PRIMARY KEY (ord_no, item_no));

DELETE rules :-
------------------------

ON DELETE NO ACTION (default)


ON DELETE CASCADE
ON DELETE SET NULL
ON DELETE SET DEFAULT

=> delete rule specifies how child rows are affected if parent row is deleted.
=> these rules are declared with foreign key.
ON DELETE NO ACTION :-
-------------------------------------

=> parent row cannot be deleted if associated with child rows

create table dept99


(
dno int primary key,
dname varchar(10) not null
)

insert into dept99 values(10,'hr') , (20,'it')

create table emp99


(
empno int primary key,
ename varchar(10) not null,
dno int references dept99(dno)
)

insert into emp99 values(1,'A',10),(2,'B',10)

DELETE FROM dept99 WHERE dno = 10 => ERROR

scenario :-

ACCOUNTS
ACCNO ACTYPE BAL
100 S 10000
101 S 20000

LOANS
ID TYPE AMT ACCNO REFERENCES ACCOUNTS(ACCNO)
1 H 30 100
2 C 10 100

Rule :- account closing is not allowed if associated with loans

ON DELETE CASCADE :-
------------------------------------

=> parent row is deleted along with child rows.

create table dept99


(
dno int primary key,
dname varchar(10) not null
)

insert into dept99 values(10,'hr') , (20,'it')

create table emp99


(
empno int primary key,
ename varchar(10) not null,
dno int references dept99(dno) ON DELETE CASCADE
)

insert into emp99 values(1,'A',10),(2,'B',10)


DELETE FROM dept99 WHERE dno = 10 => 1 row affected

SELECT * FROM emp99 => no rows

scenario :-

ACCOUNTS
ACCNO ACTYPE BAL
100 S 10000
101 S 20000

TRANSACTIONS
TRID TTYPE TDATE TAMT ACCNO REFERENCES ACCOUNTS(ACCNO)
ON
DELETE CASCADE

Rule :-

=> if account is closed then along with account delete transactions

ON DELETE SET NULL :-


--------------------------------------

=> if parent row is deleted then it is deleted but child rows are not deleted
but fk will be set to null.

create table dept99


(
dno int primary key,
dname varchar(10) not null
)

insert into dept99 values(10,'hr') , (20,'it')

create table emp99


(
empno int primary key,
ename varchar(10) not null,
dno int references dept99(dno) ON DELETE SET NULL
)

insert into emp99 values(1,'A',10),(2,'B',10)

DELETE FROM dept99 WHERE dno = 10 => 1 row affected

SELECT * FROM emp99

empno ename dno


1 A NULL
2 B NULL

scenario :-

projects
projid pname client
1000 A TATA
1001 B DBS
emp
empno ename projid REFERENCES projects (projid)
1 1000 ON DELETE SET NULL
2 1001

RULE :- if project is completed (deleted) then set the employee projid to null

ON DELETE SET DEFAULT :-


-------------------------------------------

=> if parent row is deleted then it is deleted but child rows are not deleted but
fk will be set to default value

create table dept99


(
dno int primary key,
dname varchar(10) not null
)

insert into dept99 values(10,'hr') , (20,'it')

create table emp99


(
empno int primary key,
ename varchar(10) not null,
dno int default 20
references dept99(dno)
ON DELETE SET DEFAULT
)

insert into emp99 values(1,'A',10),(2,'B',10)

DELETE FROM dept99 WHERE dno = 10 => 1 row affected

SELECT * FROM emp99

1 A 20
2 B 20

summary :-

importance of constraints
declaring constraints
column level
table level
relationship types
delete rules

===========================================================================

12-dec-24

JOINS
=====

=> join is an operation performed to display data from two or more table.
=> In DB related data stored in multiple tables , to gather or to combine data
stored
in multiple tables we need to join those tables.

ex :-

orders cust
ordid orddt deldt cid cid cname addr
1000 05 15 100 100 A HYD
1001 08 20 101 101 B HYD
1002 10 21 102 102 C HYD

SELECT o.*,c.*
FROM orders as o INNER JOIN cust as c
ON o.cid = c.cid

OUTPUT :-

ordid orddt deldt cid cname addr


1000 100 A HYD
1001 101 B HYD
1002 102 C HYD

Types of joins :-
----------------------

1 inner join
equi join
non equi join
self join
2 outer join
left join
right join
full join
3 cross join / cartesian join

equi join :-
--------------

=> To perform equi join between the two tables there must be a common field
and name of the common field need not to be same and pk-fk relationship
is not compulsory.

SELECT columns
FROM tab1 INNER JOIN tab2
ON join condition

join condition :-
---------------------

=> join condition specifies which record of tab1 joined with which record of
tab2.

=> based on the given join condition sql server joins records of two tables

table1.commonfield = table2.commonfield

ex :-
emp dept
empno ename sal deptno deptno dname loc
1 A 3000 10 10 ACCOUNTS NEW YORK
2 B 4000 20 20 RESEARCH
3 C 5000 30 30 SALES
4 D 4000 20 40 OPERATIONS
5 E 3000 NULL

=> display employee details with dept details ?

SELECT empno,ename,sal,dname,loc
FROM emp INNER JOIN dept
ON emp.deptno = dept.deptno

1 A 3000 ACCOUNTS NEW YORK


2 B 4000 RESEARCH ???
3 C 5000 SALES ???
4 D 4000 RESEARCH ???

NOTE :-

=> In join queries , declare table alias and prefix column names with
table alias for two reasons

1 to avoid ambiguity
2 for faster execution

ex :-

SELECT e.empno,e.ename,e.sal,d.deptno,d.dname,d.loc
FROM emp as e INNER JOIN dept as d
ON e.deptno = d.deptno

=> display employee details with dept details working at NEW YORK loc ?

SELECT e.ename,d.dname,d.loc
FROM emp as e INNER JOIN dept as d
ON e.deptno = d.deptno /* join cond */
WHERE d.loc = 'NEW YORK' /* filter cond */

=> display order details with cust details to be delivered today ?

SELECT o.*,c.*
FROM orders as o INNER JOIN cust as c
ON o.cid = c.cid
WHERE o.deldt = FORMAT(getdate(),'yyyy-MM-dd')

13-dec-24

joining more than two tables :-


-----------------------------------------

=> if no of tables increases no of join conditioins also increases


=> to join N tables N-1 join conditions required.

SELECT columns
FROM tab1 INNER JOIN tab2
ON join cond
INNER JOIN tab3
ON join cond
INNER JOIN tab4
ON join cond

( (tab1 JOIN tab2) join tab3 ) join tab4

ex :-

emp dept locations countries

empno deptno locid country_id


ename dname city country_name
sal locid state
deptno country_id

=> display ename dname city state country_name ?


---------- ---------- ---------------
----------------------
emp dept locations countries

SELECT e.ename,
d.dname,
l.city , l.state,
c.country_name as country
FROM emp as e INNER JOIN dept as d
ON e.deptno = d.deptno
INNER JOIN locations as l
ON d.locid = l.locid
INNER JOIN countries as c
ON l.country_id = c.country_id

Outer join :-
--------------------

=> Inner join returns only matching records but will not return unmatched records
to display unmatched records perform outer join.

ex :-

emp dept
empno ename sal deptno deptno dname loc
1 A 3000 10 10 ACCOUNTS NEW YORK
2 B 4000 20 20 RESEARCH
3 C 5000 30 30 SALES
4 D 4000 20 40 OPERATIONS => unmatched record
5 E 3000 NULL => unmatched record

=> outer join is 3 types

1 LEFT JOIN
2 RIGHT JOIN
3 FULL JOIN

LEFT JOIN :-
------------------

=> left join returns all rows (matched + unmatched) from left side table and
matching rows from
right side table.

SELECT e.ename,d.dname
FROM emp as e LEFT JOIN dept as d
ON e.deptno = d.deptno

=> above query displays all rows from emp and matching rows from dept

A ACCOUNTS
B RESEARCH
C SALES
D RESEARCH
E NULL => unmatched from emp

RIGHT JOIN :-
-------------------

=> returns all rows from right side table and matching rows from left side table

SELECT e.ename,d.dname
FROM emp as e RIGHT JOIN dept as d
ON e.deptno = d.deptno

=> above query returns all rows from dept table and matching rows from emp table

A ACCOUNTS
B RESEARCH
C SALES
D RESEARCH
NULL OPERATIONS => unmatched from dept

FULL JOIN :-
------------------

=> returns all rows from both tables

SELECT e.ename,d.dname
FROM emp as e FULL JOIN dept as d
ON e.deptno = d.deptno

=> above query returns all rows from both tables

A ACCOUNTS
B RESEARCH
C SALES
D RESEARCH
E NULL => unmatched from emp
NULL OPERATIONS => unmatched from dept

Displaying only unmatched records :-


-----------------------------------------------

left side table :-


----------------------

SELECT e.ename,d.dname
FROM emp as e LEFT JOIN dept as d
ON e.deptno = d.deptno
WHERE d.dname IS NULL

E NULL

right side table :-


------------------------

SELECT e.ename,d.dname
FROM emp as e RIGHT JOIN dept as d
ON e.deptno = d.deptno
WHERE e.ename IS NULL

NULL OPERTIONS

both tables :-
------------------

SELECT e.ename,d.dname
FROM emp as e FULL JOIN dept as d
ON e.deptno = d.deptno
WHERE d.dname IS NULL
OR
e.ename IS NULL

E NULL
NULL OPERATIONS

Question :-

emp projects
empno ename sal projid projid pname duration
1 100 100
2 101 101
3 null 102

1 display employee details with project details ?

SELECT e.* , p.*


FROM emp as e INNER JOIN projects as p
ON e.projid = p.projid

2 display employee details with project details and also


display employees not assigned to any project ?

SELECT e.* , p.*


FROM emp as e LEFT JOIN projects as p
ON e.projid = p.projid

3 display projects where no employee assigned to it ?

SELECT e.*,p.*
FROM emp as e RIGHT JOIN projects as p
ON e.projid = p.projid
WHERE e.empno IS NULL

14-dec-24
Non-Equi join :-
-----------------------

=> Non equi join is performed between the tables not sharing a common field

ex :-

emp salgrade
empno ename sal grade losal hisal
1 A 3000 1 700 1000
2 B 1000 2 1001 2000
3 C 5000 3 2001 3000
4 D 1500 4 3001 4000
5 E 2000 5 4001 9999

=> display ENAME SAL GRADE ?


----------------------- -----------
emp salgrade

SELECT e.ename,e.sal,s.grade
FROM emp as e INNER JOIN salgrade as s
ON e.sal BETWEEN s.losal and s.hisal

A 3000 3
B 1000 1
C 5000 5
D 1500 2
E 2000 2

=> display ENAME DNAME GRADE ?


----------- ----------- --------------
emp dept salgrade

SELECT e.ename,d.dname,s.grade
FROM emp as e INNER JOIN dept as d
ON e.deptno = d.deptno
INNER JOIN salgrade as s
ON e.sal BETWEEN s.losal and s.hisal

ON e.deptno = d.deptno :-
------------------------------------

emp dept
empno ename sal deptno deptno dname loc
1 A 3000 10 10 ACCOUNTS NEW YORK
2 B 4000 20 20 RESEARCH
3 C 5000 30 30 SALES
4 D 4000 20 40 OPERATIONS => unmatched record
5 E 3000 10

output :-

1 A 3000 ACCOUNTS
2 B 4000 RESEARCH
3 C 5000 SALES
4 D 4000 RESEARCH
5 E 3000 ACCOUNTS

on e.sal between s.losal and s.hisal :-


----------------------------------------------------
salgrade
grade losal hisal

1 A 3000 ACCOUNTS 1 700 1000


2 B 4000 RESEARCH 2 1001 2000
3 C 5000 SALES 3 2001 3000
4 D 4000 RESEARCH 4 3001 4000
5 E 3000 ACCOUNTS 5 4001 9999

output :-

1 A 3000 ACCOUNTS 3
2 B 4000 RESEARCH 4
3 C 5000 SALES 5
4 D 4000 RESEARCH 4
5 E 3000 ACCOUNTS 3

SELECT e.ename,d.dname,s.grade :-
--------------------------------------------------

A ACCOUNTS 3
B RESEARCH 4
C SALES 5
D RESEARCH 4
E ACCOUNTS 3

SELF JOIN :-
-------------------

=> joining a table to itself is called self join


=> In self join a record in one table joined with another record of same table
=> to perform self join the same table must be specified two times with different
alias in from clause

FROM emp as x INNER JOIN emp as y

emp x emp y
empno ename mgr empno ename mgr
7369 smith 7902 7369 smith 7902
7499 allen 7698 7499 allen 7698
7566 jones 7839 7566 jones 7839
7698 blake 7839 7698 blake 7839
7839 king null 7839 king null
7902 ford 7566 7902 ford 7566

=> display ENAME MGRNAME ?

SELECT x.ename,y.ename
FROM emp as x INNER JOIN emp as y
ON x.mgr = y.empno

smith ford
allen blake
jones king
blake king
ford jones

=> display employee names reporting to blake ?

SELECT x.ename,y.ename as manager


FROM emp as x INNER JOIN emp as y
ON x.mgr = y.empno
WHERE y.ename = 'blake'

=> display blake's manager name ?

SELECT x.ename,y.ename as manager


FROM emp as x INNER JOIN emp as y
ON x.mgr = y.empno
WHERE x.ename = 'blake'

=> employees earning more than their manager ?

SELECT x.ename,x,sal,
y.ename as manager , y.sal as mgrsal
FROM emp as x INNER JOIN emp as y
ON x.mgr = y.empno
WHERE x.sal > y.sal

Questions :-
----------------

=> employees joined before their manager ?


=> employees earning same salary ?
=> employees joined on same day ?

=> write a query to display following output ?

TEAMS
ID COUNTRY
1 IND
2 AUS
3 ENG

output :-

IND VS AUS
IND VS ENG
AUS VS ENG

TEAMS A TEAMS B
ID COUNTRY ID COUNTRY
1 IND 1 IND
2 AUS 2 AUS
3 ENG 3 ENG

A.ID <> B.ID A.ID < B.ID

IND AUS IND AUS


IND ENG IND ENG
AUS IND AUS ENG
AUS ENG
ENG IND
ENG AUS

SELECT A.COUNTRY + ' VS '+ B.COUNTRY


FROM TEAMS AS A INNER JOIN TEAMS AS B
ON A.ID < B.ID

CROSS / CARTESIAN JOIN :-


----------------------------------------

=> cross join returns cross product or cartesian product of two tables

A = 1,2
B = 3,4

AXB = (1,3 ) (1,4) (2,3) (2,4)

=> if cross join performed between two tables then all records of 1st table
joined with
all the records of 2nd table.

=> to perform cross join submit the join query without join condition.

SELECT columns
FROM tab1 CROSS JOIN tab2

ex :-

SELECT e.ename,d.dname
FROM emp as e CROSS JOIN dept as d

==========================================================================

16-dec-24

SET OPERATORS :-
=================

1 UNION
2 UNION ALL
3 INTERSECT
4 EXCEPT

A = 1,2,3,4
B = 1,2,5,6

A UNION B => 1,2,3,4,5,6


A UNION ALL B => 1,2,3,4,1,2,5,6
A INTERSECT B => 1,2
A EXCEPT B => 3,4
B EXCEPT A => 5,6

=> In sql these operations performed between the result of two queries i.e.
between the
records return by two queries.

SELECT statement 1
UNION / UNION ALL / INTERSECT / EXCEPT
SELECT statement 2
Rules :-

1 both queries must return same no of columns


2 corresponding columns datatype must be same

Query 1 :-

SELECT job FROM emp WHERE deptno = 20

CLERK
MANAGER
ANALYST
CLERK
ANALYST

Query 2 :-

SELECT job FROM emp WHERE deptno = 30

SALESMAN
SALESMAN
SALESMAN
MANAGER
SALESMAN
CLERK

UNION :-
-------------

=> combines rows return by two queries


=> duplicates are eliminated
=> result is sorted

Ex 1 :-

SELECT job FROM emp WHERE deptno = 20


UNION
SELECT job FROM emp WHERE deptno = 30

ANALYST
CLERK
MANAGER
SALESMAN

Ex 2 :-

SELECT job,sal FROM emp WHERE deptno = 20


UNION
SELECT job,sal FROM emp WHERE deptno = 30

ANALYST 3000.00
CLERK 800.00
CLERK 950.00
CLERK 1100.00
MANAGER 2850.00
MANAGER 2975.00
SALESMAN 1250.00
SALESMAN 1500.00
SALESMAN 1600.00

difference between UNION & JOIN ?

UNION JOIN

1 combines rows combines columns

2 horizontal merge vertical merge

3 performed between performed between


records return by two two tables
queries

scenario :-
--------------

EMP_US
eno ename sal dno
100 A 3000 10
101 B 4000 20
DEPT
dno dname loc
EMP_IND 10 HR
eno ename sal dno 20 IT
200 K 3000 10 30 SALES
201 X 4000 30

=> total employees list ?

SELECT * FROM EMP_US


UNION
SELECT * FROM EMP_IND

100 A
101 B
200 K
201 X

=> employees working at US loc with dept details ?

SELECT e.* , d.*


FROM emp_us as e INNER JOIN dept as d
ON e.dno = d.dno

100 A 3000 10 10 HR
101 B 4000 20 20 IT

=> total employees with dept details ?

SELECT e.* , d.*


FROM emp_us as e INNER JOIN dept as d
ON e.dno = d.dno
UNION
SELECT e.* , d.*
FROM emp_ind as e INNER JOIN dept as d
ON e.dno = d.dno
100 A 3000 10 10 HR
101 B 4000 20 20 IT
200 K 3000 10 10 HR
201 X 4000 30 30 SALES

UNION ALL :-
--------------------

=> combines rows return by two queries


=> duplicates are not eliminated
=> result is not sorted

SELECT job FROM emp WHERE deptno = 20


UNION ALL
SELECT job FROM emp WHERE deptno = 30

CLERK
MANAGER
ANALYST
CLERK
ANALYST
SALESMAN
SALESMAN
SALESMAN
MANAGER
SALESMAN
CLERK

difference between UNION & UNION ALL ?

UNION UNION ALL

1 duplicates are eliminated duplicates are not eliminated

2 result is sorted result is not sorted

3 slower faster

INTERSECT :-
--------------------

=> returns common values from the output of two select stmts

SELECT job FROM emp WHERE deptno = 20


INTERSECT
SELECT job FROM emp WHERE deptno = 30

CLERK
MANAGER

EXCEPT :-
---------------

=> returns values present in 1st query output and not present in 2nd query
output

SELECT job FROM emp WHERE deptno = 20


EXCEPT
SELECT job FROM emp WHERE deptno = 30

ANALYST

SELECT job FROM emp WHERE deptno = 30


EXCEPT
SELECT job FROM emp WHERE deptno = 20

SALESMAN

Question 1 :-

T1 T2
F1 C1
1 1
2 2
3 3
10 40
20 50
30 60

=> write the output for the following operations ?

1 inner join
2 left join
3 right join
4 full join
5 union
6 union all
7 intersect
8 except

T1 T2
F1 C1
1 1
2 2
1 1
2 2
NULL NULL
NULL NULL

=> no of rows return by following operations ?

1 inner join => 8


2 left join => 10
3 right join => 10
4 full join => 12

==========================================================================

17-dec-24

SUB-QUERIES OR NESTED QUERIES :-


--------------------------------------------------------
=> a query in another query is called sub-query or nested query
=> one query is called inner / child / sub query
=> other query is called outer / parent / main query
=> first sql server executes inner query next it executes outer query
=> result of inner query is input to outer query
=> use sub-query when where cond based on unknown value

Types of sub-queries :-
-------------------------------

1 Non co-related subqueries


2 co-realted sub-queries
3 Derived tables & CTEs
4 scalar sub-queries

non co-related sub-queries :-


--------------------------------------

SELECT columns
FROM tabname
WHERE colname OP (SELECT statement)

=> OP must be any relational opertors like = > >= < <= <>

Ex :-

=> employees earning more than blake ?

SELECT *
FROM emp
WHERE sal > ( SELECT sal FROM emp WHERE ename='BLAKE')

-----------------------------------------------------------------------
2850

=> employees who are senior to king ?

SELECT *
FROM emp
WHERE hiredate < ( SELECT hiredate FROM emp WHERE ename='KING' )

-----------------------------------------------------------------------------
1981-11-17

=> name of the employee earning max salary ?

SELECT ename
FROM emp
WHERE sal = MAX(sal) => ERROR

aggregate functions are not allowed in where clause and they are allowed only
in
select,having clauses

SELECT ename
FROM emp
WHERE sal = (SELECT MAX(sal) FROM emp)
-------------------------------------------
5000
=> name of the employee having max experience ?

SELECT ename
FROM emp
WHERE hiredate = (SELECT MIN(hiredate) FROM emp )

=> display 2nd max sal ?

SELECT MAX(sal)
FROM emp
WHERE sal < (SELECT MAX(sal) FROM emp)

=> name of the employee earning 2nd max sal ?

SELECT ename
FROM emp
WHERE sal = (SELECT MAX(sal)
FROM emp
WHERE sal < (SELECT MAX(sal) FROM emp))

=> delete the employee having max expr ?

DELETE FROM emp WHERE hiredate = (SELECT MIN(hiredate) FROM emp)

=> increment sal by 10% employee having max expr ?

UPDATE emp
SET sal = sal + (sal*0.1)
WHERE hiredate = (SELECT MIN(hiredate) FROM emp)

=> swap employee salaries whose empno = 7369,7499 ?

before swap after swap

7369 800 7369 1600


7499 1600 7499 800

UPDATE emp
SET sal = CASE empno
WHEN 7369 THEN (SELECT sal FROM emp WHERE empno=7499)
WHEN 7499 THEN (SELECT sal FROM emp WHERE empno = 7369)
END
WHERE empno IN (7369,7499)

=> display employees working at NEW YORK loc ?

sub-query :-
------------------

SELECT *
FROM emp
WHERE deptno = (SELECT deptno FROM dept WHERE loc='NEW YORK')

join :-
-----------

SELECT e.*
FROM emp as e INNER JOIN dept as d
ON e.deptno = d.deptno
WHERE d.loc = 'NEW YORK'

=> display employee details with dept details working at NEW YORK loc ?

join :-
------

SELECT e.*,d.*
FROM emp as e INNER JOIN dept as d
ON e.deptno = d.deptno
WHERE d.loc = 'NEW YORK'

sub-query :-
----------------

not possible

SUB-QUERY VS JOIN :-
------------------------------------

=> to display data from one table and condition based on another table then we
can use
sub-query or join.

=> to display data from two tables use join operation.

=> employees working at NEW YORK,CHICAGO locations ?

SELECT *
FROM emp
WHERE deptno IN (SELECT deptno FROM dept WHERE loc IN ('NEW
YORK','CHICAGO'))

-----------------------------------------------------------------------------------
------------

10
30

co-related sub-queries :-
---------------------------------

=> if inner query references values of outer query then it is called co-related
sub-query.

=> execution starts from outer query and inner query is executed no of times
depends
on no of rows return by outer query.

=> use co-related sub-query to execute sub-query for each row return by outer
query

ex :-

emp
empno ename sal deptno
1 A 5000 10
2 B 3000 20
3 C 4000 30
4 D 6000 20
5 E 3000 10

=> employees earning more than avg sal of the organization ?

SELECT *
FROM emp
WHERE sal > ( SELECT AVG(sal) FROM emp)
--------------------------------------------
4200

=> employees earning more than avg sal of their dept ?

SELECT *
FROM emp as x
WHERE sal > (SELECT AVG(sal) FROM emp WHERE deptno = x.deptno)

emp
empno ename sal deptno
1 A 5000 10 5000 > (4000) TRUE
2 B 3000 20 3000 > (4500) FALSE
3 C 4000 30 4000 > (4000) FALSE
4 D 6000 20 6000 > (4500) TRUE
5 E 3000 10 3000 > (4000) FALSE

=> employees earning max sal in their dept ?

SELECT *
FROM emp as x
WHERE sal = (SELECT MAX(sal) FROM emp WHERE deptno = x.deptno)

emp
empno ename sal deptno
1 A 5000 10 5000 = (5000) TRUE
2 B 3000 20 3000 = (6000) FALSE
3 C 4000 30 4000 = (4000) TRUE
4 D 6000 20 6000 = (6000) TRUE
5 E 3000 10 3000 = (5000) FALSE

18-dec-24

=> display top 3 max salaries ?

SELECT DISTINCT a.sal


FROM emp as a
WHERE 3 > (SELECT COUNT(DISTINCT b.sal)
FROM emp as b
WHERE a.sal < b.sal)
ORDER BY 1 DESC

emp a emp b
sal sal
5000 5000 3 > (0) TRUE
1000 1000 3 > (4) FALSE
3000 3000 3 > (2) TRUE
2000 2000 3 > (3) FALSE
4000 4000 3 > (1) TRUE
=> display 3rd max salary ?

SELECT DISTINCT a.sal


FROM emp as a
WHERE (3-1) = (SELECT COUNT(DISTINCT b.sal)
FROM emp as b
WHERE a.sal < b.sal)
ORDER BY 1 DESC

Derived tables :-
-------------------------

=> sub-queries in FROM clause are called derived tables

SELECT columns
FROM (SELECT statement) as <alias>
[WHERE cond]

=> sub-query output acts like a table for outer query

=> derived tables are used to control order of execution of clauses

default order of execution :-


-------------------------------------

FROM
WHERE
GROUP BY
HAVING
SELECT
ORDER BY

=> to control this order of execution use derived table

SELECT columns SELECT


FROM tab ======================> FROM (SELECT
WHERE cond
FROM tab
ORDER BY col ORDER BY col

WHERE
Ex 1 :-

=> display ranks of the employees based on sal ?

SELECT empno,ename,sal,
DENSE_RANK() OVER (ORDER BY SAL DESC) as rnk
FROM emp

=> above query returns ranks of all the employees but to display top 5 employees

SELECT empno,ename,sal,
DENSE_RANK() OVER (ORDER BY SAL DESC) as rnk
FROM emp
WHERE rnk <= 5 => ERROR
column alias cannot be used in where clause because where clause is executed
before select
to overcome this use derived table

SELECT *
FROM (SELECT empno,ename,sal,
DENSE_RANK() OVER (ORDER BY sal DESC) as rnk
FROM emp) as e
WHERE rnk <= 5

=> display top 5 max salaries ?

SELECT DISTINCT sal


FROM (SELECT sal,
DENSE_RANK() OVER (ORDER BY sal DESC) as rnk
FROM emp) as e
WHERE rnk <= 5
ORDER BY sal DESC

ROW_NUMBER() :-
--------------------------

=> returns record numbers


=> row_number is also based on one or more columns
=> for row_number also data must be sorted

ROW_NUMBER() OVER (ORDER BY col ASC/DESC)

Ex :-

SELECT ROW_NUMBER() OVER (ORDER BY empno ASC) as rno,


empno,ename,sal
FROM emp

=> above query displays row numbers for all the records but to display first 5
rows

SELECT *
FROM ( SELECT ROW_NUMBER() OVER (ORDER BY empno ASC) as rno,
empno,ename,sal
FROM emp ) as e
WHERE rno <= 5

WHERE rno IN (5,10,14)

WHERE rno BETWEEN 5 AND 10

WHERE rno%2 = 0

=> display last 3 rows ?

SELECT *
FROM ( SELECT ROW_NUMBER() OVER (ORDER BY empno ASC) as rno,
empno,ename,sal
FROM emp ) as e
WHERE rno >= (SELECT COUNT(*)-2 FROM emp)

simple select
where
order by
distinct
top
group by & having
functions
joins
set operators
sub-queries

19-dec-24

DATABASE TRANSACTIONS :-
------------------------------------------

=> a transaction is a unit of work that contains one or more dmls and must be
saved as a whole or must be cancelled as a whole.

ex :- money transfer

acct1 ------------------------1000------------------------->acct2

update1
update2
(bal = bal-1000)
(bal = bal + 1000)

successful failed INVALID

failed
successful INVALID

successful successful VALID

failed failed VALID

=> if transaction contains multiple operations if all are successful then it


must be
saved , if one of the operation fails then entire transaction must be
cancelled
and this property is called atomocity i.e. all or none.

=> the following commands provided by sql server to handle transactions called
TCL commands

COMMIT => to save txn


ROLLBACK => to cancel txn
SAVE TRANSACTIONS => to cancel part of the txn

=> every txn has a begin point and an end point

=> In sql server a txn begins implicitly with dml and ends implicitly with commit.

update ============> begin transaction


update
commit

delete ==============> begin transaction


delete
commit

=> a user can also start transaction by executing "begin transaction" command and
end transaction by executing commit / rollback command.

ex 1 :-

create table a(a int) => implicitly committed


insert into a values(10) => implicitly committed
insert into a values(20) => implicitly committed
insert into a values(30) => implicitly committed
insert into a values(40) => implicitly committed
rollback => trying to end txn without
starting => error

ex 2 :-

create table a(a int)


begin transaction => txn begins T1
insert into a values(10)
insert into a values(20)
insert into a values(30)
insert into a values(40)
rollback => txn ends

if txn ends with rollback then operations are cancelled

ex 3 :-

create table a(a int) => implicitly committed


begin transaction => txn begins T1
insert into a values(10)
insert into a values(20)
commit => txn ends
insert into a values(30) => implicitly committed
insert into a values(40) => implicitly committed
rollback => error

SAVE TRANSACTION :-
---------------------------------

=> we can declare save transaction and we can rollback upto the save transaction
=> using save transaction we can cancel part of the transaction

ex :-

create table a(a int)


begin transaction
insert into a values(10)
insert into a values(20)
save transaction st1
insert into a values(30)
insert into a values(40)
save transaction st2
insert into a values(50)
insert into a values(60)
rollback transaction st2
select * from a

10
20
30
40

DATABASE SECURITY :-
----------------------------------

LOGINS => provides security at server level


USERS => provides security at db level
PRIVILEGES => provides security at table level
VIEWS => provides security at row & col level

SERVER (LOGIN)
DATABASE (USER)
TABLE (PRIVILEGE)
ROWS & COLS (VIEW)

creating logins in sql server :-


---------------------------------------

=> In object explorer select

security
logins => New Login

Enter Login Name :- NARESH

select authentication :- sql server

enter password :- 123

confirm password :- 123

=> click OK

command to create login :-


-------------------------------------

=> open master database and execute the following command

CREATE LOGIN NARESH WITH PASSWORD='abc'

NOTE :-

=> a new login is created but cannot access databases , so to access database
login
must be associated with a user in database.

creating user in db :-
---------------------------

=> In object explorer expand Databases


BATCH2728
Users => New
User

Enter Username :- KUMAR

Enter Login Name :- NARESH

=> click OK

command to create user :-


-----------------------------------

=> open the database in which you want to create user for ex BATCH2728 and
execute the
following command

CREATE USER [VIJAY] FOR LOGIN [NARESH]

SERVER
LOGIN
SA
NARESH

BATCH2728
DBO (SA)
EMP
DEPT
CUST
STUDENT
KUMAR (NARESH)

NOTE :-

=> user kumar cannot access tables created by dbo

PRIVILEGES :-
--------------------

=> privileges means permissions


=> permissions granted to user by using grant command

GRANT <privileges> ON <tabname> TO <usernames>

Ex 1 :- granting all permissions

DBO :-
----------

GRANT SELECT,INSERT,UPDATE,DELETE ON EMP TO KUMAR

KUMAR :-
-------------

1 SELECT * FROM EMP

2 UPDATE EMP SET SAL=2000 WHERE EMPNO = 7369


3 DELETE FROM EMP WHERE EMPNO = 7369

Ex 2 :- granting read only permission

DBO :-
-----------

GRANT SELECT ON DEPT TO KUMAR

KUMAR :-
------------

1 SELECT * FROM DEPT

2 UPDATE DEPT SET LOC='HYD' WHERE DEPTNO = 10 => ERROR

REVOKE command :-
-----------------------------

=> command used to take back the permissions from user

REVOKE <privileges> ON <tabname> FROM <usernames>

Ex :-

DBO :-
-------------

REVOKE SELECT,INSERT,UPDATE,DELETE ON EMP FROM KUMAR

21-dec-24

DB objects :-
==========

1 TABLES
2 VIEWS
3 SYNONYMS
4 SEQUENCES
5 INDEXES

VIEWS :-
-----------

=> a view is a subset of a table i.e. part of the table.

=> a view is a virtual table because it doesn't store data and doesn't occupy
memory
and it always derives data from base table.

=> a view is representation of a query

=> views are created

1 to provide security
2 to reduce complexity

=> views are 2 types


1 simple views
2 complex views

simple views :-
--------------------

=> if view based on single table then it is called simple view

CREATE VIEW <name>


AS
SELECT statement

Ex :-

CREATE VIEW V1
AS
SELECT empno,ename,job,deptno FROM emp

sql server creates view V1 and stores query but not query output i.e. data

SELECT * FROM V1

sql server executes the above query as follows

SELECT * FROM (SELECT empno,ename,job,deptno FROM emp)

Granting permissions on view to user :-


-----------------------------------------------------

DBO :-
-----------

GRANT SELECT,INSERT,UPDATE,DELETE ON V1 TO KUMAR

KUMAR :-
--------------

1 SELECT * FROM V1

2 INSERT INTO V1 VALUES(8888,'KKK','CLERK',20)

3 UPDATE V1 SET JOB='MANAGER' WHERE EMPNO = 8888

NOTE :-

1 if we make any changes (DMLs) to view that changes are applied to table
2 if we make any changes to table we can see the changes in view

ROW LEVEL SECURITY :-


-------------------------------------

CREATE VIEW V2
AS
SELECT empno,ename,job,deptno
FROM emp
WHERE deptno = 20

DBO :-
--------

GRANT SELECT,INSERT,UPDATE,DELETE ON V2 TO KUMAR

KUMAR :-
-------------

=> user kumar can access only the employees belongs to 20th dept

1 SELECT * FROM V2

2 INSERT INTO V2 VALUES(9999,'PQR','CLERK',30) => 1 row affected

above insert command executed successfully even though it is violating where


cond

WITH CHECK OPTION :-


--------------------------------

=> if view created with " WITH CHECK OPTION " then any dml command through view
violates where cond that dml is not accepted

CREATE VIEW V3
AS
SELECT empno,ename,job,deptno
FROM emp
WHERE deptno = 20
WITH CHECK OPTION

GRANT SELECT,INSERT,UPDATE, DELETE ON V3 TO KUMAR

KUMAR :-
-------------

INSERT INTO V3 VALUES (8899,'LMN','CLERK',30) => ERROR

Complex views :-
------------------------

=> a view said to be complex view

1 if based on multiple tables


2 if query contains group by clause
distinct clause
aggregate functions
set operators
sub-queries

=> with the help of views complex queries can be converted into simple queries

Ex 1 :-

CREATE VIEW CV1


AS
SELECT e.empno,e.ename,e.sal,
d.deptno,d.dname,d.loc
FROM emp e INNER JOIN dept d
ON e.deptno = d.deptno
=> after creating view whenever we want data from emp & dept tables instead of
writing
complex join query write the simple query as follows

SELECT * FROM CV1

Ex 2 :-

CREATE VIEW CV2


AS
SELECT deptno,MIN(sal) as minsal,
MAX(sal) as maxsal,
SUM(sal) as totsal,
COUNT(*) as cnt
FROM emp
GROUP BY deptno

after creating view whenever we want dept wise summary execute the following
query

SELECT * FROM CV2

difference between simple and complex views ?

simple complex

1 based on single table based on multiple tables

2 query performs simple query performs complex operations


operations

3 allows dmls doesn't allow dmls

=> list of tables & viwes ?

SELECT * FROM INFORMATION_SCHEMA.TABLES

=> display only tables list ?

SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE='BASE TABLE'

=> display list of views ?

SELECT * FROM INFORMATION_SCHEMA.VIEWS

Droping :-
-------------

DROP VIEW V1

23-dec-24

synonyms :-
----------------

=> a synonym is another name or alternative name for a table or view


=> If tablename is lengthy then we can give a simple and short name to the
table called synonym and instead of using tablename we can use
synonym name in SELECT / INSERT / UPDATE / DELETE queries.

CREATE SYNONYM <name> FOR <tabname>

Ex :-

CREATE SYNONYM E FOR EMP

=> after creating synonym instead of using tablename EMP we can use
synonym name E as follows

1 SELECT * FROM E

2 UPDATE E SET SAL =1000 WHERE EMPNO = 7369

Question :-

1 create synonym e for emp


2 select * from emp as e
3 sp_rename 'emp','e' => changes tablename from emp to e

difference between synonym and alias ?

synonym alias

1 permanent not permanent

2 stored in db not stored in db

3 scope of the scope of the alias


synonym upto the is upto the query
db

=> list of synonyms ?

SELECT name,base_object_name FROM sys.synonyms

E EMP

Droping :-
--------------

DROP SYNONYM E

=> by default every db is created with following schemas

1 DBO => stores user define tables


2 INFORMATION_SCHEMA => stores system defined tables
3 SYS => stores system defined tables

How to create schema :-


----------------------------------

=> schemas are created to group related objects


CREATE SCHEMA <name>

Ex :-

CREATE SCHEMA SALES

=> to create table in sales schema

CREATE TABLE SALES.CUST


(
CID INT,
CNAME VARCHAR(10)
)

INSERT INTO SALES.CUST VALUES(10,'A') , (11,'B')

SELECT * FROM SALES.CUST

SEQUENCES :-
----------------------

=> sequence is also a db object created to generate sequence numbers


=> used to auto increment column values

CREATE SEQUENCE <name>


[START WITH <value>]
[INCREMENT BY <value>]
[MAXVALUE <value>]
[MINVALUE <value>]
[CYCLE]

Ex 1 :-

CREATE SEQUENCE S1
START WITH 1
INCREMENT BY 1
MAXVALUE 5

CREATE TABLE student


(
sid INT,
sname VARCHAR(10)
)

use above sequence to generate sid for every new student

INSERT INTO student VALUES(NEXT VALUE FOR S1, 'A')


INSERT INTO student VALUES(NEXT VALUE FOR S1, 'B')
INSERT INTO student VALUES(NEXT VALUE FOR S1, 'C')
INSERT INTO student VALUES(NEXT VALUE FOR S1, 'D')
INSERT INTO student VALUES(NEXT VALUE FOR S1, 'E')
INSERT INTO student VALUES(NEXT VALUE FOR S1, 'F') => ERROR

Ex 2 :-

CREATE SEQUENCE S2
START WITH 100
INCREMENT BY 1
MAXVALUE 999

use above sequence to update empno ?

UPDATE emp SET empno = NEXT VALUE FOR S2

Ex 3 :-

BILL
BILLNO BDATE AMT
NIT/1224/1 ? ?
NIT/1224/2

CREATE TABLE BILL


(
BILLNO VARCHAR(20) ,
BDATE DATETIME,
AMT MONEY
)

CREATE SEQUENCE S3
START WITH 1
INCREMENT BY 1
MAXVALUE 9999

INSERT INTO BILL VALUES('NIT/' + FORMAT(getdate() , 'MMyy') + '/' +


CAST(NEXT VALUE FOR S3 AS
VARCHAR),getdate(),2000)

How to restart sequence :-


-------------------------------------

1 manually by using alter command


2 automatically by using cycle option

by using alter command :-


-------------------------------------

ALTER SEQUENCE S1 RESTART WITH 1

by using cycle option :-


--------------------------------

CREATE SEQUENCE S10


START WITH 1
INCREMENT BY 1
MAXVALUE 5
MINVALUE 1
CYCLE

=> list of sequences created by user ?

SELECT * FROM INFORMATION_SCHEMA.SEQUENCES

Droping sequence :-
------------------------------
DROP SEQUENCE S1

=> difference between identity & sequence ?

IDENTITY SEQUENCE

1 bind to specific table and specific column not bind to any column

2 can't access identity next value we can access


sequence next value
by using next value for
sequence

3 not declared with maxvalue can be declared


with maxvalue

4 identity cannot be reset sequence can be reset

INDEXES :-
----------------

=> index is also a db object created to improve query performance.

=> index makes data accessing faster.

=> index in db is similar to index in textbook , in textbook using index


a particular topic can be located fastly but in db using index
a particular row can be located fastly.

=> indexes are created on columns and that column is called index key.

=> indexes are created on columns which are

1 frequently used in where clause


2 frequently used in join condition

Types of Indexes :-
----------------------------

1 Non clustered
2 Clustered

Non Clustered Index :-


-----------------------------------

CREATE INDEX <name> ON <tabname>(colname)

Ex :-

CREATE INDEX I1 ON EMP(SAL)

EMP
sal
3000
1000
2000
5000
3000
4000
1500
2500

=> SQL SERVER uses following methods to fetch data from table

1 TABLE SCAN
2 INDEX SCAN

=> In table scan sql server scans comple table i.e. each and every row but in
index scan
on avg sql server scans only half of the table , so index scan is much
faster than
table scan.

SELECT * FROM emp WHERE sal = 3000 (index scan)


SELECT * FROM emp WHERE sal >= 3000 (index scan)
SELECT * FROM emp WHERE sal <= 3000 (index scan)

SELECT * FROM emp ; (table scan)


SELECT * FROM emp WHERE ename='BLAKE' (table scan)

UNIQUE index :-
------------------------

=> unique index doesn't allow duplicate values into the column on which index is
created.

ex :- CREATE UNIQUE INDEX I2 ON EMP(ename)

G Q

ADAMS * JAMES * MARTIN *


SCOTT *
ALLEN * JONES * MILLER *
SMITH *
BLAKE *

1 SELECT * FROM emp WHERE ename = 'BLAKE'

2 INSERT INTO emp(empno,ename,sal) VALUES(8888,'BLAKE',4000) => ERROR

=> what are the different methods to enforce uniqueness ?

1 primary key / unique constraint


2 unique index

=> primary key / unique columns are automatically indexed by sql server and
a unique index is created on primary key / unique column and unique
index doesn't allow duplicates so primary key / unique also doesn't allow
duplicates.

26-dec-24

Clustered Index :-
--------------------------
=> a non clustered index stores pointers actual records where as clustered
index stores acutal records.

ex :- create table cust


(
cid int ,
cname varchar(10)
)

create clustered index ci1 on cust(cid)

insert into cust values(10,'A')


insert into cust values(80,'B')
insert into cust values(40,'C')
insert into cust values(60,'D')

50

30 70

10 A 40 C 60 D 80 B

1 select * from cust => sql server goes to index and access all the
leaf nodes from left to right

2 select *from cust where cid = 60 => sql server goes to index and
finds cid=60 and returns the
row from index

=> difference between clustered and non clustered index ?

clustered non clustered

1 stores actual records stores pointers to acutal records

2 table and index are table and index are


not seperate objects seperate

3 doesn't need extra memory needs extra memory

4 requires only one lookup requires two lookups


to find the record to find the record

5 only one clustered index sql server allows


allowed per table 999 non clustered indexes
per table

6 by default it is created on by default it is created on


primary key column unique column

=> list of indexes ?

SP_HELPINDEX emp

Droping index :-
--------------------
DROP INDEX EMP.I1

SERVER
DATABASE
TABLE
ROWS & COLS
CONSTRAINTS
INDEXES
TRIGGERS
VIEWS
SYNONYMS
SEQUENCES

Question :-
-----------------

SQL> DROP TABLE products;

What is the implication of this command? (Choose all that apply.)

A. All data along with the table structure is deleted T.


B. All indexes on the table will remain but they are invalidated. F
C. All views and synonyms will remain but they are invalidated. T
D. All data in the table are deleted but the table structure will remain. F

SQL

commands clauses operations objects

DDL where filtering tables


DML order by sorting views
DQL distinct eliminating duplicates synonyms
TCL top top n rows sequences
DCL group by grouping indexes
having filtering groups
on join
set operations
sub-queries
functions

================================================================

T-SQL (Transact-SQL)
-----------------------------

Basic programming
conditional statements
loops
cursors
error handling
stored procedures
functions
triggers

SQL SERVER
SQL T-SQL
(commands) (blocks)

Features :-
----------------

1 improves performance :-
--------------------------------

=> In T-SQL , sql commands can be grouped into one block and we submit
that block to sql server. so in T-SQL no of requests and response between
user and sql server are reduced and performance is improved.

2 supports conditional statements :-


----------------------------------------------

=> T-SQL supports conditional statements like IF-ELSE , so in t-sql


we can execute sql commands based on conditions.

3 supports loops :-
---------------------------

=> T-SQL supports loops like while ,so in t-sql we can execute sql commands
repeatedly multiple times.

4 supports error handling :-


----------------------------------

=> In t-sql if any statement causes error then we can handle that error
and we can replace system generated message with our own simple
and user friendly message.

5 supports reusability :-
----------------------------

=> T-SQL programs can be stored in db and applications which are connected
to sql server can reuse t-sql programs.

=> T-SQL blocks are 2 types

1 Anonymous Blocks
2 Named
stored procedures
functions
triggers

Anonymous Blocks :-
-----------------------------

=> a t-sql block without name is called anonymous block


=> the following statements are used in T-SQL blocks

1 DECLARE
2 SET
3 PRINT

DECLARE :-
------------------
=> statement used to declare variables

DECLARE @varname DATATYPE(SIZE)

Ex :-

DECLARE @x INT
DECLARE @s VARCHAR(20)
DECLARE @d DATE

DECLARE @x INT , @s VARCHAR(20),@d DATE

SET :-
---------

=> statement used to assign value to a variable

SET @varname = value

Ex :-
SET @x = 100
SET @s = 'ABC'
SET @d = getdate()

PRINT :-
---------------

=> statement used to print values or messages

PRINT @x
PRINT @s
PRINT @d
PRINT 'hello'

=> wap to add two numbers ?

declare @a tinyint,@b tinyint,@c tinyint


set @a=10
set @b=20
set @c = @a+@b
print @c

=> wap to input date and print day of the week ?

declare @d date
set @d = '2025-01-01'
print DATENAME(dw,@d)

DB programming with T-SQL :-


-----------------------------------------

=> To work with db execute sql commands from t-sql program.


=> the following commands can be executed from t-sql program.

1 DML (insert,update,delete)
2 DQL (select)
3 TCL (commit,rollback,save transaction)
SELECT stmt syntax :-
-----------------------------

SELECT @var1 = col1 ,


@var2 = col2
FROM tabname
WHERE cond

ex :-

SELECT @n=ename,@s= sal


FROM emp
WHERE empno = 7844

27-dec-24

=> wap to input empno and print name & salary ?

DECLARE @eno INT,@name VARCHAR(10),@sal MONEY


SET @eno = 105
SELECT @name = ename , @sal = sal
FROM emp
WHERE empno = @eno
PRINT @name + ' ' + CAST(@sal as varchar)

=> wap to input empno and calculate and print experience ?

DECLARE @eno INT ,@doj DATE , @expr TINYINT


SET @eno = 107
SELECT @doj = hiredate
FROM emp
WHERE empno = @eno
SET @expr = DATEDIFF(yy,@doj,getdate())
PRINT 'Experience = ' + CAST(@expr AS VARCHAR) + ' years'

conditional statements :-
---------------------------------

1 IF-ELSE
2 Multi IF
3 Nested IF

IF-ELSE :-
---------------

IF cond
BEGIN
statements
END
ELSE
BEGIN
statements
END

Multi-IF :-
---------------

IF cond1
BEGIN
statements
END
ELSE IF cond2
BEGIN
statements
END
ELSE IF cond3
BEGIN
statements
END
ELSE
BEGIN
statements
END

Nested IF :-
----------------

IF COND
BEGIN
IF COND
BEGIN
statements
END
ELSE
BEGIN
statements
END
END
ELSE
BEGIN
statements
END

=> wap to input empno and increment sal by specific amount and
after increment if sal exceeds 5000 then cancel that increment ?

DECLARE @eno INT ,@amt MONEY ,@sal MONEY


SET @eno = 107
SET @amt = 1000
BEGIN TRANSACTION
UPDATE emp SET sal = sal + @amt WHERE empno = @eno
SELECT @sal = sal FROM emp WHERE empno = @eno
IF @sal > 5000
ROLLBACK
ELSE
COMMIT

=> wap to input empno and increment sal based on job ?

if job=CLERK incr sal by 10%


SALESMAN 15%
MANAGER 20%
others 5%

DECLARE @eno INT,@job VARCHAR(10),@pct TINYINT


SET @eno = 107
SELECT @job=job FROM emp WHERE empno = @eno
IF @job='CLERK'
SET @pct = 10
ELSE IF @job='SALESMAN'
SET @pct=15
ELSE IF @job='MANAGER'
SET @pct=20
ELSE
SET @pct=5
UPDATE emp SET sal = sal + (sal*@pct/100) WHERE empno = @eno

=> wap to process bank transaction (W/D) ?

ACCOUNTS
ACCNO ACTYPE BAL
100 S 10000
101 S 20000

TRANSACTIONS
TRID TTYPE TDATE TAMT ACCNO

DECLARE @acno INT,@type CHAR(1),@amt MONEY,@bal MONEY


SET @acno = 100
SET @type='W'
SET @amt=1000
IF @type='W'
BEGIN
SELECT @bal = bal FROM accounts WHERE accno = @acno
IF @amt > @bal
BEGIN
PRINT 'insufficient balance'
END
ELSE
BEGIN
UPDATE accounts SET bal = bal - @amt WHERE accno = @acno
INSERT INTO transactions (ttype,tdate,tamt,accno)
VALUES('W',getdate(),@amt,@acno)
END
END
ELSE IF @type='D'
BEGIN
UPDATE accounts SET bal = bal + @amt WHERE accno = @acno
INSERT INTO transactions (ttype,tdate,tamt,accno)
VALUES('D',getdate(),@amt,@acno)
END
ELSE
PRINT 'invalid transaction type'

=> wap to process money transfer ?

DECLARE @sacno INT,@tacno INT,@amt MONEY,@bal MONEY


SET @sacno = 100
SET @tacno = 101
SET @amt = 100
SELECT @bal = bal FROM accounts WHERE accno = @sacno
IF @amt > @bal
PRINT 'insufficient balance'
ELSE
BEGIN
BEGIN TRANSACTION
UPDATE accounts SET bal = bal - @amt WHERE accno = @sacno
UPDATE accounts SET bal = bal + @amt WHERE accno = @tacno
INSERT INTO transactions (ttype,tdate,tamt,accno)
VALUES('W',getdate(),@amt,@sacno)
INSERT INTO transactions (ttype,tdate,tamt,accno)
VALUES('D',getdate(),@amt,@tacno)
COMMIT
END

30-dec-24

=> wap to input sno and calculate total,avg,result and insert into result table ?

STUDENT
sno sname s1 s2 s3
1 A 80 90 70
2 B 30 40 60

RESULT
sno stotal savg sresult

DECLARE @sno INT , @s1 TINYINT,@s2 TINYINT,@s3 TINYINT


DECLARE @total INT,@avg DECIMAL(5,2),@res CHAR(4)
SET @sno = 1
SELECT @s1 = s1 , @s2 = s2 , @s3 = s3 FROM student WHERE sno = @sno
SET @total = @s1 + @s2 + @s3
SET @avg = @total/3
IF @s1>=35 AND @s2>=35 AND @s3>=35
SET @res = 'pass'
ELSE
SET @res = 'fail'
INSERT INTO result VALUES(@sno,@total,@avg,@res)

WHILE loop :-
--------------------

WHILE(cond)
BEGIN
statements
END

if cond = true loop continues


if cond = false loop terminates

=> wap to print numbers from 1 to 20 ?

DECLARE @x tinyint = 1
WHILE(@x<=20)
BEGIN
PRINT @x
SET @x = @x + 1
END

=> wap to print 2025 calendar ?

2025-01-01 ?
2025-01-02 ?

2025-12-31 ?
DECLARE @d1 DATE,@d2 DATE
SET @d1 = '2025-01-01'
SET @d2 = '2025-12-31'
WHILE(@d1 <= @d2)
BEGIN
PRINT CAST(@d1 AS VARCHAR) + ' ' + DATENAME(dw,@d1)
SET @d1 = DATEADD(dd,1,@d1)
END

=> wap to print sundays between two dates ?

DECLARE @d1 DATE,@d2 DATE


SET @d1 = '2025-01-01'
SET @d2 = '2025-12-31'
WHILE(@d1 <= @d2)
BEGIN
IF DATENAME(dw,@d1) = 'sunday'
PRINT CAST(@d1 AS VARCHAR) + ' ' + DATENAME(dw,@d1)
SET @d1 = DATEADD(dd,1,@d1)
END

DECLARE @d1 DATE,@d2 DATE


SET @d1 = '2025-01-01'
SET @d2 = '2025-12-31'
WHILE(DATENAME(dw,@d1) <> 'sunday')
BEGIN
SET @d1 = DATEADD(dd,1,@d1)
END
WHILE(@d1 <= @d2)
BEGIN
PRINT CAST(@d1 AS VARCHAR) + ' ' + DATENAME(dw,@d1)
SET @d1 = DATEADD(dd,7,@d1)
END

CURSORS :-
------------------

=> cursors are used to process multiple rows in t-sql program.

=> using cursors we can access row-by-row into t-sql program.

=> from t-sql program if we submit a query to sql server then


it goes to db and copies the data from db to cursor which
is allocated in instance (ram) , In T-SQL program we can
give name to the cursor and acess row-by-row into t-sql program
and process the row.

=> follow below steps to use cursor

1 DECLARE CURSOR
2 OPEN CURSOR
3 FETCH RECORDS FROM CURSOR
4 CLOSE CURSOR
5 DEALLOCATE CURSOR

Declaring cursor :-
---------------------------

DECLARE <name> CURSOR FOR SELECT statement


Ex ;-

DECLARE CURSOR FOR SELECT ename,sal FROM emp

Opening cursor :-
----------------------

OPEN <cursor-name>

ex :- OPEN C1

1 select stmt is submitted to sql server


2 data returned by query is copied to cursor
3 c1 points to cursor

Fetching records from cursor :-


------------------------------------------

=> "FETCH" stmt is used to fetch records from cursor

FETCH NEXT FROM <cursor-name> INTO <variables>

ex :- FETCH NEXT FROM C1 INTO @ename,@sal

=> a fetch stmt fetches one row at a time but to process multiple rows
fetch stmt should be executed multiple times , so fetch should be in a loop.

Closing cursor :-
-----------------------

CLOSE <cursor-name>

Ex :- CLOSE c1

Deallocating cursor :-
-------------------------------

DEALLOCATE <cursor>

Ex :- DEALLOCATE c1

@@FETCH_STATUS :-
--------------------------------

=> It is a system variable that returns fetch status


=> it returns 0 or -1

0 => if fetch successful


-1 => if fetch unsuccessful

31-dec-24

=> wap to print all employee names and salaries ?

DECLARE C1 CURSOR FOR SELECT ename,sal FROM emp


DECLARE @ename VARCHAR(10),@sal MONEY
OPEN C1
FETCH NEXT FROM C1 INTO @ename,@sal
WHILE(@@FETCH_STATUS=0)
BEGIN
PRINT @ename + ' ' + CAST(@sal as VARCHAR)
FETCH NEXT FROM C1 INTO @ename,@sal
END
CLOSE C1
DEALLOCATE C1

=> wap to calculate total sal without using sum function ?

DECLARE C1 CURSOR FOR SELECT sal FROM emp


DECLARE @sal MONEY , @total MONEY=0
OPEN C1
FETCH NEXT FROM C1 INTO @sal
WHILE(@@FETCH_STATUS=0)
BEGIN
SET @total = @total + @sal
FETCH NEXT FROM C1 INTO @sal
END
PRINT @total
CLOSE C1
DEALLOCATE C1

=> wap to find max sal without using max function ?

DECLARE C1 CURSOR FOR SELECT sal FROM emp


DECLARE @sal MONEY , @max MONEY
OPEN C1
FETCH NEXT FROM C1 INTO @max
WHILE(@@FETCH_STATUS=0)
BEGIN
FETCH NEXT FROM C1 INTO @sal
IF @sal > @max
SET @max = @sal
END
PRINT @max
CLOSE C1
DEALLOCATE C1

DECLARE C1 CURSOR FOR SELECT sal FROM emp ORDER BY sal DESC
DECLARE @sal MONEY
OPEN C1
FETCH NEXT FROM C1 INTO @sal
PRINT @sal
CLOSE C1
DEALLOCATE C1

=> wap to print min salary ?

=> wap to calculate all the students total,avg,result and insert into result
table ?

STUDENT
sno sname s1 s2 s3
1 A 80 90 70
2 B 30 40 60
RESULT
sno stotal savg sresult

DECLARE C1 CURSOR FOR SELECT sno,s1,s2,s3 FROM student


DECLARE @sno INT,@s1 TINYINT,@s2 TINYINT,@s3 TINYINT
DECLARE @total INT,@avg DECIMAL(5,2),@res CHAR(4)
OPEN C1
FETCH NEXT FROM C1 INTO @sno,@s1,@s2,@s3
WHILE(@@FETCH_STATUS=0)
BEGIN
SET @total = @s1 + @s2 + @s3
SET @avg = @total/3.0
IF @s1>=35 AND @s2>=35 AND @s3>=35
SET @res = 'PASS'
ELSE
SET @res='FAIL'
INSERT INTO result VALUES(@sno,@total,@avg,@res)
FETCH NEXT FROM C1 INTO @sno,@s1,@s2,@s3
END
CLOSE C1
DEALLOCATE C1

SCROLLABLE CURSOR :-
-----------------------------------

=> by default cursor is forward only cursor and it supports only forward
navigation but
doesn't support backward navigation

=> if cursor declared scroll then it is called scrollable cursor and it supports
both forward and
backward navigation.

=> a forward only cursor supports only FETCH NEXT statement but scrollable cursor

supports the following fetch statements.

FETCH FIRST => fetches first row


FETCH NEXT => fetches next row
FETCH PRIOR => fetches previous row
FETCH LAST => fetches last row
FETCH ABSOLUTE N => fetches Nth row from first row
FETCH RELATIVE N => fetchex Nth row from current row

=> wap to print employee names from last to first ?

DECLARE C1 CURSOR SCROLL FOR SELECT ename FROM emp


DECLARE @name VARCHAR(10)
OPEN C1
FETCH LAST FROM C1 INTO @name
WHILE(@@FETCH_STATUS=0)
BEGIN
PRINT @name
FETCH PRIOR FROM C1 INTO @name
END
CLOSE C1
DEALLOCATE C1
=> wap to print every 5th employee name ?

DECLARE C1 CURSOR SCROLL FOR SELECT ename FROM emp


DECLARE @name VARCHAR(10)
OPEN C1
FETCH RELATIVE 5 FROM C1 INTO @name
WHILE(@@FETCH_STATUS=0)
BEGIN
PRINT @name
FETCH RELATIVE 5 FROM C1 INTO @name
END
CLOSE C1
DEALLOCATE C1

1-jan-25

=> wap to print employee names as follows ?

smith,allen,ward,jones,martin,------------

DECLARE C1 CURSOR FOR SELECT ename FROM emp


DECLARE @n VARCHAR(10),@s VARCHAR(1000)=''
OPEN C1
FETCH NEXT FROM C1 INTO @n
WHILE(@@FETCH_STATUS=0)
BEGIN
SET @s = @s + @n + ','
FETCH NEXT FROM C1 INTO @n
END
PRINT STUFF(@s,len(@s),1,'.')
CLOSE C1
DEALLOCATE C1

STRING_AGG() :-
---------------------------

=> function used to concatenate column values

STRING_AGG(colname , seperator)

ex :- SELECT STRING_AGG(ename , ',') FROM EMP

=> display dept wise employee names ?

SELECT deptno,STRING_AGG(ename , ',') as names


FROM EMP
GROUP BY deptno

10 MILLER,CLARK,KING
20 SCOTT,SMITH,JONES,FORD,ADAMS
30 JAMES,MARTIN,BLAKE,ALLEN,WARD,TURNER

========================================================================

02-jan-25
ERROR HANDLING / EXCEPTION HANDLING :-
=====================================

1 syntax errors
2 logical errors
3 runtime errors

=> errors raised during program execution are called runtime errors

ex :- declare @x tinyint
set @x = 500 => runtime error

=> if any statement causes runtime error then sql server displays error
message but messages generated by sql server are not user friendly ,
so to replace system generated message with our own simple and
user friendly message then we need to handle that runtime error.

=> to handle runtime error include a block TRY-----CATCH block.

BEGIN TRY
statement1
statement2 => stmts causes runtime error
statement3
statement4
END TRY
BEGIN CATCH
statements => stmts handles runtime error
END CATCH

=> if any statement in try block causes exception then control is transferred to
catch block
and execute the statements in catch block.

Ex 1 :-

declare @a tinyint,@b tinyint,@c tinyint


begin try
set @a=100
set @b=0
set @c=@a/@b
print @c
end try
begin catch
print 'error try again'
end catch

ERROR HANDLING functions :-


------------------------------------------

1 ERROR_NUMBER() => returns error code


2 ERROR_MESSAGE() => returns error message

declare @a tinyint,@b tinyint,@c tinyint


begin try
set @a=100
set @b=0
set @c=@a/@b
print @c
end try
begin catch
if error_number() =220
print 'value exceeding limit'
else if ERROR_NUMBER()=8134
print 'divisor cannot be zero'
end catch

ex 2 :-

CREATE TABLE emp55


(
empno INT PRIMARY KEY,
ename VARCHAR(10) NOT NULL,
sal MONEY CHECK(sal>=3000)
)

wap to insert data into emp55 ?

DECLARE @eno INT,@name VARCHAR(10),@sal MONEY


BEGIN TRY
SET @eno = 100
SET @name='ABC'
SET @sal=5000
INSERT INTO emp55 VALUES(@eno,@name,@sal)
END TRY
BEGIN CATCH
IF ERROR_NUMBER() = 2627
PRINT 'empno should not be duplicate'
ELSE IF ERROR_NUMBER() = 515
PRINT 'name should not be null'
ELSE IF ERROR_NUMBER() = 547
PRINT ' sal >= 3000'
ELSE
PRINT ERROR_MESSAGE()
END CATCH

USER DEFINED ERRORS :-


----------------------------------------

=> errors raised by user are called user defined errors.


=> user raises error to terminate program execution based on some condition.
=> the following built-in procedure is used to raise user defined error

RAISERROR(error msg,error severity level,error state)

serverity level => 0 - 25

0-9 messages
10-18 errors
19-25 fatal error

state => 0 to 255 => if same error raised at multiple


locations
using state we can identify which
part of the program
causing that error

Ex 1 :-
=> wap to input empno and increment sal by specific amount
but sunday updates are not allowed ?

DECLARE @eno INT,@amt MONEY


SET @eno = 104
SET @amt = 1000
IF DATENAME(DW,getdate())='sunday'
RAISERROR('sunday not allowed',15,1)
ELSE
UPDATE emp SET sal = sal + @amt WHERE empno = @eno

Ex 2 :-

=> wap to process money withdrawl ?

ACCOUNTS
ACCNO ACTYPE BAL
100 S 10000
101 S 20000

TRANSACTIONS
TRID TTYPE TDATE TAMT ACCNO

DECLARE @acno INT , @amt MONEY,@bal MONEY


SET @acno = 100
SET @amt=1000
SELECT @bal = bal FROM accounts WHERE accno = @acno
IF @amt > @bal
RAISERROR('insufficient balance',16,1)
ELSE
BEGIN
UPDATE accounts SET bal = bal - @amt WHERE accno = @acno
INSERT INTO transactions (ttype,tdate,tamt,accno)
VALUES('W',getdate(),@amt,@acno)
END

ex 3 :-

CREATE TABLE emp55


(
empno INT PRIMARY KEY,
ename VARCHAR(10) NOT NULL,
sal MONEY CHECK(sal>=3000)
)

wap to insert data into emp55 ?

DECLARE @eno INT,@name VARCHAR(10),@sal MONEY


BEGIN TRY
SET @eno = 101
SET @name='pqr'
SET @sal=1000
INSERT INTO emp55 VALUES(@eno,@name,@sal)
END TRY
BEGIN CATCH
IF ERROR_NUMBER() = 2627
RAISERROR('empno should not be duplicate',16,1)
ELSE IF ERROR_NUMBER() = 515
RAISERROR('name should not be null',16,1)
ELSE IF ERROR_NUMBER() = 547
RAISERROR('sal>=3000',16,1)
ELSE
PRINT ERROR_MESSAGE()
END CATCH

========================================================================

NAMED T-SQL BLOCKS :-


------------------------------------

1 STORED PROCEDURES
2 FUNCTIONS
3 TRIGGERS

SUB-PROGRAMS :-
---------------------------

1 STORED PROCEDURES
2 FUNCTIONS

Advantages :-
-------------------

1 modular programming :-
--------------------------------

=> with the help of procedures and functions we can divide a big T-SQL program
into
small modules and small modules are easy to code ,compile,execute and
debug.

2 reusability :-
-----------------

=> procedures & functions can be stored in db and applications which are
connected
to db can reuse these procedures & functions.

3 invoked from front-end :-


----------------------------------

=> procedures and functions can be invoked from front-end applications like
java/.net/python

4 improves performance :-
---------------------------------

=> proc/func improves performance because of one time compilation i.e. when we
create a procedure program is compiled and stored in db and whenever we
call procedure only execution is repeated but not compilation , so this
improves
performance.

STORED PROCEDURES :-
--------------------------------------
=> a procedure is a named T-SQL Block that accepts some input
performs some actions on db and may or may not returns a value.

=> procedures are created to perform one or more actions like


insert,update,delete

CREATE OR ALTER PROCEDURE <name>


parameters if any
AS
statements

parameters :-
--------------------

=> parameters are used to receive values from calling program and sends value to
calling program
=> parameters are 2 types

1 INPUT (DEFAULT)
2 OUTPUT

=> INPUT parameter always receives value


=> OUTPUT parameter always sends value

C#.NET PROCEDURE

A ----------------------------------------------------------> X
(INPUT)

B <----------------------------------------------------------- Y
(OUTPUT)

Ex 1 :- procedure without parameters

=> create procedure to increment all the employee salaries by 1000

CREATE OR ALTER PROCEDURE raise_salary


AS
UPDATE emp SET sal = sal + 1000

procedure created (compiled + stored in db)

Executing :-
-----------------

EXECUTE raise_salary

Ex 2 :- procedure with parameters

=> create procedure to increment specific employee sal by specific amount ?

CREATE OR ALTER PROCEDURE raise_salary


@eno INT ,
@amt MONEY
AS
UPDATE emp SET sal = sal + @amt WHERE empno = @eno

Execution :-
1 EXECUTE raise_salary 104,1000 positional association

2 EXECUTE raise_salary @eno=104,@amt=1000 named association

3 EXECUTE raise_salary @amt=1000,@eno=104

Ex 3 :- procedure with output parameter

=> create a procedure to increment specific employee sal by specific amount


and after increment send the updated sal to calling program.

CREATE OR ALTER PROCEDURE raise_salary


@eno INT,
@amt MONEY,
@newsal MONEY OUTPUT
AS
UPDATE emp SET sal = sal + @amt WHERE empno = @eno
SELECT @newsal = sal FROM emp WHERE empno = @eno

Execution :-
-----------------

declare @s money
execute raise_salary 104,1000,@s output
print @s

declare @s money
execute raise_salary @eno=104,@amt=1000,@newsal=@s output
print @s

4-jan-24

Declaring parameter with default value :-


--------------------------------------------------------

=> a parameter can be declared with default value as follows

@amt money = 500

=> while calling procedure if we don't pass value to @amt sql server assigns
default value i.e. 500

ex 4 :-

CREATE OR ALTER PROCEDURE raise_salary


@eno INT,
@amt MONEY = 500,
@newsal MONEY OUTPUT
AS
UPDATE emp SET sal = sal + @amt WHERE empno = @eno
SELECT @newsal = sal FROM emp WHERE empno = @eno

execution :-

declare @s money
execute raise_salary 100,default,@s output
print @s

declare @s money
execute raise_salary @eno=100,@newsal=@s output
print @s

ex 5 :-

create procedure to process money withdrawl ?

ACCOUNTS
ACCNO ACTYPE BAL
100 S 10000
101 S 20000

TRANSACTIONS
TRID TTYPE TDATE TAMT ACCNO

CREATE OR ALTER PROCEDURE DEBIT


@acno INT ,
@amt MONEY,
@newbal MONEY OUTPUT
AS
DECLARE @bal MONEY
SELECT @bal = bal FROM accounts WHERE accno = @acno
IF @amt > @bal
RAISERROR('insufficient balance',16,1)
ELSE
BEGIN
UPDATE accounts SET bal = bal - @amt WHERE accno = @acno
INSERT INTO transactions(ttype,tdate,tamt,accno)
VALUES('W',getdate(),@amt,@acno)
SELECT @newbal = bal FROM accounts WHERE accno = @acno
END

=> create a procedure for money deposit ?

=> create a proceudre for money transfer ?

USER DEFINE FUNCTIONS :-


------------------------------------------

=> functions created by user are called user define functions.

=> when predefine functions not meeting our requirements then we create
our own functions called user define functions.

=> a function is also a named T-SQL block that accepts some input
performs some calculation and must return a value.

=> functions are 2 types

1 scalar valued functions (svf)


2 table valued functions (tvf)

scalar valued functions :-


---------------------------------

=> these functions returns one value


=> return type must scalar types like int,varchar,money
=> return expression is a scalar variable
CREATE OR ALTER
FUNCTION <name>(parameters) RETURNS <type>
AS
BEGIN
statements
RETURN <expr>
END

Ex 1 :-

CREATE OR ALTER
FUNCTION CALC(@a INT,@b INT,@op CHAR(1)) RETURNS INT
AS
BEGIN
DECLARE @c INT
IF @op='+'
SET @c = @a + @b
ELSE IF @op='-'
SET @c = @a - @b
ELSE IF @op='*'
SET @c = @a*@b
ELSE
SET @c = @a/@b
RETURN @c
END

Execution :-

SELECT dbo.calc(10,20,'*') => 200

Ex 2 :-

orders products
ordid prodid qty prodid pname price
1000 100 2 100 A 1000
1000 101 3 101 B 2000
1000 102 2 102 C 1500
1001 100 2

=> create a function to calculate total amount of particular order ?

input :- ordid = 1000


output amount = 11000

CREATE OR ALTER
FUNCTION getOrdAmt(@d INT) RETURNS MONEY
AS
BEGIN
DECLARE C1 CURSOR FOR SELECT o.prodid,o.qty,p.price
FROM orders as o INNER JOIN
products as p
ON o.prodid = p.prodid
WHERE o.ordid = @d
DECLARE @pid INT,@qty INT,@price MONEY
DECLARE @amt MONEY = 0
OPEN C1
FETCH NEXT FROM C1 INTO @pid,@qty,@price
WHILE(@@FETCH_STATUS=0)
BEGIN
SET @amt = @amt + (@qty*@price)
FETCH NEXT FROM C1 INTO @pid,@qty,@price
END
CLOSE C1
DEALLOCATE C1
RETURN @amt
END

C1
100 2 1000
101 3 2000
102 2 1500

Execution :-

SELECT DBO.GETORDAMT(1000) => 11000

5-jan-25

TABLE VALUED FUNCTIONS :-


--------------------------------------------

=> these functions returns records


=> return type of these function must be table
=> return expression must be a select stmt
=> tvf allows only one stmt and it must be return stmt

CREATE OR ALTER
FUNCTION <name>(parameters) RETURNS TABLE
AS
RETURN (SELECT statement)

Ex 1 :-

=> create a function to accept deptno and returns employees working for that dept
?

create or alter
function getEmpList(@dno INT) RETURNS TABLE
AS
RETURN (SELECT * FROM emp WHERE deptno=@dno)

Execution :-

SELECT * FROM dbo.getEmpList(20)

Ex 2 :-

=> create a function to return top n employees list based on sal ?

CREATE OR ALTER
FUNCTION getTopN(@n INT) RETURNS TABLE
AS
RETURN ( SELECT *
FROM (SELECT empno,ename,sal,
dense_rank() over (order by sal desc) as
rnk
FROM emp) AS E
WHERE rnk<= @n )

Execution :-

SELECT * FROM dbo.getTopN(5)

Ex 3 :-

=> create a function to get top N employees in each dept ?

Assignment :-
------------------

ACCOUNTS
ACCNO ACTYPE BAL
100 S 10000
101 S 20000

TRANSACTIONS
TRID TTYPE TDATE TAMT ACCNO

create procedures & functions to implement following bank transactions ?

1 account opening (proc)


2 account closing (proc)
3 balance enquiry (svf)
4 money deposit (proc)
5 money withdrawl (proc)
6 money transfer (proc)
7 statement between two given dates (tvf)
8 latest N transactions of particular customer (tvf)

=> difference between scalar and table valued functions ?

scalar table

1 returns one value returns records

2 return type must be return type must be TABLE


scalar types like int,varchar

3 return expr must be scalar return expr must be select stmt


variable

4 called in select clause called in from clause

=> difference between procedures & functions ?

procedures functions

1 may or may not returns a value must return a value

2 can return multiple values always returns one value

3 returns values using output parameter returns value using return stmt

4 allows dmls stmts doesn't allow dmls stmts


5 cannot be called from sql commands can be called from sql commands

6 created to perform dml operations created for calculations

7 create procedure to update bal create function to get balance

=> list of procedures & functions ?

SELECT ROUTINE_NAME,ROUTINE_TYPE,ROUTINE_DEFINITION
FROM INFORMATION_SCHEMA.ROUTINES

Droping :-
--------------

DROP PROCEDURE raise_salary

DROP FUNCTION calc

6-jan-24

TRIGGERS :-
-----------------

=> a trigger is also a named T-SQL block like procedure but executed implicitly
by sql server
whenever user submits DML commands

=> triggers are created

1 to control dmls
2 to enforce complex rules and validations
3 to audit day-to-day operations on tables

CREATE OR ALTER TRIGGER <NAME>


ON <TABNAME>
AFTER / INSTEAD OF INSERT,UPDATE,DELETE
AS
STATEMENTS

AFTER triggers :-
------------------------

=> if trigger is after then sql server executes the trigger after executing dml

INSTEAD OF triggers :-
--------------------------------

=> if trigger is instead of then sql server executes the trigger instead of
executing dml

Ex 1 :-

=> create trigger to not to allow dmls on emp table on sunday ?

CREATE OR ALTER TRIGGER T1


ON EMP
AFTER INSERT,UPDATE,DELETE
AS
IF DATENAME(DW,getdate())='sunday'
BEGIN
ROLLBACK
RAISERROR('sunday not allowed',16,1)
END

Testing :-
--------------

update emp set sal=3000 where empno=104 => ERROR

Ex 2 :-

=> create trigger to not to allow dmls on emp table as follows ?

MON - FRI <10AM AND >4PM


SAT <10AM AND >2PM
SUN --------------------------

CREATE OR ALTER TRIGGER T2


ON EMP
AFTER INSERT,UPDATE,DELETE
AS
IF DATEPART(DW,GETDATE()) BETWEEN 2 AND 6
BEGIN
IF DATEPART(HH,GETDATE()) < 10 OR DATEPART(HH,GETDATE()) >= 16
BEGIN
ROLLBACK
RAISERROR('only between 10am and 4pm',16,1)
END
END
ELSE IF DATEPART(DW,GETDATE())=7
BEGIN
IF DATEPART(HH,GETDATE()) < 10 OR DATEPART(HH,GETDATE()) >= 14
BEGIN
ROLLBACK
RAISERROR('only between 10am and 2pm',16,1)
END
END
ELSE
BEGIN
ROLLBACK
RAISERROR('sunday not allowed',16,1)
END

Testing :-
--------------

update emp set sal=3000 where empno=104 => ERROR

Ex 3 :-

=> create trigger to not to allow to update empno ?

CREATE OR ALTER TRIGGER T3


ON EMP
AFTER UPDATE
AS
IF UPDATE(empno) OR UPDATE(hiredate)
BEGIN
ROLLBACK
RAISERROR('cannot update empno and hiredate',16,1)
END

Ex 4 : - create trigger to not to allow to update ename more than 2 times ?

Magic Tables :-
---------------------

1 INSERTED
2 DELETED

=> these two tables are called magic tables.

=> these tables exists only during trigger execution , once trigger execution is
completed then these tables are deleted.

=> with the help of magic tables we can access data affected by dmls

=> record user is trying to insert is copied to INSERTED table

=> record user is trying to delete is copied to DELETED table.

=> record user is trying to update is copied to both INSERTED & DELETED tables

ex :-

insert into emp values(100,'A','clerk',4000,--20) => INSERTED

delete from emp where empno = 105 => DELETED

update emp set sal=3000 where empno=100 => INSERTED


empno sal
100 3000

DELETED
empno sal
100 2500

7-jan-25

=> create trigger to not to allow user to decrement salary ?

CREATE OR ALTER TRIGGER T4


ON EMP
AFTER UPDATE
AS
DECLARE @OLDSAL MONEY,@NEWSAL MONEY
SELECT @OLDSAL = SAL FROM DELETED
SELECT @NEWSAL = SAL FROM INSERTED
IF @NEWSAL < @OLDSAL
BEGIN
ROLLBACK
RAISERROR('sal cannot be decremented',16,1)
END

Testing :-

UPDATE EMP SET SAL=1000 WHERE EMPNO=100 => ERROR

/*
1 row is copied to inserted,deleted tables
2 executes update command
3 executes trigger

*/

=> create trigger to insert details into emp_resign table when employee resigns ?

EMP_RESIGN
EMPNO ENAME JOB SAL HIREDATE DOR

CREATE TABLE EMP_RESIGN


(
EMPNO INT,
ENAME VARCHAR(10),
JOB VARCHAR(10),
SAL MONEY,
HIREDATE DATE,
DOR DATE
)

CREATE OR ALTER TRIGGER T5


ON EMP
AFTER DELETE
AS
DECLARE @eno INT,@name VARCHAR(10),@job VARCHAR(10),@sal MONEY,@hire DATE
SELECT @eno=empno , @name=ename,@job=job,@sal=sal,@hire=hiredate FROM deleted
INSERT INTO emp_resign VALUES(@eno,@name,@job,@sal,@hire,getdate())

Testing :-

DELETE FROM emp WHERE empno = 100

/*
1 row is copied to deleted table
2 executes delete command
3 executes trigger
*/

=> create trigger to audit day-to-day operations (I,U,D) on emp table ?

EMP_AUDIT
uname operation odate new_eno new_ename new_sal old_eno old_ename
old_sal

CREATE TABLE EMP_AUDIT


(
uname VARCHAR(10),
operation VARCHAR(10),
odate DATETIME,
new_eno INT,
new_ename VARCHAR(10),
new_sal MONEY,
old_eno INT,
old_ename VARCHAR(10),
old_sal MONEY
)

CREATE OR ALTER TRIGGER T6


ON EMP
AFTER INSERT,UPDATE,DELETE
AS
DECLARE @neweno INT,@newename VARCHAR(10),@newsal MONEY
DECLARE @oldeno INT,@oldename VARCHAR(10),@oldsal MONEY
DECLARE @cnt1 INT,@cnt2 INT,@op VARCHAR(10)
SELECT @cnt1=COUNT(*) FROM INSERTED
SELECT @cnt2=COUNT(*) FROM DELETED
SELECT @neweno=empno,@newename=ename,@newsal=sal FROM INSERTED
SELECT @oldeno=empno,@oldename=ename,@oldsal=sal FROM DELETED
IF @cnt1=1 AND @cnt2=0
SET @op='INSERT'
ELSE IF @cnt1=0 AND @cnt2=1
SET @op='DELETE'
ELSE
SET @op='UPDATE'
INSERT INTO emp_audit
VALUES(user_name() , @op,getdate(),@neweno,@newename,@newsal,
@oldeno,@oldename,@oldsal)

Testing :-
-------------

1 INSERT INTO emp(empno,ename,sal) VALUES(777,'ABC',5000)


2 update emp set sal=6000 where empno = 777
3 delete from emp where empno=777

SELECT * FROM emp_audit

AFTER INSERT

DECLARE @neweno INT,@newename VARCHAR(10),@newsal MONEY


SELECT @neweno=empno,@newename=ename,@newsal=sal FROM INSERTED
INSERT INTO emp_audit
VALUES(user_name() , 'INSERT',getdate(),
@neweno,@newename,@newsal,
NULL,NULL,NULL)

=> display triggername & tabname ?

sys.triggers
sys.tables
name object_id parent_id name object_id

SELECT tr.name,tb.name
FROM sys.triggers as tr INNER JOIN sys.tables as tb
ON tr.parent_id = tb.object_id
Droping triggers ;-
--------------------------

DROP TRIGGER T1

================================================================

8-jan-25

Dynamic SQL :-
-----------------------

=> SQL commands generated at runtime are called dyhnamic SQL commands

ex :- DROP TABLE emp (static sql)

DECLARE @tname VARCHAR(10)


SET @tname='EMP'
DROP TABLE @tname (dynamic sql)

=> dynamic sql is useful when we don't know table names and column names
until runtime.

=> dynamic sql commands are executed by using EXEC procedure

EXEC (' dynamic sql command ')

=> dynamic sql command that you want to execute should be passed as a
string to EXEC procedure.

Ex 1 :-

=> create a procedure to drop table ?

CREATE OR ALTER PROCEDURE drop_table


@tname VARCHAR(30)
AS
EXEC (' DROP TABLE ' + @tname)

Execution :-

EXECUTE drop_table 'emp_resign'

Ex 2 :-

=> create a procedure to drop all tables ?

CREATE OR ALTER PROCEDURE drop_all_tables


AS
DECLARE C1 CURSOR FOR SELECT TABLE_NAME
FROM
INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE='BASE
TABLE'
DECLARE @TNAME VARCHAR(30)
OPEN C1
FETCH NEXT FROM C1 INTO @TNAME
WHILE(@@FETCH_STATUS=0)
BEGIN
EXEC (' DROP TABLE ' + @TNAME)
FETCH NEXT FROM C1 INTO @TNAME
END
CLOSE C1
DEALLOCATE C1

Execution :-

EXECUTE DROP_ALL_TABLES

========================================================================

9-jan-25

BACKUP & RESTORE :-


----------------------------------

=> backup is the process of protecting db from failures like


hardware,software,network etc
=> copying db from server to file (.bak) is called backup
=> backup file is useful to restore db if any failure occurs
=> recovering db from backup is called restore.

command to take backup :-


-----------------------------------

BACKUP DATABASE DB9AM TO DISK = 'D:\BACKUPS\DB9AM.BAK'

How to take backup of all databases :-


---------------------------------------------------

CREATE OR ALTER PROCEDURE backup_dbs


AS
DECLARE C1 CURSOR FOR SELECT name
FROM sys.databases
WHERE database_id > 4
DECLARE @dbname VARCHAR(100)
DECLARE @fname VARCHAR(100)
OPEN C1
FETCH NEXT FROM C1 INTO @dbname
WHILE(@@FETCH_STATUS=0)
BEGIN
SET @fname = 'D:\BACKUPS\' + @dbname + '.bak'
BACKUP DATABASE @dbname TO DISK = @fname
FETCH NEXT FROM C1 INTO @dbname
END
CLOSE C1
DEALLOCATE C1

RESTORING DATABASE :-
-------------------------------------

RESTORE DATABASE <NAME> FROM DISK = filename

Ex :-

RESTORE DATABASE DB9AM FROM DISK = 'D:\BACKUPS\DB9AM.BAK'


==========================================================================

You might also like