0% found this document useful (0 votes)
3 views

SQL

The document provides an overview of databases, including types like OLTP and OLAP, and explains the role of DBMS and RDBMS in managing data. It details the database development life cycle, SQL Server features, and various SQL data types and commands. Additionally, it covers the process of creating databases and tables in SQL Server, along with examples of data insertion and operators used in SQL.

Uploaded by

Ajith Golla
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

SQL

The document provides an overview of databases, including types like OLTP and OLAP, and explains the role of DBMS and RDBMS in managing data. It details the database development life cycle, SQL Server features, and various SQL data types and commands. Additionally, it covers the process of creating databases and tables in SQL Server, along with examples of data insertion and operators used in SQL.

Uploaded by

Ajith Golla
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 139

07-sep-23

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

=> a Database is a organized collection of interrelated data ,


for example a univ db stores data related to students,courses,faculty etc.

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
data 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.


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

USER------------------------DBMS----------DB

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

1960 FMS (File Mgmt System)

1970 HDBMS (Hierarchical)


NDBMS (Network)

1980 RDBMS (Relational)

1990 ORDBMS (Object Relational)

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

=> RDBMS concepts are introduced by E.F.CODD


=> E.F.CODD introduced 12 rules
=> a db that supports all 12 rules is called perfect rdbms

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

=> according to information rule data must be organized in tables i.e. rows and
columns

CUSTOMERS
CID NAME ADDR => columns/fields/attributes
10 SACHIN MUM
11 RAHUL DEL
12 VIJAY HYD => row / record / tuple

Database = collection of tables


Table = collection of rows & cols
Row = collection of field values
Column = collection of values assigned to one field

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

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

08-sep-23

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

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

SQL SERVER from microsoft


ORACLE from oracle corp
MYSQL from oracle corp
DB2 from IBM
POSTGRESQL from postgresql forum
RDS from amazon

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

=> object relational dbms


=> ordbms is combination of rdbms & oops

ordbms = rdbms + oops (reusability)

=> RDBMS doesn't support reusability but ORDBMS supports reusability

ORDBMS softwares :-
---------------------------

SQL SERVER
ORACLE
POSTGRESQL

what is SQL SERVER ?

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

DB Development Life Cycle :-


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

1 Analysis
2 Design
3 Development
4 Testing
5 Implementation
6 Maintenance

Design :-
---------------

=> Designing db means designing tables.


=> DB is designed by db designers or db architects.
=> DB is designed by using

1 ER Model (Entity Relationship)


2 Normalization

Development :-
----------------------

=> DB is developed by Developers & DBAs


=> DB is developed by using any RDBMS tool like sql server

Developers DBAs

creating tables installation of sql server


creating views creating database
creating synonyms creating logins
creating sequences backup & restore
creating indexes db export & import
creating procedures performance tuning
creating functions db upgradation &
migration
creating triggers
writing queries

09-sep-23

=> DB is tested by QA (Quality Assurance) team by using some tools called


testing tools like selenium.

=> implementation means moving db from DEV server to PROD server.

=> DB can deployed in

1 on premises server
2 cloud server

=> in " on premises " db is deployed in server managed by client.

=> in " on cloud " db is deployed in the server managed by cloud service
provider
for ex amazon.
summary :-

what is db ?
what is dbms ?
what is rdbms ?
what is ordbms ?
db development life cycle ?

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

SQL SERVER
-------------------

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

=> sql server can be used for both development and administration.

versions :-
---------------

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 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 where users can

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

client tool :-

SSMS (SQL SERVER MANAGEMENT STUDIO)

USER----SSMS-----------------------------------------SQL SERVER------DB

11-SEP-23

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

=> SQL stands for structured query language


=> 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 submitted to sql server
to perform some operation over db.
=> sql is originally introduced by IBM and initial name of this language was
"sequel" and later it is renamed to sql.
=> sql is common to all relational db softwares

SQL SERVER ORACLE MYSQL POSTGRESQL DB2 RDS


SQL SQL SQL SQL
SQL SQL

USER---SSMS--------------SQL------------------SQL SERVER-------DB

USER----SQLPLUS---------SQL------------------ORACLE------------DB

USER---MYSQLWORKBENCH-----SQL--------MYSQL----------DB

=> based on operations over db SQL is categorized into following sublangugages

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
1 A 8000 DATA

how to connect to sql server :-


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

=> 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

12-sep-23

creating database in sql server :-


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

=> in object explorer select Database => New Database

Enter Database Name :- DB6PM

=> click OK

=> a db is created with following two files

1 DATA (.MDF) (MASTER DATA FILE)


2 LOG (.LDF) (LOG DATA FILE)

NAME SIZE AUTOGROWTH PATH


DB6PM 8MB 64MB C:--------\
DB6PM_LOG 8MB 64MB C:--------\

download & install :- (sql server)


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

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

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

step by step installation :-


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

https://computingforgeeks.com/
install-sql-server-developer-edition-on-windows-server/?expand_article=1

SSMS :-
-------------

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

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

=> a datatype specifies

1 what type of data allowed in a column


2 amount of memory allocated for column

Datatypes

CHAR Integer Float


Currency DATE

ASCII UNICODE tinyint Numeric(p,s) smallmoney


date
smallint Decimal(p,s) money
time
char nchar int
datetime
varchar nvarchar bigint
varchar(max) nvarchar(max) Numeric(p)

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

=> allows character data upto 8000 chars


=> recommended for fixed length char columns

ex :- NAME CHAR(10)

SACHIN-----
wasted

RAVI------
wasted

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

ex :- gender char(1)

M
F

state_code char(2)

AP
TS
MH

country_code char(3)

IND
USA

varchar(size) :-
---------------------
=> varchar allows character data upto 8000 chars
=> recommended for variable length fields

ex :- NAME VARCHAR(10)

sachin-----
released

varchar(max) :-
---------------------

=> allows character data upto 2GB.

ex :- feedback varchar(max)

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

char/varchar/varchar(max) allows ascii chars (256 chars) that includes a-z,A-Z,0-


9,
special chars.

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

NCHAR/NVARCHAR/NVARCHAR(MAX) :-
----------------------------------------------------------

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

Integer Types :-
---------------------

=> allows numbers with out decimal (integers)

DATATYPE BYTES 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 upto 38 digits

ex :- empid NUMERIC(4)

10
100
1000
10000 => INVALID
AADHARNO NUMERIC(12)

PHONE NUMERIC(10)

ACCNO NUMERIC(11)

13-sep-23

Numeric(p,s) / Decimal(p,s) :-
---------------------------------------

=> allows numbers with decimal (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.507 => allowed => 5000.51


5000.523 => allowed => 5000.52

Currency types :-
-----------------------

=> currency types are used for fields related to money

SMALLMONEY 4 BYTES -214748.3648 to 214748.3647

MONEY 8 BYTES -922337203685477.5808


to

922337203685477.5807

ex :- salary smallmoney
balance money

DATE :-
------------

DATE => allows only date


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-03-10

LOGIN TIME

9:30:00
TXNDT DATETIME

2023-09-13 10:00:00

creating tables in sql server :-


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

CREATE TABLE <tabname>


(
field1 datatype(size),
field2 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 upto 1024 cols
5 no of rows unlimited

123emp invalid
emp 123 invalid
emp*123 invalid
emp_123 valid

ex :-

EMP
EMPID ENAME JOB SAL HIREDATE AGE GENDER

CREATE TABLE EMP


(
EMPID TINYINT ,
ENAME VARCHAR(10),
JOB VARCHAR(10),
SAL SMALLMONEY,
HIREDATE DATE,
AGE TINYINT,
GENDER CHAR(1)
)

=> 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
AGE tinyint 1
GENDER char 1

inserting data into table :-


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

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


=> 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',4000,'2023-09-13',40,'m')


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

inserting multiple rows :-


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

INSERT INTO emp VALUES(102,'kavitha','analyst',9000,'2020-10-05',25,'f'),


(103,'vinod','clerk',5000,'2019-04-
15',30,'m')

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

=> a null means blank or empty and it is not equal to 0 or space


=> nulls can be inserted in two ways

method 1 :- (explicit)
---------------

INSERT INTO emp VALUES(104,'ravi',null,null,'2018-02-12',25,'m')

method 2 :- (implicit)
----------------

INSERT INTO emp(empid,ename,hiredate,age,gender)


VALUES(105,'sindhu',getdate(),30,'f')

remaining two fields job,sal filled with nulls.

Operators in sql server :-


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

Arithmetic Operators => + - * / %


Relational Operators => > >= < <= = <>
Logical Operators => AND OR NOT
Special Operators => BETWEEN
IN
LIKE
IS
ANY
ALL
EXISTS
PIVOT
Set Operators => UNION
UNION ALL
INTERSECT
EXCEPT

Displaying Data :-
-------------------------

=> "select" command is used to display data from table.


=> we can display all rows & all cols
=> we can display specific rows & cols

syn :- SELECT columns / * FROM tabname

SQL = ENGLISH
QUERIES = SENTENCES
CLAUSES = WORDS

=> display all the data from emp table ?

SELECT * FROM EMP

* => all columns

=> display employee names and salaries ?

SELECT ENAME,SAL FROM EMP

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

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

SELECT columns/*
FROM tabname
WHERE condition

condition :-
--------------

COLNAME OP VALUE

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

ex :-

=> display employee details whose empid = 103 ?

SELECT *
FROM EMP
WHERE EMPID = 103

=> display employee details whose name = ravi ?


SELECT *
FROM EMP
WHERE ENAME = 'ravi'

=> display employee details earning more than 5000 ?

SELECT *
FROM EMP
WHERE SAL > 5000

=> employees joined after 2020 ?

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 working as clerk,manager ?

SELECT *
FROM EMP
WHERE JOB='CLERK' OR JOB ='MANAGER'

=> employees whose id = 100,103 ?

SELECT *
FROM EMP
WHERE EMPID=100 OR EMPID=103

=> display male employees age > 30 ?

SELECT *
FROM EMP
WHERE GENDER='M' AND AGE > 30
=> employees joined in 2020 year ?

SELECT *
FROM EMP
WHERE HIREDATE >= '2020-01-01'
AND
HIREDATE <= '2020-12-31'

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

SELECT *
FROM EMP
WHERE SAL>5000
AND
SAL<10000

15-sep-23

=>

STUDENT
SID SNAME S1 S2 S3
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

Testing :-
-------------

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)

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 not working as clerk,manager ?

SELECT * FROM EMP WHERE JOB NOT IN ('CLERK','MANAGER')

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

=> use BETWEEN operator for range comparision

WHERE COLNAME BETWEEN V1 AND V2

=> employees earning between 5000 and 10000 ?

SELECT * FROM EMP WHERE SAL BETWEEN 5000 AND 10000

=> employees not joined in 2020 year ?

SELECT *
FROM EMP
WHERE HIREDATE NOT BETWEEN '2020-01-01' AND '2020-12-31'

Question :-

SELECT *
FROM EMP
WHERE SAL BETWEEN 10000 AND 5000

A ERROR
B RETURNS ROWS
C RETURNS NO ROWS
D NONE

ANS :-

WHERE SAL BETWEEN 5000 AND 10000 (SAL>=5000 AND SAL<=10000)

WHERE SAL BETWEEN 10000 AND 5000 (SAL>=10000 AND SAL<=5000)

NOTE :- use between operator with lower and upper but not with upper and lower

=> employees list working as clerk,manager and earning between 5000 and
10000 and joined in 2023 and gender must be m ?

SELECT *
FROM EMP
WHERE JOB IN ('CLERK','MANAGER')
AND
SAL BETWEEN 5000 AND 10000
AND
HIREDATE BETWEEN '2023-01-01' AND '2023-12-31'
AND
GENDER='M'

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

PRODUCTS
PRODID NAME PRICE CATEGORY BRAND

SELECT *
FROM PRODUCTS
WHERE BRAND IN ('SAMSUNG','REALME')
AND
CATEGORY='MOBILES'
AND
PRICE BETWEEN 10000 AND 20000

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

=> use LIKE operator for pattern comparision

ex :- name starts with 's'


name contains 'a'
emailid ends with '.in'

WHERE COLNAME LIKE 'PATTERN'

=> pattern consists of alphabets,digits,wildcard chars

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

% => 0 or many chars

_ => exactly 1 char

=> employees name starts with 's' ?

SELECT *
FROM EMP
WHERE ENAME LIKE 's%'

=> employees names ends with 'd' ?

SELECT *
FROM EMP
WHERE ENAME LIKE '%d'

16-sep-23

=> employees name contains 'a' ?

SELECT *
FROM EMP
WHERE ENAME LIKE '%a%'
=> employees where 'a' is the 2nd char in their name ?

SELECT *
FROM EMP
WHERE ENAME LIKE '_a%'

=> 'a' is the 3rd char from last ?

SELECT *
FROM EMP
WHERE ENAME LIKE '%a__'

=> name contains 4 chars ?

SELECT *
FROM EMP
WHERE ENAME LIKE '____'

=> name starts with 'a','r','v' ?

SELECT *
FROM EMP
WHERE ENAME LIKE '[arv]%'

=> name starts 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 year ?

SELECT *
FROM EMP
WHERE HIREDATE LIKE '2020%'

=> name contains "_" ?

CUST
CID CNAME
10 sachin_tendulkar
11 virat%kohli
12 mahendra_singh_dhoni

SELECT *
FROM CUST
WHERE CNAME LIKE '%_%'

=> above query returns all customer records because "_" is treated as wildcard
char
but not treated as normal char , to overcome this problem user ESCAPE char

SELECT *
FROM EMP
WHERE CNAME LIKE '%\_%' ESCAPE '\'

=> name contains "%" ?

SELECT *
FROM CUST
WHERE CNAME LIKE '%\%%' ESCAPE '\'

=> name contains 2 "_" ?

SELECT *
FROM CUST
WHERE CNAME LIKE '%\_%\_%' ESCAPE '\'

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

=> use IS operator for NULL comparision

WHERE COLNAME IS NULL


WHERE COLNAME IS NOT NULL

=> employees not earning salary ?

SELECT * FROM EMP WHERE SAL IS NULL

=> who are earning salary ?

SELECT * FROM EMP WHERE SAL IS NOT NULL

summary :-

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


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

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

=> alias means another name


=> used to change column heading

COLNAME / EXPRESSION [AS] ALIAS

=> display employee names and annual salaries ?

SELECT ENAME,SAL*12 AS ANNSAL


FROM EMP

SELECT ENAME,SAL*12 AS [ANNUAL SAL]


FROM EMP

=> employees whose annual sal > 60000 ?

SELECT *,SAL*12 AS ANNSAL


FROM EMP
WHERE SAL*12 > 60000
=> display ENAME SAL HRA DA TAX TOTSAL ?

HRA = house rent allowance = 20% on sal


DA = dearness allowance = 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

19-sep-23

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

=> order by clause is used to sort data based on one or more columns
either in ascending or in descending order.

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

=> default order is ascending

ex :-

=> arrange employee list name wise asc ?

SELECT *
FROM EMP
ORDER BY ENAME ASC

=> arrange employee list sal wise desc order ?

SELECT *
FROM EMP
ORDER BY SAL DESC

=> arrange employee list hiredate wise asc ?

SELECT *
FROM EMP
ORDER BY HIREDATE ASC

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

SELECT EMPNO,ENAME,SAL,DEPTNO
FROM EMP
ORDER BY DEPTNO ASC,SAL DESC

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

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

SELECT EMPNO,ENAME,HIREDATE,DEPTNO
FROM EMP
ORDER BY DEPTNO ASC,HIREDATE 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 80 70
4 D 90 70 80

SELECT * , (M+P+C)/3 AS AVG


FROM STUDENT
ORDER BY (M+P+C)/3 DESC,M DESC, P DESC

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

=> display employee names and annual salaries and arrange list annual sal
wise desc order ?

SELECT ename,sal*12 as annsal


FROM emp
WHERE annsal > 30000 => INVALID
ORDER BY annsal DESC => VALID

order of execution :-
--------------------------

FROM
WHERE
SELECT
ORDER BY

1 alias cannot be used in where clause because where clause is executed


before select

2 alias can be used in order by clause because order by clause is executed


after select.

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

=> distinct clause eliminates duplicates from the select stmt output

DISTINCT colname
DISTINCT col1,col2,--
DISTINCT *

ex :-

SELECT DISTINCT JOB FROM EMP

ANALYST
CLERK
MANAGER
PRESIDENT
SALESMAN

SELECT DISTINCT DEPTNO FROM EMP

10
20
30

SELECT DISTINCT DEPTNO,JOB FROM EMP


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

10 CLERK
10 MANAGER
10 PRESIDENT
20 ANALYST
20 CLERK
20 MANAGER
30 CLERK
30 MANAGER
30 SALESMAN

20-SEP-23

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

=> TOP clause is used to display Top N rows

SELECT TOP <n> *


FROM tabname
WHERE cond
ORDER BY col

ex :-

=> display first 3 rows from emp table ?

SELECT TOP 3 * FROM EMP

=> display top 3 highest paid employees ?

SELECT TOP 3 *
FROM EMP
ORDER BY SAL DESC

=> display top 3 employees based on experience ?

SELECT TOP 3 *
FROM EMP
ORDER BY HIREDATE ASC

=> display top 3 max salaries ?

SELECT DISTINCT TOP 3 SAL


FROM EMP
ORDER BY SAL DESC

summary :-

WHERE => to select specific rows


ORDER BY => to sort data
DISTINCT => to eliminate duplicates
TOP => to select top N rows

DML commands :- (Data Manipulation Lang)


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

INSERT
UPDATE
DELETE
MERGE

=> all DML commands acts on table data.


=> all DML operations are auto committed.
=> 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 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 = NULL

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

UPDATE EMP SET COMM = NULL WHERE COMM IS NOT NULL

NULL comparision IS
NULL assignment =
=> update sal with 2000 and comm with 800 whose empno = 7369 ?

UPDATE EMP
SET SAL = 2000 , COMM = 800
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*1.2 , COMM = COMM *1.1
WHERE JOB='SALESMAN'
AND
HIREDATE LIKE '1981%'

=> transfer all employees from 10th dept to 20th dept ?

UPDATE EMP SET DEPTNO = 20 WHERE DEPTNO = 10

=> increase samsung,redmi,realme mobile phones price by 10% ?

PRODUCTS
prodid pname price category brand

UPDATE PRODUCTS
SET PRICE = PRICE*1.1
WHERE CATEGORY='mobiles'
AND
BRAND IN ('samsung','redmi','realme')

DELETE command :-
----------------------------

=> command used to delete row/rows from table

DELETE FROM <tabname> [WHERE cond]

ex :-

=> delete all rows from emp ?

DELETE FROM EMP

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

DELETE
FROM EMP
WHERE HIREDATE BETWEEN '1981-04-01' AND '1981-06-30'

21-sep-23

DDL commands :- (Data Definition Lang)


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

CREATE
ALTER
DROP
TRUNCATE
=> DDL commands acts on table structure.

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

=> command used to modify table structure


=> using ALTER we can

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

Adding columns :-
------------------------

=> 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 column :-
-----------------------

=> drop column gender ?

ALTER TABLE EMP


DROP COLUMN GENDER

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

=> change the datatype of column empno to int ?

ALTER TABLE EMP


ALTER COLUMN EMPNO INT

=> increase the size of ename to 20 ?

ALTER TABLE EMP


ALTER COLUMN ENAME VARCHAR(20)

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

=> command drops table from db.


=> drops table structure along with data.

syn :- DROP TABLE <tabname>

ex :- DROP TABLE EMP


TRUNCATE :-
-------------------

=> deletes all the data from table but keeps structure.
=> will empty the table.
=> releases memory allocated for table.

syn :- TRUNCATE TABLE <tabname>

ex :- TRUNCATE TABLE emp

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

DELETE TRUNCATE

1 DML DDL

2 can delete specific row/rows cannot delete


specific row
can delete only all rows

3 where cond can be used with where cond cannot be


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

SP_RENAME :-
---------------------

=> used to change table name / column name

SP_RENAME ' old name ' , ' new name'

=> rename table emp to employees ?

SP_RENAME 'EMP','EMPLOYEES'

=> rename column COMM to BONUS ?

SP_RENAME 'EMPLOYEES.COMM','BONUS'

=> list of tables created by user ?

SELECT * FROM INFORMATION_SCHEMA.TABLES

Built-in Functions in SQL SERVER :-


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

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

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

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

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

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

=> function returns today's date

SELECT GETDATE() => 2023-09-21 19:15:59.130

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

=> used to get part of the date

DATEPART(interval,date)

ex :-

SELECT DATEPART(yy,GETDATE()) => 2023


mm => 09
dd => 21
dy => 264 (day of the year)
dw => 5 (day of the week)
hh => hour
mi => minutes
ss => seconds
qq => quarter (1-4)

jan-mar 1
apr-jun 2

jul-sep 3

oct-dec 4

=> display ENAME , SAL , year of join ?

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

22-sep-23

=> display employees joined in 1980,1983,1985 ?

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

=> employees joined in leap year ?


SELECT *
FROM EMP
WHERE DATEPART(yy,hiredate)%4=0

=> employees joined in jan,apr,dec months ?

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

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

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

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

=> used to extract date intervals

MM DW

DATEPART 09 6

DATENAME September Friday

=> employees joined on sunday ?

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

=> display ENAME DAY OF THE WEEK ?

SELECT ENAME,DATENAME(DW,HIREDATE) AS DAY


FROM EMP

=> write a query to display on which day india got independence ?

SELECT DATENAME(DW,'1947-08-15')

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

=> used to display date in different formats

FORMAT(date,'format')

SELECT FORMAT(getdate(),'dd.MM.yyyy') => 22.09.2023


SELECT FORMAT(GETDATE(),'HH:mm:ss') => 18:51:20
SELECT FORMAT(GETDATE(),'hh:mm:ss') => 6:51:23
=> display ENAME HIREDATE ? display hiredate in MM/DD/YYYY format ?

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


FROM EMP

scenario :-

INSERT INTO EMP(EMPNO,ENAME,SAL,HIREDATE)


VALUES(999,'ABC',5000,GETDATE())

=> list of employees joined today ?

SELECT *
FROM EMP
WHERE HIREDATE = GETDATE() => NO ROWS

2023-09-22 = 2023-09-22 18:58:33.133

SELECT *
FROM EMP
WHERE HIREDATE = FORMAT(GETDATE(),'yyyy-MM-dd')

2023-09-22 = 2023-09-22

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

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

DATEADD(interval,int,date)

SELECT DATEADD(YY,1,GETDATE()) => 2024-09-22 19:06:01.383


SELECT DATEADD(MM,2,GETDATE()) => 2023-11-22
SELECT DATEADD(DD,-10,GETDATE()) => 2023-09-12

EX :-

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

2023-09-22 ?

=> display today's gold rate ?


=> display yesterday's gold rate ?
=> display last month same day gold rate ?
=> display last year same day gold rate ?

1 SELECT *
FROM GOLD_RATES
WHERE DATEID = FORMAT(GETDATE(),'yyyy-MM-dd')

2 SELECT *
FROM GOLD_RATES
WHERE DATEID = FORMAT(DATEADD(DD,-1,GETDATE()),'yyyy-MM-dd')

3 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 last 1 month gold rates ?

SELECT *
FROM GOLD_RATES
WHERE DATEID BETWEEN FORMAT(DATEADD(MM,-1,GETDATE()),'yyyy-MM-dd')
AND
FORMAT(GETDATE(),'yyyy-MM-dd')

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

=> used to calculate difference between two dates in given interval

DATEDIFF(interval,start date,end date)

SELECT DATEDIFF(yy,'2022-09-22',getdate()) => 1


SELECT DATEDIFF(mm,'2022-09-22',getdate()) => 12

=> display ENAME EXPERIENCE in years ?

SELECT ENAME,DATEDIFF(YY,HIREDATE,GETDATE()) AS EXPERIENCE


FROM EMP

23-SEP-23

=> display ENAME EXPERIENCE ?


M YEARS N MONTHS

experience = 40 months = 3 YEARS 4 MONTHS

YEARS = months/12 = 40/12 = 3

MONTHS = months%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)

SELECT EOMONTH(GETDATE(),0) => 2023-09-30


SELECT EOMONTH(GETDATE(),1) => 2023-10-31
SELECT EOMONTH(GETDATE(),-1) => 2023-08-31

=> display next month first day ?


=> display current month first day ?
=> display next year first day ?
=> display current year first day ?

STRING functions :-
----------------------------

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

=> converts string to uppercase

UPPER(arg)

SELECT UPPER('hello') => HELLO

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

=> converts string to lowercase

LOWER(arg)

SELECT LOWER('HELLO') => hello

=> display ENAME SAL ? display names in lowercase ?

SELECT LOWER(ENAME) AS ENAME,SAL FROM EMP

=> convert names to lowercase in table ?

UPDATE EMP SET ENAME = LOWER(ENAME)

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

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

LEN(arg)

1 SELECT ENAME,LEN(ENAME) AS LEN FROM EMP

2 display employees name contains 4 chars ?

SELECT *
FROM EMP
WHERE ENAME LIKE '____'

WHERE LEN(ENAME) = 4

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

=> returns chars starting from left side

LEFT(STRING,NO OF CHARS)

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

RIGHT() :-
----------------
=> returns chars starting from right side

RIGHT(STRING,NO OF CHARS)

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

=> employees name starts with 's' ?

SELECT * FROM EMP WHERE LEFT(ENAME,1)='s'

=> name ends with 's' ?

SELECT * FROM EMP WHERE RIGHT(ENAME,1)='s'

=> name starts and ends with same char ?

SELECT * FROM EMP WHERE LEFT(ENAME,1) = RIGHT(ENAME,1)

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

=> generate emailids for the employees ?

empno ename emailid


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

'a' + 'b' => ab

'a' + ' ' + 'b' => a b

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(30)

STEP 2 :- update column with emailids

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

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

=> used to extract part of the string starting from specific position

SUBSTRING(string,start,length)

ex :-

SELECT SUBSTRING('HELLO WELCOME',7,4) => WELC


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

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

=> repeats given char for given no of times

REPLICATE(char,length)

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

=> display ENAME SAL ?


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

SELECT ENAME,REPLICATE('*',LEN(SAL)) AS SAL FROM EMP

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

ACCOUNTS
ACCNO
12345678967

your a/c no XXXX8967 debited --------

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

25-SEP-23

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

=> used to replace one string with another string

REPLACE(str1,str2.str3)

=> in str1 , str2 replaced with str3

ex :-

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


SELECT REPLACE('hello','l','abc') => heabcabco
SELECT REPLACE('hello','elo','abc') => hello
SELECT REPLACE('@@he@@ll@@o@@','@','') => hello

=> display employees name contains exactly 1 'a' ?

SELECT *
FROM EMP
WHERE LEN(ENAME) - LEN(REPLACE(ENAME,'A','')) = 1

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

=> used to translate one char to another char

TRANSLATE(str1,str2,str3)
ex :-

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

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

NOTE :-

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

ex :-

SELECT ENAME,
TRANSLATE(SAL,'0123456789.','$bT*h@U%#^&') AS SAL
FROM EMP

JONES 2975.00 T^%@&$$

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

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

--------------------------------------------------------------------
**he**ll**o**

O/P :- hello

STUFF() :-
-------------

=> used to replace one string with another string


=> it is based on start and length

STUFF(str1,start,length,str2)

ex :-

SELECT STUFF('hello welcome',10,3,'abc') => hello welabce

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

=> returns position of a char in a string

CHARINDEX(char,string,[start])

SELECT CHARINDEX('o','hello welcome') => 5


SELECT CHARINDEX('x','hello welcome') => 0
SELECT CHARINDEX('o','hello welcome',6) => 11
SELECT CHARINDEX('e','hello welcome',10) => 13

scenario :-
CUST
CID CNAME
10 SACHIN TENDULKAR
11 VIRAT KOHLI

=> display CID FNAME LNAME ?

SELECT CID,
SUBSTRING(CNAME,1,CHARINDEX(' ',CNAME)-1) AS FNAME,
SUBSTRING(CNAME,CHARINDEX(' ',CNAME)+1,LEN(CNAME)) AS LNAME
FROM CUST

SUBSTRING(STRING,START,LENGTH)

Assignment :-

CUST
CID CNAME
10 SACHIN RAMESH TENDULKAR
11 MAHENDRA SINGH DHONI

=> display CID FNAME MNAME LNAME ?

26-sep-23

Numeric functions :-
--------------------------

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

ROUND
CEILING
FLOOR

ROUND() :-
---------------

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

ROUND(number,decimal places)

ex :-

ROUND(38.5678,0) =>

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

number >= avg => rounded to highest


number < avg => rounded to lowest

ROUND(38.3647,0) => 38

ROUND(38.5638,2) => 38.56

ROUND(38.5678,2) => 38.57

ROUND(38.5678,1) => 38.6


ROUND(386,-2) => 400

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

ROUND(386,-1) => 390

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

ROUND(386,-3) => 0

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

=> round all the employee salaries to hundred ?

update emp set sal = round(sal,-2)

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

=> rounds number always to highest

CEILING(number)

SELECT CEILING(3.1) => 4

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

=> rounds number always to lowest

FLOOR(number)

SELECT FLOOR(3.9) => 3

conversion functions :-
-----------------------------

1 CAST
2 CONVERT

=> both functions are used to convert one datatype to another datatype

CAST() :-
------------

CAST(source-value as target-type)

SELECT CAST(10.5 AS INT) => 10

=> display smith earns 800 ?


allen earns 1600

string concatenation => +

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


FROM EMP

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


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

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

CONVERT(TARGET-TYPE, SOURCE-VALUE)

SELECT CONVERT(INT,10.5) => 10

=> difference between cast & convert ?

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

Date styles :-
-----------------

CONVERT(VARCHAR,DATE,STYLE-NUMBER)

SELECT CONVERT(VARCHAR,GETDATE(),101) => 09/26/2023

106 => 26 Sep 2023

114 => 19:06:44:713

SELECT ENAME,CONVERT(VARCHAR,HIREDATE,105) AS HIREDATE


FROM EMP

Money Styles :-
---------------------

CONVERT(VARCHAR,MONEY,STYLE-NUMBER)

0 => 2 digits after decimal


1 => thousand seperator
2 => 4 digits after decimal

=> 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

SELECT ISNULL(100,200) => 100


SELECT ISNULL(NULL,200) => 200

=> display ENAME SAL COMM TOTSAL ?

TOTSAL = SAL + COMM

SELECT ENAME,SAL,COMM,SAL+ISNULL(COMM,0) AS TOTSAL


FROM EMP

WARD 1300.00 500.00 1800.00


JONES 3000.00 NULL 3000.00

27-sep-23

=> display ENAME SAL COMM ? if comm = null display N/A ?

SELECT ENAME,SAL, ISNULL(CAST(COMM AS VARCHAR),'N/A') AS COMM


FROM EMP

Analytical Functions :-
------------------------------

RANK & DENSE_RANK :-


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

=> both functions are used to find ranks


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

RANK() OVER (ORDER BY COLNAME ASC/DESC ,------)

=> find the ranks of the employees based on sal and highest paid employee
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 gaps.

2 in rank function ranks are not 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

=> find ranks of the employees based on sal , if salaries are same then
ranking should be based on hiredate ?

SELECT empno,ename,hiredate,sal,
dense_rank() over (ORDER BY sal DESC,hiredate ASC)
FROM emp

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

=> use partition by clause to find ranks with in group , for ex to find
ranks with dept first divide the table dept wise and apply rank/dense_rank
functions on each dept instead of applying it on whole table.

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

10 5000 1
2450 2
1300 3

20 3000 1
3000 1
2975 2
2000 3
1100 4

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

=> returns record numbers


=> it is also based on some column
=> data must be sorted

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

SELECT EMPNO,ENAME,SAL,
ROW_NUMBER() OVER (ORDER BY EMPNO ASC) AS RNO
FROM EMP

SAL RNK DRNK RNO


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

28-sep-23

LAG & LEAD :-


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

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


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

SELECT EMPNO,ENAME,SAL,
LAG(SAL,1) OVER (ORDER BY EMPNO ASC) AS PREV_SAL
FROM EMP

7369 smith 2000.00 NULL


7499 allen 1600.00 2000.00
7521 ward 1250.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

7369 VIJAY 1980-12-17 NULL


7499 ALLEN 1981-02-20 65

Aggregate Functions / Group Functions :-


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

=> these functions process group of rows and returns one value

MAX
MIN
SUM
AVG
COUNT
COUNT(*)

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

=> returns maximum value

MAX(arg)

SELECT MAX(SAL) FROM EMP => 5000


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

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

=> returns minimum value

MIN(arg)

SELECT MIN(SAL) FROM EMP => 800


SELECT MIN(HIREDATE) FROM EMP =>1980-12-17

SUM() :-
------------
=> returns total

SELECT SUM(SAL) FROM EMP => 29300.00

=> round the total sal to thousands ?

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

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

=> after rounding display total sal with thousand seperator ?

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


FROM EMP

o/p :- 29,000.00

=> calculate total sal including comm ?

SELECT SUM(SAL+COMM) FROM EMP

SAL COMM SAL+COMM


5000 NULL NULL
4000 500 4500
3000 NULL NULL

SUM(SAL) => 12000


SUM(SAL+COMM) => 4500

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

SAL COMM SAL+ISNULL(COMM,0)


5000 NULL 5000
4000 500 4500
3000 NULL 3000

SUM(SAL) => 12000


SUM(SAL+ISNULL(COMM,0)) => 12500

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

=> returns average value

SELECT AVG(SAL) FROM EMP => 2092.8571

=> round avg sal to lowest integer ?

SELECT FLOOR(AVG(SAL)) FROM EMP => 2092

NOTE :- sum,avg cannot be applied on date,char columns

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

=> counts no of values in a column

SELECT COUNT(EMPNO) FROM EMP => 14


SELECT COUNT(COMM) FROM EMP => 4 => nulls are not counted

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

=> counts no of rows in a table

SELECT COUNT(*) FROM EMP => 14

diff b/w count & count(*) ?

count doesn't include nulls


count(*) includes nulls

T1
F1
10
NULL
20
NULL
30

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

=> how many employees joined in 1981 year ?

SELECT COUNT(*) FROM EMP WHERE HIREDATE LIKE '1981%'

=> how many employees joined on sunday ?

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

NOTE :-

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

SELECT ENAME
FROM EMP
WHERE SAL = MAX(SAL) => ERROR

SELECT DEPTNO
FROM EMP
WHERE COUNT(*) = 3 => ERROR

NOTE :- to overcome this problem use subqueries

date :- datepart,datename,dateadd,datediff,eomonth,format
char :-
upper,lower,len,left,right,substring,replicate,replace,translate,charindex
numeric :- round,ceiling,floor
conversion :- cast,convert
special :- isnull
analytical :- rank,dense_rank,row_number,lag,lead
aggregate :- max,min,sum,avg,count,count(*)
========================================================================

29-SEP-23

CASE STATEMENT :-
-------------------------------

=> it is similar to switch case


=> used to implement IF-ELSE in sql queries
=> using case we can return values based on conditions
=> 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

=> display ENAME JOB ?

IF JOB=CLERK DISPLAY WORKER


MANAGER BOSS
PRESIDENT BIG BOSS
ELSE EMPLOYEE

SELECT ENAME,
CASE JOB
WHEN 'CLERK' THEN 'WORKER'
WHEN 'MANAGER' THEN 'BOSS'
WHEN 'PRESIDENT' THEN 'BIG BOSS'
ELSE 'EMPLOYEE'
END AS JOB
FROM EMP

=> increment employee salaries as follows ?

if deptno = 10 incr sal by 10%


20 15%
30 20%
others 5%

UPDATE EMP
SET SAL = CASE DEPTNO
WHEN 10 THEN SAL+(SAL*0.1)
WHEN 20 THEN SAL+(SAL*0.15)
WHEN 30 THEN SAL+(SAL*0.2)
ELSE SAL+(SAL*0.05)
END

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

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

CASE
WHEN cond1 THEN return expr1
WHEN cond2 THEN return expr2
-------------------
ELSE return expr
END

=> 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

=>

T1
AMT
1000
-2000
3000
-500
-2000

output :-

AMT TRANS
1000 CREDIT
-2000 DEBIT

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

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

EMP
EMPNO ENAME SAL DEPTNO
1 A 3000 10
2 B 4000 20 GROUP BY 10 7000
3 C 2000 30 ===========> 20 9000
4 D 5000 20 30 2000
5 E 4000 10
detailed data summarized data

=> GROUP BY clause converts detailed data into summrized data


which is useful for analysis.

syn :-

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

02-OCT-23

=> display dept wise total salary ?

SELECT DEPTNO,SUM(SAL) AS TOTSAL


FROM EMP
GROUP BY DEPTNO

10 9680.00
20 12535.00
30 11520.00

FROM EMP :-
-------------------

EMPNO ENAME SAL DEPTNO


1 A 3000 10
2 B 4000 20
3 C 2000 30
4 D 5000 20
5 E 4000 10

GROUP BY DEPTNO :-
--------------------------------

10 1 A 3000 10
5 E 4000 10

20 2 B 4000 20
4 D 5000 20

30 3 C 2000 30

SELECT DEPTNO,SUM(SAL) AS TOTSAL :-


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

10 7000
20 9000
30 2000

=> display job wise no of employees ?

SELECT JOB,COUNT(*) AS CNT


FROM EMP
GROUP BY JOB

ANALYST 2
CLERK 4
MANAGER 3
PRESIDENT 1
SALESMAN 4

=> 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

=> 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 joined in 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)

=> display departments 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 before group by conditions applied after group by

3 use where clause if cond use having clause


if cond
doesn't contain aggregate contains aggregate
function
function

=> display dept wise no of employees where deptno = 10,20 and no of employees >
3 ?

SELECT DEPTNO,COUNT(*) AS CNT


FROM EMP
WHERE DEPTNO IN (10,20)
GROUP BY DEPTNO
HAVING COUNT(*) > 3

20 5

=> find southern states having more than 5cr population ?

PERSONS
AADHRNO NAME GENDER AGE ADDR CITY STATE

SELECT STATE,COUNT(*)
FROM PERSONS
WHERE STATE IN ('AP','TS','KA','KL','TN')
GROUP BY STATE
HAVING COUNT(*) > 50000000

Range grouping :-
--------------------------

SELECT CASE
WHEN SAL BETWEEN 0 AND 2000 THEN '0-2000'
WHEN SAL BETWEEN 2001 AND 4000 THEN '2001-4000'
WHEN SAL>4000 THEN 'ABOVE 4000'
END AS SALRANGE, COUNT(*) AS CNT
FROM EMP
GROUP BY CASE
WHEN SAL BETWEEN 0 AND 2000 THEN '0-2000'
WHEN SAL BETWEEN 2001 AND 4000 THEN '2001-4000'
WHEN SAL>4000 THEN 'ABOVE 4000'
END

03-OCT-23

=> display dept wise and with in dept job wise total salary ?
SELECT DEPTNO,JOB,SUM(SAL) AS TOTSAL
FROM EMP
GROUP BY DEPTNO,JOB
ORDER BY DEPTNO ASC

10 CLERK 1430
MANAGER 2750
PRESIDENT 5500

20 ANALYST 6900
CLERK 2185
MANAGER 3450

30 CLERK 1200
MANAGER 3840
SALESMAN 6840

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

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 YEAR ASC

1980 1 ?
2 ?
3 ?
4 ?

1981 1 ?
2 ?
3 ?

ROLLUP & CUBE :-


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

=> both functions are used to display subtotals and grand total

GROUP BY ROLLUP(col1,col2,--)
GROUP BY CUBE(col1,col2,-----)

ROLLUP :-
--------------

=> ROLLUP displays subtotals for each group and also displays grand total

SELECT DEPTNO,JOB,SUM(SAL) AS TOTSAL


FROM EMP
GROUP BY ROLLUP(DEPTNO,JOB)
ORDER BY DEPTNO ASC ,JOB ASC

NULL NULL 33735.00 => grand total


10 NULL 9680.00 => dept subtotal
10 CLERK 1430.00
10 MANAGER 2750.00
10 PRESIDENT 5500.00
20 NULL 12535.00 => dept subtotal
20 ANALYST 6900.00
20 CLERK 2185.00
20 MANAGER 3450.00
30 NULL 11520.00 => dept subtotal
30 CLERK 1200.00
30 MANAGER 3480.00
30 SALESMAN 6840.00

CUBE :-
-----------

=> CUBE displays subtotals for each group by column (deptno,job) and also
displays grand total.

SELECT DEPTNO,JOB,SUM(SAL) AS TOTSAL


FROM EMP
GROUP BY CUBE(DEPTNO,JOB)
ORDER BY DEPTNO ASC ,JOB ASC

NULL NULL 33735.00 => grand total


NULL ANALYST 6900.00 => job subtotal
NULL CLERK 4815.00 => job subtotal
NULL MANAGER 9680.00
NULL PRESIDENT 5500.00
NULL SALESMAN 6840.00
10 NULL 9680.00 => dept subtotal
10 CLERK 1430.00
10 MANAGER 2750.00
10 PRESIDENT 5500.00
20 NULL 12535.00
20 ANALYST 6900.00
20 CLERK 2185.00
20 MANAGER 3450.00
30 NULL 11520.00
30 CLERK 1200.00
30 MANAGER 3480.00
30 SALESMAN 6840.00

GROUPING_ID() :-
--------------------------

=> this functions accepts group by columns and returns subtotal belongs to
which group by column

ex :- GROUPING_ID(DEPTNO,JOB) =>

1 => subtotal belongs to 1st group by column i.e. deptno


2 => subtotal belongs to 2nd group by column i.e. job
3 => grand total

SELECT DEPTNO,JOB,SUM(SAL) AS TOTSAL,


CASE GROUPING_ID(DEPTNO,JOB)
WHEN 1 THEN 'Dept subtotal'
WHEN 2 THEN 'Job subtotal'
WHEN 3 THEN 'Grand total'
END AS SUBTOTALS
FROM EMP
GROUP BY CUBE(DEPTNO,JOB)
ORDER BY DEPTNO ASC ,JOB ASC

Assignment :-
-------------------

PERSONS
AADHRNO NAME GENDER AGE ADDR CITY STATE

=> display state wise and with in stage gender wise population and also
display state wise and gender wise subtotals ?

2 SALES
DATEID PRODID CUSTID QTY AMT
2018-01-01 100 10 1 2000

=> display year wise and with in year quarter wise total amount
and also display year wise subtotals ?

NOTE :-

SELECT DATEPART(YY,HIREDATE) AS YEAR,COUNT(*) AS CNT


FROM EMP
GROUP BY YEAR /* invalid */
ORDER BY YEAR ASC /* valid */

=> column alias cannot be used in group by 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.

SELECT DEPTNO,ENAME,COUNT(*) AS CNT


FROM EMP
GROUP BY DEPTNO => ERROR

in select only group by columns and aggregate functions should appear


other than these columns if any column appears then returns error.

summary :-

importance of group by
writing queries using group by
where vs having
displaying subtotals & grand total
rollup & cube
grouping_id

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

04-oct-23 Integrity Constraints


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

=> Integrity Constraints are rules to maintain Data Quality or Data Consistency.
=> used to prevent users from entering invalid data.
=> used to enforce rules like min bal must be 1000.

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

=> constraints can be declared in two ways

1 column level
2 table level

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

=> if constraints are declared immediately after declaring column is called


column level.

CREATE TABLE <tabname>


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

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

=> NOT NULL constraint doesn't accept null values


=> a field declared with not null is called mandatory field

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

ex :-

CREATE TABLE cust


(
custid INT ,
cname VARCHAR(10) NOT NULL,
emailid VARCHAR(20) UNIQUE
)

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


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

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

=> primary key doesn't accept duplicates and nulls.


=> it is the combination of unique & not null

primary key = unique + not null

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

ex :-

CREATE TABLE emp13


(
empid INT PRIMARY KEY,
ename VARCHAR(10) NOT NULL
)

INSERT INTO emp13 VALUES(100,'A')


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

=> only one primary key is allowed per table , if we want multiple primary keys
then declare one column with primary key and other columns with
unique not null.

CREATE TABLE CUST


(
CUSTID INT PRIMARY KEY,
CNAME VARCHAR(10) NOT NULL,
AADHARNO NUMERIC(12) UNIQUE NOT NULL,
PANNO CHAR(10) UNIQUE NOT NULL
)

=> difference between unique & primary key ?

unique primary key

1 allows one null doesn't allow nulls

2 multiple columns only one column can


can be declared be declared with primary
key
with unique

3 non clustered index clustered index created


is created on unique on primary key

candidate key :-
---------------------

=> a field eligible for primary key is called candidate key


ex :- VEHICLES
VEHNO NAME MODEL COST CHASSISNO

candidate keys :- VEHNO,CHASSISNO


primary key :- VEHNO
secondary key :- CHASSISNO
or
alternate key

=> while creating table secondary key columns are declared with unique not null.

CHECK :-
------------

=> use check constraint when rule based on condition.

syn :- CHECK(condition)

ex 1 :- sal must be min 3000

CREATE TABLE emp15


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

insert into emp15 values(100,'A',1000) => error


insert into emp15 values(101,'B',5000)
insert into emp15 values(102,'C',NULL)

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 must be min 6 chars

pwd varchar(10) CHECK(LEN(pwd) >= 6)

ex 5 :- emailid must contain '@'


emailid 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'
))
Assignment :-

pwd must contain lowercase alphabets


must contain uppercase alphabets
must contain digits
must contain _ or @ or $

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

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

EMP
EMPNO ENAME SAL DNO DNAME LOC
1 A 3000 10 HR BLR
2 10 HR BLR
3 10 HR BLR

=> above table contains redundency , to reduce redundency divide the


table into two tables and establish relationship relationship by
adding foreign key.

=> to establish relationship take primary key of one table and add it to
another table as foreign key and declare with references constraint.

DEPT
DNO DNAME LOC
10 HR BLR
20 IT HYD

EMP
EMPNO ENAME SAL DNO REFERENCES DEPT(DNO)
1 A 4000 10
2 B 3000 20
3 C 5000 90 => INVALID
4 D 3000 10
5 E 2000 NULL

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

=> fk allows duplicates & nulls.

=> after declaring foreign key a relationship is created between two tables
called parent/child relationship

=> primary key table is parent and fk table is child

CREATE TABLE DEPT55


(
DNO INT PRIMARY KEY,
DNAME VARCHAR(10) UNIQUE NOT NULL
)

INSERT INTO DEPT55 VALUES(10,'HR'),(20,'IT')

CREATE TABLE EMP55


(
EMPNO INT PRIMARY KEY,
ENAME VARCHAR(10) NOT NULL,
SAL MONEY CHECK(SAL>=3000) ,
DNO INT REFERENCES DEPT55(DNO)
)

INSERT INTO EMP55 VALUES(1,'A',4000,10)


INSERT INTO EMP55 VALUES(2,'B',3000,90) => ERROR
INSERT INTO EMP55 VALUES(3,'C',3000,10)
INSERT INTO EMP55 VALUES(4,'D',5000,NULL)

Relationship Types :-
-----------------------------

1 one to one
2 one to many
3 many to one
4 many to many

=> default relationship in sql server is one to many

one to one relationship :-


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

=> to establish one to one relationship declare foreign key with unique constraint

ex :-

DEPT
DNO DNAME
10 HR
20 IT

MGR
MGRNO MNAME DNO REFERENCES DEPT(DNO) UNIQUE
1 A 10
2 B 20

many to many relationship :-


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

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

ex :-

CUST PRODUCTS
CID NAME ADDR PRODID PNAME PRICE
1 A HYD 100 A 500
2 B BLR 101 B 200

SALES
CID PRODID QTY
1 100 1
1 101 2
2 100 1
2 101 3

06-oct-23
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

CREATE TABLE emp16


(
empno INT PRIMARY KEY,
ename VARCHAR(10) NOT NULL,
hiredate DATE DEFAULT GETDATE()
)

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


INSERT INTO emp16 VALUES(101,'B','2023-01-01')
INSERT INTO emp16 VALUES(102,'C',NULL)

SELECT * FROM EMP16

EMPNO ENAME HIREDATE


100 A 2023-10-06
101 B 2023-01-01
102 C NULL

TABLE LEVEL :-
----------------------

=> use table level to declare constraints for multiple or combination of columns.
=> table level constraints are declared after declaring all columns

Declaring check constraint at table level :-


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

PRODUCTS
prodid pname price mfd_dt exp_dt
100 A 100 2023-10-01 2023-01-01 INVALID

Rule :- exp_dt > mfd_dt

create table products


(
prodid int primary key,
pname varchar(10) not null,
mfd_dt date ,
exp_dt date ,
CHECK(exp_dt > mfd_dt)
)

insert into products


values(100,'A', getdate() , '2023-01-01') => ERROR

insert into products


values(101,'B','2023-01-01',getdate()) => 1 row affected

composite primary key :-


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

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


primary key.

=> in some tables we need combination of columns to uniquely identify records


and that combination declared primary key at table level.

ex :-

STUDENT COURSE
SID SNAME CID CNAME
------ ------
1 A 10 .NET
2 B 11 SQL

REGISTRATIONS
SID CID DOR FEE
----------------
1 10 ? ?
1 11 ? ?
2 10 ? ?

CREATE TABLE STUDENT


(
SID INT PRIMARY KEY,
SNAME VARCHAR(10) NOT NULL
)

INSERT INTO STUDENT VALUES(1,'A'),(2,'B')

CREATE TABLE COURSE


(
CID INT PRIMARY KEY,
CNAME VARCHAR(10) NOT NULL
)

INSERT INTO COURSE VALUES(10,'.NET') , (11,'SQL')

CREATE TABLE REGISTRATIONS


(
SID INT REFERENCES STUDENT(SID) ,
CID INT REFERENCES COURSE(CID) ,
DOR DATE,
FEE MONEY ,
PRIMARY KEY(SID,CID)
)

INSERT INTO REGISTRATIONS VALUES(1,10,GETDATE(),1000)


INSERT INTO REGISTRATIONS VALUES(1,11,GETDATE(),1000)
INSERT INTO REGISTRATIONS VALUES(2,10,GETDATE(),1000)
INSERT INTO REGISTRATIONS VALUES(1,10,GETDATE(),1000) => ERROR

Question :-
----------------

SALES
DATEID PRODID CUSTID QTY AMT
2023-10-05 100 10 1 1000
2023-10-05 100 11 1 1000
2023-10-05 101 10 1 2000
2023-10-06 100 10 1 1000

=> identify primary key and write create table script ?

composite foreign key :-


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

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


foreign key
=> a composite foreign key refers composite primary key

ex :-

REGISTRATIONS
SID CID DOR FEE
----------------
1 10 ? ?
1 11 ? ?
2 10 ? ?

CERTIFICATES
CERTNO DOI SID CID
1000 ? 1 10
1001 ? 1 11
1002 ? 2 11

=> in the above table SID,CID combination should match with registrations table
SID,CID combination

CREATE TABLE CERTIFICATES


(
CERTNO INT PRIMARY KEY,
DOI DATE,
SID INT,
CID INT ,
FOREIGN KEY(SID,CID) REFERENCES REGISTRATIONS(SID,CID)
)

INSERT INTO CERTIFICDATES VALUES(1000,GETDATE(),2,11) => ERROR

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

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

ANS :- C

07-oct-23

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 tabled 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 NUMERIC(2) PRIMARY KEY,
item_no NUMERIC(3) PRIMARY KEY,
ord_date DATE NOT NULL);

B. CREATE TABLE ord_details


(ord_no NUMERIC(2) UNIQUE, NOT NULL,
item_no NUMERIC(3),
ord_date DATE DEFAULT GETDATE() NOT NULL);

C. CREATE TABLE ord_details


(ord_no NUMERIC(2) ,
item_no NUMERIC(3),
ord_date DATE DEFAULT NOT NULL,
UNIQUE (ord_no),
PRIMARY KEY (ord_no));

D. CREATE TABLE ord_details


(ord_no NUMERIC(2),
item_no NUMERIC(3),
ord_date DATE DEFAULT GETDATE() NOT NULL,
PRIMARY KEY (ord_no, item_no));

Adding constraints to existing table :-


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

=> "ALTER" command is used to add constraints to existing table.

CREATE TABLE EMP33


(
EMPNO INT,
ENAME VARCHAR(10),
SAL MONEY,
DNO INT,
EMAILID VARCHAR(20)
)

Adding primary key :-


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

=> primary key cannot be added to nullable column


=> to add primary key first change the column to not null.

add primary key to empno ?

STEP 1 :- change the column to not null

ALTER TABLE EMP33


ALTER COLUMN EMPNO INT NOT NULL

STEP 2 :- add primary key

ALTER TABLE EMP33


ADD PRIMARY KEY(EMPNO)
Adding check constraint :-
------------------------------------

=> add check constraint with cond sal >= 3000 ?

ALTER TABLE EMP33


ADD CHECK(SAL>=3000)

ALTER TABLE EMP


ADD CHECK(SAL>=3000) => ERROR

above command returns error because in table some of the employee


salaries are less than 3000 . While adding constraint sql server also
validates existing data.

WITH NOCHECK :-
--------------------------

=> if check constraint added "WITH NOCHECK" then sql server will not
validate existing data and it validates only new data.

ALTER TABLE EMP


WITH NOCHECK ADD CHECK(SAL>=3000)

Adding foreign key :-


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

=> add fk to dno that refers dept55 table pk i.e. dno ?

ALTER TABLE EMP33


ADD FOREIGN KEY(DNO) REFERENCES DEPT55(DNO)

Adding unique :-
-----------------------

=> add unique constraint to emialid ?

ALTER TABLE EMP33


ADD UNIQUE(EMAILID)

changing from NULL TO NOT NULL :-


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

=> modify the column ename to not null ?

ALTER TABLE EMP33


ALTER COLUMN ENAME VARCHAR(10) NOT NULL

Droping constraints :-
-------------------------------

ALTER TABLE <tabname>


DROP CONSTRAINT <name>

EX :-

drop check constraint in emp33 ?

ALTER TABLE EMP33


DROP CONSTRAINT CK__EMP33__SAL__693CA210

drop primary key in dept55 table ?

ALTER TABLE DEPT55


DROP CONSTRAINT PK__DEPT55__C035B8C2CC99E6C6 => ERROR

DROP TABLE DEPT55 => ERROR

TRUNCATE TABLE DEPT55 => ERROR

NOTE :-

=> pk cannot be dropped if referenced by some fk


=> pk table cannot be dropped if referenced by some fk
=> pk table cannot be truncated if referenced by some fk

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

1 ON DELETE NO ACTION (DEFAULT)


2 ON DELETE CASCADE
3 ON DELETE SET NULL
4 ON DELETE SET DEFAULT

=> these rules are declared with foreign key.


=> delete rule specifies how child rows are affected if parent row is deleted.

ON DELETE NO ACTION :-
-------------------------------------

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

CREATE TABLE DEPT88


(
DNO INT PRIMARY KEY,
DNAME VARCHAR(10) UNIQUE NOT NULL
)

INSERT INTO DEPT88 VALUES(10,'HR'),(20,'IT')

CREATE TABLE EMP88


(
EMPNO INT PRIMARY KEY,
ENAME VARCHAR(10) NOT NULL,
DNO INT REFERENCES DEPT88(DNO)
)

INSERT INTO EMP88 VALUES(1,'A',10),(2,'B',10)

DELETE FROM DEPT88 WHERE DNO=10 => ERROR

scenario :-

ACCOUNTS
ACCNO ACTYPE BAL
100 S 10000

LOANS
ID TYPE AMT ACCNO
1 H 30 100
2 C 10 100

RULE :- account closing is not possible if associated with loans

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

=> parent row is deleted along with child rows.

CREATE TABLE DEPT88


(
DNO INT PRIMARY KEY,
DNAME VARCHAR(10) UNIQUE NOT NULL
)

INSERT INTO DEPT88 VALUES(10,'HR'),(20,'IT')

CREATE TABLE EMP88


(
EMPNO INT PRIMARY KEY,
ENAME VARCHAR(10) NOT NULL,
DNO INT REFERENCES DEPT88(DNO)
ON DELETE CASCADE
)

INSERT INTO EMP88 VALUES(1,'A',10),(2,'B',10)

DELETE FROM DEPT88 WHERE DNO=10 => 1 ROW AFFECTED

SELECT * FROM EMP88 => NO ROWS

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

ACCOUNTS
ACCNO ACTYPE BAL
100 S 10000

TRANS
TRID TTYPE TDATE TAMT ACCNO REFERENCES ACCOUNTS(ACCNO)
1 W 100 ON DELETE CASCADE
2 D 100

ON DELETE SET NULL :-


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

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

CREATE TABLE DEPT88


(
DNO INT PRIMARY KEY,
DNAME VARCHAR(10) UNIQUE NOT NULL
)

INSERT INTO DEPT88 VALUES(10,'HR'),(20,'IT')


CREATE TABLE EMP88
(
EMPNO INT PRIMARY KEY,
ENAME VARCHAR(10) NOT NULL,
DNO INT REFERENCES DEPT88(DNO)
ON DELETE SET NULL
)

INSERT INTO EMP88 VALUES(1,'A',10),(2,'B',10)

DELETE FROM DEPT88 WHERE DNO=10 =>1 ROW AFFECTED

SELECT * FROM EMP88

ENO ENAME DNO


1 A NULL
2 B NULL

scenario :-

projects
projid name duration
100
101

emp
empno ename projid references projects (projid) on delete set null
1 100
2 101

rule :- if project is completed (deleted) set the employee projid to null.

ON DELETE SET DEFAULT :-


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

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

CREATE TABLE DEPT88


(
DNO INT PRIMARY KEY,
DNAME VARCHAR(10) UNIQUE NOT NULL
)

INSERT INTO DEPT88 VALUES(10,'HR'),(20,'IT')

CREATE TABLE EMP88


(
EMPNO INT PRIMARY KEY,
ENAME VARCHAR(10) NOT NULL,
DNO INT DEFAULT 20
REFERENCES DEPT88(DNO)
ON DELETE SET DEFAULT
)

INSERT INTO EMP88 VALUES(1,'A',10),(2,'B',10)

summary :-
importance of constraints
types of constraints
declaring constraints
column level
table level
adding constraints
droping constraints
delete rules

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

JOINS
=====

=> join is an operation performed to display data from two or more tables.

=> In DB related data is stored in multiple tables , to combine the data


stored in multiple table we need to join those tables.

ex :-

orders customers
ordid orddt deldt cid cid cname addr
1000 10 10 A HYD
1001 11 11 B HYD

=> join the above tables to display following output

ordid orddt deldt cname caddr


1000 A HYD
1001 B HYD

Types of join :-
--------------------

1 Inner join / Equi join


2 Outer join
left join
right join
full join
3 Self join
4 Non Equi join
5 Cross join / Cartesian join

Inner join / Equi join :-


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

=> To perform inner 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 cond

join cond :-
------------------

=> based on the given join condition sql server joins the records of two tables
TABLE1.COMMONFIELD = TABLE2.COMMONFIELD

EX :-

EMP DEPT
EMPNO ENAME DEPTNO DEPTNO DNAME LOC
1 A 10 10 ACCOUNTS NEW YORK
2 B 20 20 RESEARCH
3 C 30 30 SALES
4 D 20 40 OPERATIONS
5 E NULL

=> display ENAME DNAME LOC ?


----------- --------------------------
EMP DEPT

SELECT ENAME,DNAME,LOC
FROM EMP INNER JOIN DEPT
ON EMP.DEPTNO = DEPT.DEPTNO

A ACCOUNTS NEW YORK


B RESEARCH ?
C SALES ?
D RESEARCH ?

10-oct-23

NOTE :-

=> in join , Declare table alias and prefix column names with table alias for
two reasons

1 to avoid ambiguity
2 for faster execution

SELECT E.ENAME,E.DEPTNO,D.DNAME,D.LOC
FROM EMP AS E INNER JOIN DEPT AS D
ON E.DEPTNO = D.DEPTNO

=> display ENAME DNAME working at NEW YORK loc ?

SELECT E.ENAME,D.DNAME
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 ?

SELECT O.* , C.*


FROM ORDERS AS O INNER JOIN CUSTOMERS AS C
ON O.CID = C.ID

joining more than 2 tables :-


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

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


=> to join N tables N-1 join conditions required
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 ?


----------- ----------- -------------------
----------------
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

EMP DEPT
EMPNO ENAME DEPTNO DEPTNO DNAME LOC
1 A 10 10 ACCOUNTS NEW YORK
2 B 20 20 RESEARCH
3 C 30 30 SALES
4 D 20 40 OPERATIONS => unmatched row
5 E NULL => unmatched row

=> outer join is 3 types

1 LEFT JOIN
2 RIGHT JOIN
3 FULL JOIN

11-oct-23

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

=> returns 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

=> returns all rows from dept and matching rows from emp

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

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

Displaying 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 OPERATIONS

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

scenario :-

EMP PROJECTS
EMPNO ENAME PROJID PROJID NAME DURATION
1 100 100 AAA
2 101 101 BBB
3 NULL 102 CCC

=> display employee details with project details ?

=> display employee details with project details and also display employees
not assigned to any projects ?

=> display list of projects where no employee assigned to it ?

NON-EQUI JOIN :-
--------------------------

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

EMP SALGRADE
EMPNO ENAME SAL GRADE LOSAL HISAL
1 A 3000 1 700 1000
2 B 5000 2 1001 2000
3 C 1500 3 2001 3000
4 D 2500 4 3001 4000
5 E 1000 5 4001 9999

=> display ENAME SAL GRADE ?


----------------- -----------
EMP SALGRADE

SELECT E.ENAME,E.SAL,S.GRADE
FROM EMP AS E JOIN SALGRADE AS S
ON E.SAL BETWEEN S.LOSAL AND S.HISAL

A 3000 3
B 5000 5
C 1500 2
D 2500 3
E 1000 1
=> display grade 3 employee list ?

SELECT E.ENAME,E.SAL,S.GRADE
FROM EMP AS E JOIN SALGRADE AS S
ON E.SAL BETWEEN S.LOSAL AND S.HISAL
WHERE S.GRADE=3

=> display ENAME DNAME GRADE ?

SELECT E.ENAME,D.DNAME,S.GRADE
FROM EMP AS E INNER JOIN DEPT AS D
ON E.DEPTNO = D.DEPTNO
JOIN SALGRADE AS S
ON E.SAL BETWEEN S.LOSAL AND S.HISAL

12-OCT-23

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

=> joining a table to itself is called self join or recursive join.


=> in self join a record in one table joined with another record of same table.

ex :-

EMP
EMPID ENAME MGR
7369 VIJAY 7902
7499 ALLEN 7698
7566 JONES 7839
7698 BLAKE 7839
7839 KING NULL
7902 FORD 7566

=> above table contains manager number but to display manager name perform self
join

=> to perform self join the same table must be declared two times with different
alias

FROM EMP AS X JOIN EMP AS Y

EMP X EMP Y
EMPID ENAME MGR EMPID ENAME MGR
7369 VIJAY 7902 7369 VIJAY 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 AS MANAGER


FROM EMP AS X JOIN EMP AS Y
ON X.MGR = Y.EMPID

VIJAY FORD
ALLEN BLAKE
JONES KING
BLAKE KING
FORD JONES

=> employees reporting to blake ?

SELECT X.ENAME,Y.ENAME AS MANAGER


FROM EMP AS X JOIN EMP AS Y
ON X.MGR = Y.EMPID
WHERE Y.ENAME='BLAKE'

=> blake's manager name ?

SELECT X.ENAME,Y.ENAME AS MANAGER


FROM EMP AS X JOIN EMP AS Y
ON X.MGR = Y.EMPID
WHERE X.ENAME='BLAKE'

=> employees earning more than their managers ?

SELECT X.ENAME,Y.ENAME AS MANAGER


FROM EMP AS X JOIN EMP AS Y
ON X.MGR = Y.EMPID
WHERE X.SAL > Y.SAL

=> employees joined before their manager ?

SELECT X.ENAME,X.HIREDATE,
Y.ENAME AS MANAGER,Y.HIREDATE AS MGRHIRE
FROM EMP AS X JOIN EMP AS Y
ON X.MGR = Y.EMPID
WHERE X.HIREDATE < Y.HIREDATE

Question :-

TEAMS
ID COUNTRY
1 IND
2 AUS
3 ENG

=> write the query to display following 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

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


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

CROSS 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 records of 2nd table.

SELECT E.ENAME,D.DNAME
FROM EMP AS E CROSS JOIN DEPT AS D

13-OCT-23

GROUP BY & JOIN :-


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

=> display dept wise total sal ? display dept names ?

SELECT D.DNAME,SUM(E.SAL) AS TOTSAL


FROM EMP AS E INNER JOIN DEPT AS D
ON E.DEPTNO = D.DEPTNO
GROUP BY D.DNAME

ON E.DEPTNO = D.DEPTNO :-
------------------------------------------

EMP DEPT
EMPNO ENAME SAL DEPTNO DEPTNO DNAME
1 A 3000 10 10 ACCOUNTS
2 B 4000 20 20 RESEARCH
3 C 3000 30 30 SALES
4 D 5000 20 40 OPERATIONS
5 E 4000 10

output :-

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

GROUP BY D.DNAME :-
---------------------------------

ACCOUNTS 1 A 3000
5 E 4000

RESEARCH 2 B 4000
4 D 5000

SALES 3 C 3000

SELECT D.DNAME,SUM(E.SAL) AS TOTSAL :-


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

ACCOUNTS 7000
RESEARCH 9000
SALES 3000

=> display grade wise no of employees ?

=> display no of employees working under each manager ?

=>

SALES
DATEID PRODID CUSTID QTY AMT
2023-10-13 100 10 1 2000

PRODUCTS
PRODID PNAME PRICE CATEGORY
100 AAA 2000 ELECTRONICS

CUST
CUSTID NAME ADDR COUNTRY
10 KKK HYD IND

=> display year wise total amount ?


=> display category wise total amount ?
=> display country wise total amount ?
=> display year wise,country wise,category wise total amount ?

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

UNION
UNION ALL
INTERSECT
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 set operations performed between records return by two queries

SELECT STATEMENT 1
UNION / UNION ALL / INTERSECT / EXCEPT
SELECT STATEMENT 2

Rules :-

1 no of columns return by both queries must be same


2 corresponding columns datatype must be same

SELECT job FROM emp WHERE deptno = 20


CLERK
MANAGER
ANALYST
CLERK
ANALYST

SELECT job FROM emp WHERE deptno = 30

SALESMAN
SALESMAN
SALESMAN
MANAGER
SALESMAN
CLERK

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

=> combines rows


=> eliminates duplicates
=> sorts result

SELECT job FROM emp WHERE deptno = 20


UNION
SELECT job FROM emp WHERE deptno = 30

ANALYST
CLERK
MANAGER
SALESMAN

SELECT job,sal FROM emp WHERE deptno = 20


UNION
SELECT job,sal FROM emp WHERE deptno = 30

ANALYST 3450.00
CLERK 920.00
CLERK 1200.00
CLERK 1265.00
MANAGER 3450.00
MANAGER 3480.00
SALESMAN 1560.00
SALESMAN 1800.00
SALESMAN 1920.00

UNION VS JOIN :-
-------------------------

UNION JOIN

1 combines rows combines columns

2 horizontal merge vertical merge

3 performed between can be performed between


two similar structures two dissimilar structures

scenario :-
--------------
EMP_US
ENO ENAME DNO

DEPT
EMP_IND DNO DNAME LOC
ENO ENAME DNO

=> total employee list ?

SELECT * FROM EMP_US


UNION
SELECT * FROM EMP_IND

=> 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

=> 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

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

=> combines rows


=> 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

UNION VS UNION ALL :-


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

UNION UNION ALL

1 eliminates duplicates doesn't


eliminate duplicates

2 sorts result doesn't sort result

3 slower faster

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

=> returns common values from output of two queries

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

Question :-

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

=> write outputs 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

14-oct-23

SUB-QUERIES / NESTED QUERIES :-


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

=> a query in another query is called sub-query or nested query


=> one query is called inner query and other query is called outer query
=> first sql server executes inner query then sql server executes outer query
=> result of inner query is input to outer query
=> use subqueries when where cond based on unknown value.
Types of subqueries :-
------------------------------

1 single row sub-queries


2 multi-row sub-queries
3 co-related sub-queries
4 derived tables and CTEs
5 scalar sub-queries

single row sub-queries :-


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

=> if sub-query returns one value then it is called single row sub-query

SELECT columns
FROM tabname
WHERE colname OP (SELECT STATEMENT)

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

ex :-

=> display employees earning more than blake ?

SELECT *
FROM EMP
WHERE SAL > (SELECT SAL FROM EMP WHERE ENAME='BLAKE')

=> employees who are senior to king ?

SELECT *
FROM EMP
WHERE HIREDATE < (SELECT HIREDATE
FROM EMP
WHERE ENAME='KING')

=> name of the employee earning max sal ?

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 )

=> 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))

NOTE :-

=> outer query can be select/insert/update/delete but inner query must be


always select

=> increase sal of employee having max experience by 10% ?

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)

UPDATE EMP
SET SAL = CASE EMPNO
WHEN 7369 THEN 1600
WHEN 7499 THEN 800
END
WHERE EMPNO IN (7369,7499)

16-oct-23

Multi-row subqueries :-
------------------------------

=> if sub-query returns more than one value then it is called multi-row subquery

SELECT columns
FROM tabname
WHERE colname OP (SELECT STMT)

=> OP must be IN , NOT IN,ANY,ALL

SINGLE MULTI

= IN
<> NOT IN

> >ANY >ALL

< <ANY <ALL

examples :-

=> employees working at NEW YORK,CHICAGO locations ?

subquery :-
-----------------

SELECT *
FROM EMP
WHERE DEPTNO IN ( SELECT DEPTNO
FROM DEPT
WHERE LOC IN ('NEW YORK','CHICAGO'))

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

SELECT E.*
FROM EMP AS E INNER JOIN DEPT AS D
ON E.DEPTNO = D.DEPTNO
WHERE D.LOC IN ('NEW YORK','CHICAGO')

=> display ENAME DNAME working at NEW YORK,CHICAGO loc ?

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

SELECT E.ENAME,D.DNAME
FROM EMP AS E INNER JOIN DEPT AS D
ON E.DEPTNO = D.DEPTNO
WHERE D.LOC IN ('NEW YORK','CHICAGO')

subquery :-
-----------------

not possible

Difference between subquery & join ?

1 to display data from one table and condition based on another table
then we can use subquery or join

2 to display data from two tables then use join

ANY & ALL operators :-


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

=> use ANY & ALL operators for > < comparision with multiple values

WHERE X > ANY(1000,2000,3000) WHERE X > ALL(1000,2000,3000)

IF X = 800 FALSE IF X = 800 FALSE


1500 TRUE 1500 FALSE
4500 TRUE 4500 TRUE

WHERE X < ANY(1000,2000,3000) WHERE X < ALL(1000,2000,3000)

IF X = 800 TRUE IF X = 800 TRUE


1500 TRUE 1500 FALSE
4500 FALSE 4500 FALSE

=> employees earning more than all managers ?

SELECT *
FROM EMP
WHERE SAL > ALL (SELECT SAL
FROM EMP
WHERE JOB='MANAGER')
-------------------------------------
2975,2850,2450

=> employees earning more than atleast one manager ?

SELECT *
FROM EMP
WHERE SAL > ANY (SELECT SAL
FROM EMP
WHERE JOB='MANAGER')
------------------------------------
2975,2850,2450

CO-RELATED subqueries :-
--------------------------------------

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

=> 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 subquery to execute subquery for each row return by outer query

1 returns a row from outer query


2 pass value to inner query
3 executes inner query
4 returns output to outer query
5 execute outer query where cond

example 1 :-

EMP
EMPNO ENAME SAL DEPTNO
1 A 5000 10
2 B 3000 20
3 C 4000 30
4 D 6000 20
5 E 2000 10

=> 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)

1 A 5000 10 5000 > (WHERE DEPTNO=10) 3500 TRUE


2 B 3000 20 3000 > (WHERE DEPTNO=20) 4500 FALSE
3 C 4000 30 4000 > (WHERE DEPTNO=30) 4000 FALSE
4 D 6000 20 6000 > (WHERE DEPTNO=20) 4500 TRUE
5 E 2000 10 2000 > (WHERE DEPTNO=10) 3500 FALSE

=> employees earning max sal in their dept ?

SELECT *
FROM EMP AS X
WHERE SAL = ( SELECT MAX(SAL)
FROM EMP
WHERE DEPTNO = X.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 2000 10 2000 = (5000) FALSE

17-oct-23

=> 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 SAL DESC

EMP A EMP B
SAL SAL
5000 5000 3 > (0) TRUE
1000 1000 3 > (4) FALSE
3000 3000 3 > (1) TRUE
2000 2000 3 > (3) FALSE
2975 2975 3 > (2) 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 SAL DESC

Derived Tables :-
------------------------
=> subqueries in FROM clause are called derived tables

SELECT columns
FROM (SELECT STATEMENT) AS <ALIAS>
[WHERE COND]

=> subquery output acts like a table for outer query

=> derived tables are used in following senarios

1 to control order of execution of clauses


2 to use result of one operation in another operation
3 to join two query outputs

controlling order of execution of clauses :-


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

default order :-
-------------------

FROM
WHERE
GROUP BY
HAVING
SELECT
ORDER BY

=> to control this order of execution use derived table

Example 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 problem 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

SELECT *
FROM E
WHERE RNK <= 5

=> display top 3 max salaries ?


SELECT DISTINCT sal
FROM (SELECT sal,
dense_rank() over (order by sal desc) as rnk
FROM emp) AS E
WHERE rnk <= 3
ORDER BY SAL DESC

=> display top 3 max salaries in each dept ?

SELECT *
FROM (SELECT deptno,sal,
dense_rank() over (partition by deptno
order by sal desc) as rnk
FROM emp ) AS E
WHERE rnk <= 3

10 5000 1
2450 2
1300 3

20 3000 1
3000 1
2975 2
1100 3

18-oct-23

=> display first 5 rows from emp table ?

SELECT *
FROM (SELECT EMPNO,ENAME,SAL ,
ROW_NUMBER() OVER (ORDER BY EMPNO ASC) AS RNO
FROM EMP) AS E
WHERE RNO<=5

WHERE RNO = 5

WHERE RNO IN (5,7,11)

WHERE RNO BETWEEN 5 AND 10

WHERE RNO%2=0

=> display last 3 rows from emp ?

SELECT *
FROM (SELECT EMPNO,ENAME,SAL ,
ROW_NUMBER() OVER (ORDER BY EMPNO ASC) AS RNO
FROM EMP) AS E
WHERE RNO >= (SELECT COUNT(*)-2 FROM EMP)

=> delete first 3 rows from emp ?

DELETE
FROM (SELECT EMPNO,ENAME,SAL ,
ROW_NUMBER() OVER (ORDER BY EMPNO ASC) AS RNO
FROM EMP) AS E
WHERE RNO<=3 => error
NOTE :- in derived tables outer query cannot be DML and it must be always
SELECT

CTE :-
---------

=> CTE stands for common table expression,

=> using CTE we can give name to the query output and we can refer that
name in another query like SELECT/INSERT/UPDATE/DELETE.

=> in derived tables outer query cannot be DML but in CTEs outer query can be
DML

=> using CTEs we can simplify complex queries

WITH
<CTE-NAME1>
AS
(SELECT STATEMENT)

<CTE-NAME2>
AS
(SELECT STATEMENT)

SELECT / INSERT / UPDATE / DELETE

EX :-

delete frist 3 rows from emp ?

WITH E
AS
(SELECT EMPNO,ENAME,SAL ,
ROW_NUMBER() OVER (ORDER BY EMPNO ASC) AS RNO
FROM EMP)
DELETE FROM E WHERE RNO<=3

=> delete duplicate records from table ?

EMP44
ENO ENAME SAL
1 A 5000
2 B 6000
3 C 7000
1 A 5000
2 B 6000

STEP 1 :- generate row numbers with in group of eno,ename,sal

SELECT ENO,ENAME,SAL,
ROW_NUMBER() OVER (PARTITION BY ENO,ENAME,SAL
ORDER BY ENO,ENAME,SAL ) AS RNO
FROM EMP44

1 A 5000.00 1
1 A 5000.00 2

2 B 6000.00 1
2 B 6000.00 2

3 C 7000.00 1

STEP 2 :- delete the records with rno > 1

WITH E
AS
(SELECT ENO,ENAME,SAL,
ROW_NUMBER() OVER (PARTITION BY ENO,ENAME,SAL
ORDER BY ENO,ENAME,SAL ) AS RNO
FROM EMP44)
DELETE FROM E WHERE RNO>1

Assignment :-

T1
AMT
1000
-200
2000
-800
3000
-500

output :-
POS NEG
1000 -200
2000 -800
3000 -500

2 T1 T2
F1 C1
1 A
2 B
3 C

OUTPUT :-

1 A
2 B
3 C

3
DEPTNO FIRST_MAX SECOND_MAX
10 ? ?
20 ? ?
30 ? ?

scalar subqueries :-
---------------------------

=> subqueries in SELECT clause are called scalar subqueries

SELECT (subquery1),(subquery2),--------------
FROM tabname
WHERE cond

=> subquery output acts like a column

=> use scalar subquery to show query output in seperate column

ex 1 :-

SELECT (SELECT COUNT(*) FROM EMP) AS EMP,


(SELECT COUNT(*) FROM DEPT) AS DEPT

EMP DEPT
14 4

ex 2 :-

=> display dept wise total sal ?

SELECT DEPTNO,SUM(SAL) AS DEPT_TOTAL


FROM EMP
GROUP BY DEPTNO

10 8750.00
20 10075.00
30 6550.00

=> display DEPTNO DEPT_TOTAL TOTAL ?

SELECT DEPTNO,SUM(SAL) AS DEPT_TOTAL ,


(SELECT SUM(SAL) FROM EMP) AS TOTAL
FROM EMP
GROUP BY DEPTNO

10 8750.00 25375
20 10075.00 25375
30 6550.00 25375

19-OCT-23

=> display DEPTNO DEPT_TOTAL TOTAL PCT ?

PCT = (DEPT_TOTAL / TOTAL * 100

SELECT DEPTNO,SUM(SAL) AS DEPT_TOTAL ,


(SELECT SUM(SAL) FROM EMP) AS TOTAL ,
(SUM(SAL) / (SELECT SUM(SAL) FROM EMP))*100 AS PCT
FROM EMP
GROUP BY DEPTNO

10 8750.00 25375.00 34.48


20 10075.00 25375.00 39.70
30 6550.00 25375.00 25.81

select stmt
where
order by
distinct
top
functions
group by & having
joins
set operators
subqueries

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

PIVOT operator :-
-------------------------

=> operator used to convert rows into columns


=> used to display data in matrix form

SELECT columns
FROM (SELECT required data) AS <ALIAS>
PIVOT
(
AGGR-EXPR FOR COLNAME IN (V1,V2,V3,--)
) AS <PIVOT_TBL_NAME>
ORDER BY COLNAME ASC/DESC

Ex :-
10 20 30

ANALYST ? ? ?

CLERK ? ? ?

MANAGER ? ? ?

SALESMAN ? ? ?

SELECT *
FROM (SELECT DEPTNO,JOB,SAL FROM EMP) AS E
PIVOT
(
SUM(SAL) FOR DEPTNO IN ([10],[20],[30])
) AS PIVOT_TBL
ORDER BY JOB ASC

Ex 2 :-

1 2 3 4

1980 ? ? ? ?

1981 ? ? ? ?

1982 ? ? ? ?

1983 ? ? ? ?

SELECT *
FROM (SELECT DATEPART(YY,HIREDATE) AS YEAR,
DATEPART(QQ,HIREDATE) AS QRT,
EMPNO
FROM EMP) AS E
PIVOT
(
COUNT(EMPNO) FOR QRT IN ([1],[2],[3],[4])
) AS PIVOT_TBL
ORDER BY YEAR ASC

ex 3 :-

STUDENT
SNO SNAME SUBJECT MARKS
1 A MAT 70
1 A PHY 60
1 A CHE 80
2 B MAT 60
2 B PHY 50
2 B CHE 40

output :-

SNO SNAME MAT PHY CHE


1 A 70 60 80
2 B 60 50 40

creating new table from existing table (replica) :-


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

SELECT COLUMNS INTO <NEW-TABNAME>


FROM <OLD-TABNAME>
WHERE COND

ex 1 :- copying complete table

SELECT * INTO EMP11


FROM EMP

creates new table with name EMP11 and copies rows & cols from emp to emp11

ex 2 :- copying specific rows & cols

SELECT EMPNO,ENAME,JOB,SAL INTO EMP22


FROM EMP
WHERE JOB IN ('CLERK','MANAGER')

ex 3 :- copy only columns but not rows

SELECT * INTO EMP33


FROM EMP
WHERE 1=2

ex 3 :- copy table from one db to another db

copy emp table from DB6PM to SALESDB

SELECT * INTO SALESDB.DBO.EMP


FROM EMP

MERGE command :-
--------------------------

=> merge is the combination of insert , update & delete.


=> merge used to manage replicas
=> using merge we can apply changes made to one table to another table.

syn :-

MERGE INTO <TARGET-TABLE> AS <ALIAS>


USING <SOURCE-TABLE> AS <ALIAS>
ON (CONDITION)
WHEN MATCHED THEN
UPDATE
WHEN NOT MATCHED THEN
INSERT
WHEN NOT MATCHED BY SOURCE
DELETE ;

Ex :-

STEP 1 :- create source table

CREATE TABLE CUSTS


(
CID INT,
CNAME VARCHAR(10),
CADDR VARCHAR(10)
)

INSERT INTO CUSTS VALUES(1,'A','HYD'),(2,'B','MUM')

STEP 2 :- create target table

SELECT * INTO CUSTT


FROM CUSTS

CUSTT
CID CNAME CADDR
1 A HYD
2 B MUM

STEP 3 :- modify source table

INSERT INTO CUSTS VALUES(3,'C','DEL')

UPDATE CUSTS SET CADDR='BLR' WHERE CID=1

CUSTS
CID CNAME CADDR
1 A BLR => UPDATED
2 B MUM
3 C DEL => INSERTED

STEP 4 :- apply changes made to custs to custt ?

MERGE INTO CUSTT AS T


USING CUSTS AS S
ON (S.CID = T.CID)
WHEN MATCHED THEN
UPDATE SET T.CADDR = S.CADDR
WHEN NOT MATCHED THEN
INSERT VALUES(S.CID,S.CNAME,S.CADDR)
WHEN NOT MATCHED BY SOURCE THEN
DELETE ;

=>

EMPS EMPT
EMPID ENAME SAL EMPID ENAME SAL
1 A 5000 1 A
2 B 6000 2 B
3 C 7000 3 C

copy salaries from EMPS to EMPT ?

method 1
method 2

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

=> every transaction must gurantee a property called atomocity i.e. all or none
if txn contains multiple operations , if all are successful then it must be
saved,
if one of the operation failes then entire txn must be cancelled.

=> the following commands provided by sql server to control the transaction
called TCL commands.

COMMIT => to save txn


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

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

=> a txn begins implicitly with dml command and ends implicitly with commit.

=> a user can also start txn by using "BEGIN TRANSACTION" command.
and ends explicitly with COMMIT / ROLLBACK command.

ex 1 :-

CREATE TABLE A(A INT) => commit


BEGIN TRANSACTION => txn starts T1
INSERT INTO A VALUES(10)
INSERT INTO A VALUES(20)
COMMIT => txn ends

if txn ends with COMMIT then it is called successful txn and operations are
saved

ex 2 :-

CREATE TABLE A(A INT) => commit


BEGIN TRANSACTION => txn starts T1
INSERT INTO A VALUES(10)
INSERT INTO A VALUES(20)
ROLLBACK => txn ends

=> if txn ends with ROLLBACK then it is called aborted txn and operations are
cancelled

ex 3 :-

CREATE TABLE A(A INT) => commit


BEGIN TRANSACTION => txn starts T1
INSERT INTO A VALUES(10)
INSERT INTO A VALUES(20)
COMMIT => txn ends
INSERT INTO A VALUES(30) => commit
INSERT INTO A VALUES(40) => commit
ROLLBACK => ERROR

SELECT * FROM A

10
20
30
40

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

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

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 ST1

SELECT * FROM A

10
20

27-OCT-23

DB Security :-
-------------------

1 LOGINS => provides security at server level


2 USERS => provides securityt at db level
3 PRIVILEGES => provides security at table level
4 VIEWS => provides security at row & col level

SERVER (LOGINS)
DATABASE (USERS)
TABLES (PRIVILEGES)
ROWS & COLS (VIEWS)

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 :-


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

USE [master]
GO
CREATE LOGIN [NARESH] WITH PASSWORD=N'123'
GO

creating user in db :-
---------------------------

=> In object explorer expand Database


DB6PM
Users => New User

Enter Username :- VIJAY

Enter Login Name :- NARESH

=> click OK

command to create user :-


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

USE [DB6PM]
GO
CREATE USER [VIJAY] FOR LOGIN [NARESH]
GO

SERVER
SA
NARESH

DB6PM
DBO (SA)
EMP
DEPT
CUST
STUDENT
VIJAY (NARESH)

PRIVILEGES :-
----------------------

=> privileges means permissions


=> permissions are granted to user by using grant command

GRANT <privileges> ON <tabname> TO <usernames>

DBO :-

GRANT SELECT,INSERT,UPDATE,DELETE ON EMP TO VIJAY

VIJAY :-

1 SELECT * FROM EMP

2 UPDATE EMP SET SAL=3000 WHERE EMPNO = 7566

REVOKE command :-
---------------------------

=> command used to take back permissions from user

REVOKE <privileges> ON <tabname> FROM <usernames>

DBO :-

REVOKE SELECT,INSERT,UPDATE,DELETE ON EMP FROM VIJAY

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

DB objects / SCHEMA objects :-


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

TABLES
VIEWS
SYNONYMS
SEQUENCES
INDEXES

STORED PROCEDURES
FUNCTIONS
TRIGGERS

28-OCT-23

VIEWS :-
----------

=> a view is a subset of a table i.e part of a 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 a representation of a query.

=> views are created

1 to provide security
2 to reduce complexity

=> view provides another level of security i.e. row & col level , with the help
of views we can grant specific rows & cols to users.

=> 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

SELECT * FROM V1

=> when above query submitted to sql server , it executes the query as follows

SELECT * FROM (SELECT EMPNO,ENAME,JOB,DEPTNO FROM EMP)

Granting permissions on view to user :-


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

GRANT SELECT,INSERT,UPDATE,DELETE ON V1 TO VIJAY

VIJAY :-
1 SELECT * FROM V1

2 UPDATE V1 SET JOB='CLERK' WHERE EMPNO=7566

3 UPDATE V1 SET SAL=2000 WHERE EMPNO=7566 => ERROR

Row level security :-


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

CREATE VIEW V2
AS
SELECT EMPNO,ENAME,JOB,DEPTNO
FROM EMP
WHERE DEPTNO=20

GRANT SELECT,INSERT,UPDATE,DELETE ON V2 TO VIJAY

VIJAY :-
-----------

INSERT INTO V2 VALUES(100,'ABC', 'CLERK',30)

above insert command is accepted 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 condition 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 VIJAY

VIJAY :-
-----------

INSERT INTO V3 VALUES(110,'KLM','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
subqueries

=> 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 AS E INNER JOIN DEPT AS D
ON E.DEPTNO = D.DEPTNO

after creating view whenever we want data from emp & dept tables then
execute the following simple query

SELECT * FROM CV1

ex 2 :-

CREATE VIEW CV2


AS
SELECT D.DNAME,SUM(E.SAL) AS TOTSAL
FROM EMP AS E INNER JOIN DEPT AS D
ON E.DEPTNO = D.DEPTNO
GROUP BY D.DNAME

=> whenever we want dept wise total salary then execute the following simple 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 like where operations like joins,group by etc

3 always updatable not updatable i.e. doesn't allow dmls


i.e. allows dmls

=> list of views created by user ?

SELECT * FROM INFORMATION_SCHEMA.VIEWS

Droping view :-
--------------------

DROP VIEW V1

if we drop table what about views created on table ?

ans :- views are not dropped but cannot be queried

WITH SCHEMABINDING :-
------------------------------------

=> if view created with schemabinding then sql server will not allow user
to drop table if any view exists on the table.

=> to drop table first we need to drop view


Rules :-

1 "*" is not allowed in select


2 table name should be prefixed with schema name

ex :-

CREATE VIEW V10


WITH SCHEMABINDING
AS
SELECT DEPTNO,DNAME,LOC FROM DBO.DEPT

DROP TABLE DEPT => ERROR

30-OCT-23

Synonyms :-
-----------------

=> a synonym is another name or alternative name to a table or view.

=> if tablename is lengthy then we can give a simple and short name to
the table called synonym and after creating synonym 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

=> use synonym name in SELECT / INSERT /UPDATE /DELETE queries

1 SELECT * FROM E
2 UPDATE E SET COMM = 500 WHERE EMPNO = 7369

accessing tables without dbname and schema name :-


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

to access tables of other dbs

SELECT * FROM DB4PM.DBO.STUDENT

CREATE SYNONYM STUDENT FOR DB4PM.DBO.STUDENT

SELECT * FROM STUDENT

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 synonym scope of the alias


is upto the schema is upto the query

=> list of synonyms created by user ?

SELECT name,base_object_name FROM SYS.SYNONYMS

Droping synonym :-
---------------------------

DROP SYNONYM E

SEQUENCES :-
--------------------

=> sequences are 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 / NOCYCLE]
[CACHE <SIZE>]

Example 1 :-

CREATE SEQUENCE S1
START WITH 1
INCREMENT BY 1
MAXVALUE 5

using sequence :-
-----------------------

CREATE TABLE STUDENT


(
SID INT,
SNAME VARCHAR(10)
)

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

SELECT * FROM STUDENT

SID SNAME
1 A
2 B
3 C
4 D
5 E

Example 2 :-

CREATE SEQUENCE S2
START WITH 100
INCREMENT BY 1
MAXVALUE 999

use above sequence to generate empno ?

UPDATE EMP SET EMPNO = NEXT VALUE FOR S2

Example 3 :-

BILL
BILLNO BDATE
NIT/1023/1 ??
NIT/1023/2 ??

CREATE TABLE BILL


(
BILLNO VARCHAR(20) ,
BDATE DATETIME
)

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())

How to restart sequence :-


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

1 using ALTER command


2 using CYCLE

using ALTER command :-


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

ALTER SEQUENCE S3 RESTART WITH 1

31-OCT-23

USING CYCLE :-
-----------------------

=> by default sequence created with NOCYCLE

=> sequence starts from start with and generates upto max and after reaching
max then it stops

=> if sequence created with CYCLE then it starts from start with and generates
upto max and after reaching max then it will reset to min.

CREATE SEQUENCE S5
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

INDEXES :-
---------------

=> index is also a db object created to improve the performance of data


accessing.

=> index in db is similar to index in textbook , In textbook using index a


particular topic can be located fastly, In db using index a particular
record can be located fastly.

=> indexes are created on columns and that column is called index key.

=> indexes created on columns

1 that are frequently used in where clause


2 which are used in join operation

Types of Indexes :-
--------------------------

1 Non Clustered Indexes


simple
composite
unique
2 Clustered Indexes

simple non clustered index :-


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

=> if index created on single column then it is called simple index

CREATE INDEX <NAME> ON <TABNAME> (COLNAME)

EX :- CREATE INDEX I1 ON EMP(SAL)

EMP 3000
SAL
3000
1000 2000 4000
2000
4000
3000 1000 * 2500 * 4000 * 5000 *
1500 1500 * 3000 *,*
2500 2000 *
5000

=> when we submit query to sql server ,it uses following methods to locate the
record

1 TABLE SCAN
2 INDEX SCAN

=> in TABLE SCAN sql server scans complete table i.e. each and every row.

=> in INDEX SCAN on avg sql server scans only half of the table , so index
scan is 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)

composite index :-
------------------------

=> if index created on multiple columns then it is called composite index

ex :- CREATE INDEX I2 ON EMP(DEPTNO,JOB)

20

10 30

10 CLERK * 20 CLERK *,* 30 CLERK *


10 MGR * 20 MGR * 30 MGR *
30 SALESMAN *,*,*,*

=> sql server uses above index when where cond based on deptno

SELECT * FROM EMP WHERE DEPTNO = 20 ; (INDEX)


SELECT * FROM EMP WHERE DEPTNO = 20 AND JOB = 'CLERK' ; (INDEX)

SELECT * FROM EMP WHERE JOB='CLERK' (TABLE)

01-NOV-23

UNIQUE index :-
-----------------------

=> unique index doesn't allow duplicate values into the column on which index
is created.

CREATE UNIQUE INDEX I3 ON EMP(ENAME)

G Q
ADAMS * JAMES * MARTIN * SCOTT *
ALLEN * JONES * MILLER * SMITH *
BLAKE * WARD *

1 SELECT * FROM EMP WHERE ENAME = 'BLAKE'

2 INSERT INTO EMP(EMPNO,ENAME,SAL) VALUES(100,'BLAKE',5000) => ERROR

what are different methods to enforce uniqueness ?

1 declare primary key / unique


2 create unique index

=> primary key / unique columns are automatically indexed by sql server ,
sql server creates a unique index on primary key / unique columns and
unique index doesn't allow duplicates so primary key / unique also doesn't
allow duplicates.

CLUSTERED INDEX :-
-------------------------------

=> a non clustered index stores pointers to actual records where as clustered
index stores
actual records

CREATE TABLE CUST


(
CID INT,
CNAME VARCHAR(10)
)

CREATE CLUSTERED INDEX I5 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

10 A
40 C
60 D
80 B

2 SELECT * FROM CUST WHERE CID=40 => sql server goes to index and find
the entry with cid=40 and return
the record from index
NOTE :-

=> only one clustered index is allowed per table


=> sql server creates a clustered index on primary key column.

difference between clustered and non clustered indexes ?

non clustered clustered

1 stores pointers to actual recortd stores actual records

2 data is not sorted based on data sorted based on index column


index column

3 needs extra storage doesn't need extra storage

4 needs two lookups needs one lookup

5 max 999 non clustered only one clustered index allowed


per table
indexes allowed per table

6 by default a non clustered by default a


clustered index is
index is created on unique created on primary key
column
column

=> list of indexes ?

SP_HELPINDEX EMP

Droping index :-
-----------------------

DROP INDEX EMP.I1

SERVER
DATABASE
TABLE
ROWS & COLS
CONSTRAINTS
INDEXES
TRIGGERS
VIEW
SYNONYMS
SEQUENCES

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

02-NOV-23 T-SQL programming (Transact-SQL)


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

Basic programming
conditional stmts
loops
cursors
error handling
stored procedures
functions
triggers
dynamic sql

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 & response between
user and sql server are reduced and performance is improved.

2 supports conditional stmts :-


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

=> T-SQL supports conditional stmts like IF-ELSE, so in T-SQL we can


execute SQL commands based on conditions.

3 supports loops :-
------------------------

=> T-SQL supports loops like while , with the help of loops 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 display our own simple and user friendly message.

5 supports modular programming :-


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

=> in T-SQL a big program can be divided into small modules with the help of
procedures and functions.

6 supports reusability :-
--------------------------------

=> T-SQL programs can be stored in db and applications which are connected
to db can reuse T-SQL programs

=> T-SQL blocks are 2 types

1 Anonymous Blocks
2 Named Blocks
stored procedures
functions
triggers

Anonymous Blocks :-
-------------------------------

=> a T-SQL program without name is called anonymous block


=> the following statements are used in T-SQL programs

1 DECLARE
2 SET
3 PRINT

DECLARE statement :-
-------------------------------

=> used to declare variables

DECLARE @varname DATATYPE(size)

ex :- DECLARE @x INT
DECLARE @s VARCHAR(10)
DECLARE @d DATE

DECLARE @x INT,@s VARCHAR(10),@d DATE

SET statement :-
-----------------------

=> statements used to assign value to variable

SET @varname = value

ex :- SET @x = 100
SET @s = 'HELLO'
SET @d = GETDATE()

PRINT statement :-
--------------------------

=> statement used to print messages or values

EX :- PRINT 'HELLO'

PRINT @x

Ex 1 :-

DECLARE @a INT,@b INT,@c INT


SET @a=100
SET @b=200
SET @c = @a+@b
PRINT @c

Ex 2 :-

=> write a prog to input date and print day of the week ?

DECLARE @d DATE
SET @d = '2024-01-01'
PRINT DATENAME(DW,@d)

Ex 3 :-

=> write a prog to input name and print first name and last name ?
DECLARE @n VARCHAR(20) , @f VARCHAR(20),@l VARCHAR(20)
SET @n = 'sachin tendulkar'
SET @f = SUBSTRING(@n,1,CHARINDEX(' ',@n)-1)
SET @l = SUBSTRING(@n,CHARINDEX(' ',@n)+1,LEN(@n))
PRINT @f
PRINT @l

SUBSTRING(string,start,len)
CHARINDEX(char,string,[start])

DB PROGRAMMING WITH T-SQL :-


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

=> to perform operations over db execute SQL commands from t-sql program.
=> the following commands are executed from T-SQL program.

1 DML (INSERT,UPDATE,DELETE,MERGE)
2 DQL (SELECT)
3 TCL (COMMIT,ROLLBACK,SAVE TRANSACTION)

SELECT stmt syntax :-


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

SELECT @var1 = col1 ,


@var2 = col2,
-----------------
FROM tabname
WHERE condition

ex :-

SELECT @n = ENAME,
@s = SAL
FROM EMP
WHERE EMPNO = 110

03-nov-23

=> write a prog to input empno and print name & salary ?

DECLARE @eno INT,@name VARCHAR(10),@sal MONEY


SET @eno = 110
SELECT @name = ename ,
@sal = sal
FROM emp
WHERE empno = @eno
PRINT @name + ' ' + CAST(@sal AS VARCHAR)

=> write a prog to input empno and calculate experience ?

DECLARE @eno INT,@hire DATE,@expr TINYINT


SET @eno=105
SELECT @hire=hiredate FROM emp WHERE empno = @eno
SET @expr = DATEDIFF(YY,@hire,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

=> write a prog 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 = 2500
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

=> write a prog to input empno and increment sal as follows ?

if deptno = 10 incr sal by 10%


20 15%
30 20%
others 5%

DECLARE @eno INT,@dno INT,@pct TINYINT


SET @eno=112
SELECT @dno=deptno FROM emp WHERE empno = @eno
IF @dno=10
SET @pct=10
ELSE IF @dno=20
SET @pct=15
ELSE IF @dno=30
SET @pct=20
ELSE
SET @pct=5
UPDATE emp SET sal = sal + (sal*@pct/100) WHERE empno = @eno

=> Write a prog to process bank transaction (w/d) ?

ACCOUNTS
ACCNO ACTYPE BAL
100 S 10000
101 C 20000

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
PRINT 'insufficient balance'
ELSE
UPDATE accounts SET bal = bal - @amt WHERE accno = @acno
END
ELSE IF @type='d'
UPDATE accounts SET bal = bal + @amt WHERE accno = @acno
ELSE
PRINT 'invalid transaction type'

=> write a prog to process money transfer ?

DECLARE @sacno INT,@tacno INT,@amt MONEY,@bal MONEY


DECLARE @cnt1 INT,@cnt2 INT
SET @sacno=100
SET @tacno=101
SET @amt=1000
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
SET @cnt1 = @@rowcount
UPDATE accounts SET bal = bal + @amt WHERE accno = @tacno
SET @cnt2=@@rowcount
IF @cnt1=1 AND @cnt2=1
COMMIT
ELSE
ROLLBACK
END

@@rowcount :-
--------------------

=> It is a system variable that returns no of rows affected by last dml

Atomocity :-
---------------

=> atomocity means all or none , if txn contains multiple operations if all are
succssful then it must be committed , if one of the operation fails then entire
txn must be cancelled.

=> @@rowcount is useful to check whether individual operations are successful


or not

=> write a prog 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 60 50

RESULT
SNO TOTAL AVG RESULT

DECLARE @sno INT,@s1 INT,@s2 INT,@s3 INT


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

=> write a prog to print numbers from 1 to 20 ?

DECLARE @x INT = 1
WHILE(@x<=20)
BEGIN
PRINT @x
SET @x = @x+1
END

=> write a prog to print 2024 calendar ?

2024-01-01 ??
2024-01-02 ??

2024-12-31 ??

DECLARE @d1 DATE,@d2 DATE


SET @d1 = '2024-01-01'
SET @d2 = '2024-12-31'
WHILE(@d1<=@d2)
BEGIN
PRINT CAST(@d1 AS VARCHAR) + ' ' + DATENAME(DW,@d1)
SET @d1 = DATEADD(DD,1,@d1)
END

06-NOV-23

=> write a prog to print only sundays between two given dates ?

DECLARE @d1 DATE,@d2 DATE


SET @d1 = '2024-01-01'
SET @d2 = '2024-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 = '2024-01-01'
SET @d2 = '2024-12-31'
/* to find first sunday */
WHILE(DATENAME(DW,@d1) <> 'SUNDAY')
BEGIN
SET @d1 = DATEADD(DD,1,@d1)
END
/* to print sundays */
WHILE(@d1<=@d2)
BEGIN
PRINT CAST(@d1 AS VARCHAR) + ' ' + DATENAME(DW,@d1)
SET @d1 = DATEADD(DD,7,@d1)
END

=> write a prog to input string and print following pattern ?

input :- NARESH

output :-

N
A
R
E
S
H

DECLARE @s VARCHAR(10),@x INT = 1


SET @s='NARESH'
WHILE(@x <= LEN(@s))
BEGIN
PRINT SUBSTRING(@s,@x,1)
SET @x = @x + 1
END

=> write a prog to input string and print following pattern ?

input :- NARESH

output :-

N
NA
NAR
NARE
NARES
NARESH

DECLARE @s VARCHAR(10),@x INT = 1


SET @s='NARESH'
WHILE(@x <= LEN(@s))
BEGIN
PRINT SUBSTRING(@s,1,@x)
SET @x = @x + 1
END

=> write a prog to input string and print reverse of that string ?

input :- NARESH

output :- HSERAN

DECLARE @s1 VARCHAR(10),@s2 VARCHAR(10)=' ',@x INT


SET @s1='NARESH'
SET @x = LEN(@s1)
WHILE(@x >= 1)
BEGIN
SET @s2 = @s2 + SUBSTRING(@s1,@x,1)
SET @x = @x -1
END
PRINT @s2
IF @s1 = LTRIM(@s2)
PRINT 'palindrome'
ELSE
PRINT 'not a palindrome'

CURSORS :-
------------------

=> cursors are used to access row-by-row into t-sql program

=> from T-SQL program if we submit a query to sql server , it goes to db


and gets the data and copies that data into temporary memory
called cursor and in our program we can give name to that cursor
and access 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 <cursor-name> CURSOR FOR SELECT STATEMENT

ex :-

DECLARE C1 CURSOR FOR SELECT ENAME,SAL FROM EMP

Opening cursor :-
------------------------

OPEN <cursor-name>

EX :- OPEN C1

1 select stmt submitted to sql server


2 data returned by query is copied to cursor
3 c1 points to cursor

Fetching records from cursor :-


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

=> "FETCH" statement is used to fetch record from cursor

FETCH NEXT FROM <cursor> INTO <variables>

EX :-

FETCH NEXT FROM C1 INTO @name,@sal

=> a fetch stmt fetches one row at a time but to process multiple rows fetch stmt
should be executed multiple times, so fetch stmt should be in a loop.
Closing cursor :-
----------------------

CLOSE <cursor-name>

EX :- CLOSE C1

Deallocating cursor :-
--------------------------

DEALLOCATE <cursor-name>

ex :- DEALLOCATE C1

@@FETCH_STATUS :-
--------------------------------

=> system variable that returns status of fetch stmt i.e. successful or failed

0 => fetch is successful


-1 => fetch is unsuccessful

07-NOV-23

=> Write a prog to print all employee names and salaries ?

DECLARE C1 CURSOR FOR SELECT ENAME,SAL FROM EMP


DECLARE @NAME VARCHAR(10),@SAL MONEY
OPEN C1
FETCH NEXT FROM C1 INTO @NAME,@SAL
WHILE(@@FETCH_STATUS=0)
BEGIN
PRINT @NAME + ' ' + CAST(@SAL AS VARCHAR)
FETCH NEXT FROM C1 INTO @NAME,@SAL
END
CLOSE C1
DEALLOCATE C1

=> write a prog to calculate total sal without using sum function ?

DECLARE C1 CURSOR FOR SELECT SAL FROM EMP


DECLARE @SAL MONEY,@TOTSAL MONEY=0
OPEN C1
FETCH NEXT FROM C1 INTO @SAL
WHILE(@@FETCH_STATUS=0)
BEGIN
SET @TOTSAL = @TOTSAL + @SAL
FETCH NEXT FROM C1 INTO @SAL
PRINT @TOTSAL
END
PRINT @TOTSAL
CLOSE C1
DEALLOCATE C1

=> write a prog to calculate max sal without using max function ?

DECLARE C1 CURSOR FOR SELECT SAL FROM EMP


DECLARE @SAL MONEY,@MAX MONEY=0
OPEN C1
FETCH NEXT FROM C1 INTO @SAL
WHILE(@@FETCH_STATUS=0)
BEGIN
IF @SAL > @MAX
SET @MAX = @SAL
FETCH NEXT FROM C1 INTO @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

=> write a prog to print min sal ?

=> write a prog to print employee names as follows ?

smith,allen,ward,jones,martin,-----------

DECLARE C1 CURSOR FOR SELECT ENAME FROM EMP


DECLARE @NAME VARCHAR(10),@S VARCHAR(1000)=' '
OPEN C1
FETCH NEXT FROM C1 INTO @NAME
WHILE(@@FETCH_STATUS=0)
BEGIN
SET @S = @S + @NAME + ','
FETCH NEXT FROM C1 INTO @NAME
END
PRINT STUFF(@S,LEN(@S),1,'.')
CLOSE C1
DEALLOCATE C1

REPLACE(str1,str2,str3)

STUFF(str1,start,len,str2)

=> write a prog 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 60 50

RESULT
SNO TOTAL AVG RESULT
DECLARE C1 CURSOR FOR SELECT SNO,S1,S2,S3 FROM STUDENT
DECLARE @SNO INT,@S1 INT,@S2 INT,@S3 INT
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
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

1 80 90 70
2 30 60 50

08-NOV-23

SCROLLABLE CURSOR :-
------------------------------------

=> by default cursor is FORWARD ONLY cursor and it supports forward


navigation but doesn't support backward navigation.

=> if cursor declared with SCROLL then it is called scrollable cursor


and supports both forward and backward navigation.

=> forward only cursor supports only FETCH NEXT statement but scrollable
cursor supports the following fetch statements.

FETCH FIRST => returns first record


FETCH NEXT => returns next record
FETCH PRIOR => returns previous record
FETCH LAST => returns last record
FETCH ABSOLUTE N => returns Nth record from first record
FETCH RELATIVE N => returns Nth record from current record

EX :-

DECLARE C1 CURSOR SCROLL FOR SELECT ENAME FROM EMP


DECLARE @NAME VARCHAR(10)
OPEN C1
FETCH FIRST FROM C1 INTO @NAME
PRINT @NAME
FETCH LAST FROM C1 INTO @NAME
PRINT @NAME
FETCH PRIOR FROM C1 INTO @NAME
PRINT @NAME
FETCH ABSOLUTE 5 FROM C1 INTO @NAME
PRINT @NAME
FETCH RELATIVE 5 FROM C1 INTO @NAME
PRINT @NAME
CLOSE C1
DEALLOCATE C1

=> write a prog to print every 5th record ?

DECLARE C1 CURSOR SCROLL FOR SELECT ENAME FROM EMP


DECLARE @NAME VARCHAR(10)
OPEN C1
FETCH ABSOLUTE 5 FROM C1 INTO @NAME
WHILE(@@FETCH_STATUS=0)
BEGIN
PRINT @NAME
FETCH RELATIVE 5 FROM C1 INTO @NAME
END
CLOSE C1
DEALLOCATE C1

=> write a prog to print 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

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

ERROR HANDLING / EXCEPTION HANDLING :-


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

1 syntax errors
2 logical errors
3 runtime errors

=> errors that are raised during program execution are called runtime errors

ex :- declare @x tinyint
set @x = 1000 => runtime error
print @x

=> if any statement causes runtime error then sql server displays error message ,
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 called TRY---CATCH block

BEGIN TRY
statements => statements causes exception
END TRY
BEGIN CATCH
statements => statements handles exception
END CATCH
=> in try block if any statement causes exception then control transferred to
catch block and executes the statements catch block.

ex :-

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
3 ERROR_SEVERITY() => returns severity level
4 ERROR_STATE() => returns state
5 ERROR_LINE() => returns line number

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 0'
END CATCH

09-nov-23

CREATE TABLE CUST


(
CID INT PRIMARY KEY,
CNAME VARCHAR(10) NOT NULL,
AGE TINYINT CHECK(AGE>=20)
)

=> write a prog to insert data into cust table ?

DECLARE @cid INT,@name VARCHAR(10),@age TINYINT


BEGIN TRY
SET @cid=100
SET @name='A'
SET @age=25
INSERT INTO cust VALUES(@cid,@name,@age)
END TRY
BEGIN CATCH
IF ERROR_NUMBER()=2627
PRINT ' cid should not be duplicate '
ELSE IF ERROR_NUMBER()=515
PRINT ' name should not be null'
ELSE IF ERROR_NUMBER()=547
PRINT ' age >= 20 '
END CATCH

USER DEFINED ERRORS :-


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

=> errors raised by user are called user defined errors


=> user raises error to stop program execution based on condition
=> the following procedure is used to raise error

RAISERROR(error msg,severity level,state)

severity level :-
---------------------

0–10 Informational messages


11–18 Errors
19–25 Fatal errors

state :-
-----------

state is an integer between 0 to 255. If you raise the same user-defined


error at multiple locations, using state we can identity which section of the
code
is causing the error.

example 1 :-

=> write a prog to increment specific employee sal by specific amt and
sunday updates are not allowed ?

DECLARE @eno INT,@amt MONEY


SET @eno=108
SET @amt=1000
IF DATENAME(DW,GETDATE())='SUNDAY'
RAISERROR('sunday not allowed',16 ,1)
ELSE
UPDATE emp SET sal = sal + @amt WHERE empno = @eno

example 2 :-

=> write a prog for money withdrawl ?

ACCOUNTS
ACCNO ACTYPE BAL
100 S 10000
101 C 20000

DECLARE @acno INT,@amt MONEY,@bal MONEY,@cnt INT


DECLARE @msg VARCHAR(100)
BEGIN TRY
SET @acno = 100
SET @amt = 20000
SELECT @cnt = COUNT(*) FROM accounts WHERE accno = @acno
IF @cnt=0
RAISERROR(' account does not exists',16,1)
SELECT @bal = bal FROM accounts WHERE accno = @acno
IF @amt > @bal
RAISERROR('insufficient balance',15,1)
UPDATE accounts SET bal = bal - @amt WHERE accno = @acno
END TRY
BEGIN CATCH
SET @msg = ERROR_MESSAGE()
RAISERROR(@msg,16,1)
END CATCH

=> list of errors ?

SELECT * FROM SYS.MESSAGES

how to add user defined error to sys.messages :-


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

SP_ADDMESSAGE 50001,16,'sunday not allowed'

DECLARE @eno INT,@amt MONEY


SET @eno=108
SET @amt=1000
IF DATENAME(DW,GETDATE())='SUNDAY'
RAISERROR(50001,16 ,1)
ELSE
UPDATE emp SET sal = sal + @amt WHERE empno = @eno

Remove user defined error from sys.messages :-


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

SP_DROPMESSAGE 50001

10-NOV-23

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 & functions a big T-SQL program can be
divided into small modules.
2 reusability :-
-------------------

=> procedures & functions can be stored in db , so applications which are


connected to db can reuse procedures & functions.

3 can be invoked from front-end :-


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

=> procedures & functions can be called from front-end applications like
java,.net and procedures reduces no of requests going to db and improves
performance.

4 improves performance :-
--------------------------------

=> procedures improves performance because they are precompiled i.e.


compiled already and ready for execution. if we create a procedure
then 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 and performs
some action on db and may or may not returns a value.

=> procedures are created to perform one or more dml operations on tables

CREATE OR ALTER PROCEDURE <NAME>


parameters if any
AS
statements

parameters :-
-------------------

=> we can declare parameters and we can pass values to parameters


=> parameters are 2 types

1 INPUT (DEFAULT)
2 OUTPUT

=> input parameters always receives value


=> output parameter always sends value

main procedure

A--------------------------------------> X (INPUT)

B <---------------------------------------- Y (OUTPUT)

example 1 :- procedure without parameters

=> create a 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)

Execution :-

1 from ssms
2 from t-sql program
3 front-end applications

from ssms :-
-----------------

EXECUTE raise_salary

example 2 :- procedure with parameters

=> create a 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 100,1000 positional


association

2 EXECUTE raise_salary @eno=100,@amt=1000 named association

3 EXECUTE raise_salary @amt=1000 ,@eno=100

11-NOV-23

example 3 :- procedure with output parameter

=> create a procedure to increment specific employee sal by specific amount


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 100,1000,@s OUTPUT
PRINT @s

Declaring parameters with default value :-


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

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

@amt MONEY = 500

=> while execution if we don't pass value to @amt then sql server assigns
default value.

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

=> create procedure for money withdrawl ?

ACCOUNTS
ACCNO ACTYPE BAL
100 S 10000

TRANSACTIONS
TRID TTYPE TDATE TAMT ACCNO

CREATE TABLE ACCOUNTS


(
ACCNO INT PRIMARY KEY,
ACTYPE CHAR(1),
BAL MONEY
)
INSERT INTO ACCOUNTS VALUES(100,'S',10000)

CREATE TABLE TRANSACTIONS


(
TRID INT IDENTITY ,
TTYPE CHAR(1) ,
TDATE DATETIME,
TAMT MONEY,
ACCNO INT REFERENCES ACCOUNTS(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)
END

EXECUTION :-

DECLARE @b MONEY
EXECUTE DEBIT 100,15000,@b OUTPUT
PRINT @b

=> create procedure for money deposit ?

=> create procedure for money transfer ?

13-NOV-23

Procedures returning cursor :-


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

=> create procedure that accepts deptno and returns list of employees working for
that dept ?

CREATE OR ALTER PROCEDURE getEmpList


@dno INT,
@empcur CURSOR VARYING OUTPUT
AS
SET @empcur = CURSOR FOR
SELECT empno,ename,sal
FROM emp
WHERE deptno = @dno
OPEN @empcur

Execution :-

DECLARE @c1 CURSOR


DECLARE @eno INT,@name VARCHAR(10),@sal MONEY
EXECUTE getEmpList 20,@c1 OUTPUT
FETCH NEXT FROM @c1 INTO @eno,@name,@sal
WHILE(@@FETCH_STATUS=0)
BEGIN
PRINT cast(@eno as varchar) + ' ' + @name + ' ' +
cast(@sal as varchar)
FETCH NEXT FROM @c1 INTO @eno,@name,@sal
END
CLOSE C1
DEALLOCATE C1

Assignment :-

=> create a procedure to return top n employees list ?


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
and performs some calucation and must return a value.

=> functions are created

1 for calculations
2 to fetch data from table

syntax :-

CREATE OR ALTER FUNCTION <NAME>


(
parameters
) RETURNS <type>
AS
BEGIN
STATEMENTS
RETURN <expr>
END

Example 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 :-

1 sql commands
2 another t-sql program
3 front-end applications

Executing from sql commands :-


--------------------------------------------
SELECT DBO.CALC(10,20,'*') => 200

=> create a function to calculate experience of employee ?

CREATE OR ALTER FUNCTION expr


(
@eno INT
) RETURNS INT
AS
BEGIN
DECLARE @hire DATE ,@x INT
SELECT @hire=hiredate FROM emp WHERE empno = @eno
SET @x = DATEDIFF(YY,@hire,GETDATE())
RETURN @x
END

Execute :-

1 SELECT DBO.EXPR(100) => 43

2 SELECT EMPNO,ENAME,DBO.EXPR(EMPNO) AS EXPR


FROM EMP

TABLE VALUED FUNCTIONS :-


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

=> these functions returns records


=> return type must be TABLE.
=> return expr is SELECT statement
=> table valued functions allows only one stmt and it must be return stmt

CREATE OR ALTER FUNCTION <name>


(
parameters if any
) RETURNS TABLE
AS
RETURN (SELECT STATEMENT)

Example 1 :-

=> create a function that accepts deptno and returns list of employees
working for that dept ?

CREATE OR ALTER FUNCTION getEmpList


(
@d INT
) RETURNS TABLE
AS
RETURN (SELECT * FROM EMP WHERE DEPTNO = @d)

Execution :-

=> table valued functions are called in FROM clause

SELECT * FROM DBO.GETEMPLIST(20)

Example 2 :-

create a function that returns Top N employee list based on sal ?


CREATE OR ALTER FUNCTION getTopNEmpList
(
@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)

=> create following procedures & functions to implement variou bank txns ?

ACCOUNTS
ACCNO ACTYPE BAL

TRANSACTIONS
TRID TTYPE TDATE TAMT ACCNO

CREATE SEQUENCE S1
START WITH 1
INCREMENT BY 1
MAXVALUE 99999

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 stmt between two given dates (tvf)
8 latest N transactions of particualr customer (tvf)

=> difference between procedures & functions ?

PROCEDURES FUNCTIONS

1 may or may not returns a value must return a value

2 can return multiple always


returns one

3 procedure returns values returns value using


using output parameter return stmt

4 cannot be called from can be called


from sql commands
sql commands

5 created to perform one created for


calculations
or more dml operations

6 create procedure to create


function to get balance
update bal
=> 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 type like int,
varchar

3 returns expr is return exp is select stmt


scalar type variable

4 called in select clause called in from clause

list of procedures & functions created by user ?

SELECT * FROM INFORMATION_SCHEMA.ROUTINES

Droping :-
---------------

DROP PROCEDURE RAISE_SALARY

DROP FUNCTION CALC

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

16-nov-23

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 & 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
example 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=sal+1000 where empno = 100 => ERROR

example 2 :- create trigger to not to allow dmls <10am and >4pm ?

CREATE OR ALTER TRIGGER T2


ON EMP
AFTER INSERT,UPDATE,DELETE
AS
IF DATEPART(HH,GETDATE()) < 10
OR
DATEPART(HH,GETDATE()) >= 16
BEGIN
ROLLBACK
RAISERROR(' only between 10AM and 4PM',16,1)
END

Testing :-

UPDATE EMP SET COMM=1000 WHERE EMPNO = 100 => ERROR

example 3 :- 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 T3


ON EMP
AFTER INSERT,UPDATE,DELETE
AS
IF DATEPART(DW,GETDATE()) BETWEEN 2 AND 6
AND
DATEPART(HH,GETDATE()) NOT BETWEEN 10 AND 15
BEGIN
ROLLBACK
RAISERROR('only between 10AM and 4PM',16,1)
END
ELSE IF DATEPART(DW,GETDATE()) = 7
AND
DATEPART(HH,GETDATE()) NOT BETWEEN 10 AND 13
BEGIN
ROLLBACK
RAISERROR('only between 10AM and 2PM',16,1)
END
ELSE IF DATEPART(DW,GETDATE())=1
BEGIN
ROLLBACK
RAISERROR('sunday not allowed',16,1)
END

Testing :-

UPDATE EMP SET COMM=300 WHERE EMPNO = 100

how to disable trigger & enable trigger ?

DISABLE TRIGGER T2 ON EMP

ENABLE TRIGGER T2 ON EMP

ex 4 :- create trigger to not to allow to update empno ?

CREATE OR ALTER TRIGGER T4


ON EMP
AFTER UPDATE
AS
IF UPDATE(EMPNO)
BEGIN
ROLLBACK
RAISERROR('empno cannot be updated',16,1)
END

Testing :-

UPDATE EMP SET EMPNO = 999 WHERE EMPNO = 100 => error

17-NOV-23

Magic Tables :-
---------------------

1 INSERTED
2 DELETED

=> These tables are called magic tables because they are created and deleted
automatically
=> data affected by dml commands copied to magic tables.
=> 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.

INSERT INTO EMP VALUES(100,'A','CLERK',5000,---) => INSERTED


EMPNO ENAME JOB SAL
100 A CLERK 5000

DELETE FROM EMP WHERE EMPNO = 7369 => DELETED


EMPNO ENAME JOB SAL
7369 SMITH CLERK 800

UPDATE EMP SET SAL=6000 WHERE EMPNO=100 => INSERTED


EMPNO SAL
100 6000
DELETED
EMPNO SAL
100 5000

=> create trigger to not to allow to decrement salary ?

CREATE OR ALTER TRIGGER T5


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 = 500 WHERE EMPNO = 100 => ERROR

=> create trigger to insert details into emp_resign when employee resigns ?

EMP_RESIGN
EMPNO ENAME HIREDATE DOR

CREATE TABLE EMP_RESIGN


(
EMPNO INT ,
ENAME VARCHAR(10),
HIREDATE DATE,
DOR DATE
)

CREATE OR ALTER TRIGGER T6


ON EMP
AFTER DELETE
AS
DECLARE @ENO INT,@NAME VARCHAR(10),@HIRE DATE
SELECT @ENO=EMPNO,@NAME=ENAME,@HIRE=HIREDATE FROM DELETED
INSERT INTO EMP_RESIGN VALUES(@ENO,@NAME,@HIRE,GETDATE())

Testing :-

1 DELETE FROM EMP WHERE EMPNO = 100

2 SELECT * FROM EMP_RESIGN

INSTEAD OF trigger :-
--------------------------------

=> if trigger is instead of then sql server executes the trigger instead of
executing dml
ex :- create trigger to not to allow more than 4 employees per dept ?

EMP33
ENO ENAME DNO
1 A 10
2 B 10
3 C 10
4 D 10
5 E 10 => NOT ALLOWED

CREATE OR ALTER TRIGGER T7


ON EMP33
INSTEAD OF INSERT
AS
DECLARE @ENO INT,@NAME VARCHAR(10),@DNO INT,@CNT INT
SELECT @ENO=ENO,@NAME=ENAME,@DNO=DNO FROM INSERTED
SELECT @CNT = COUNT(*) FROM EMP33 WHERE DNO = @DNO
IF @CNT = 4
RAISERROR('max 4 emps per dept',16,1)
ELSE
INSERT INTO EMP33 VALUES(@ENO,@NAME,@DNO)

Testing :-

INSERT INTO EMP33 VALUES(1,'A',10)


INSERT INTO EMP33 VALUES(2,'B',10)
INSERT INTO EMP33 VALUES(3,'C',10)
INSERT INTO EMP33 VALUES(4,'D',10)
INSERT INTO EMP33 VALUES(5,'E',10) => ERROR

AFTER INSTEAD OF

IF COND IF COND
BEGIN RAISERROR
ROLLBACK ELSE
RAISERROR DML
END

=> list of triggers & tablenames ?

SELECT x.name,y.name
FROM SYS.triggers AS X INNER JOIN sys.tables AS Y
ON X.parent_id= y.object_id

18-nov-23

Auditing :-
---------------

=> Auditing means monitoring day-to-day activities on tables.


=> Triggers are created to perform auditing

ex :-

EMP_AUDIT
UNAME OPERATION OPTIME NEW_ENO NEW_ENAME NEW_SAL OLD_ENO OLD_ENAME
OLD_SAL
CREATE TABLE EMP_AUDIT
(
UNAME VARCHAR(10),
OPERATION VARCHAR(10),
OPTIME DATETIME,
NEW_ENO INT,
NEW_ENAME VARCHAR(10),
NEW_SAL MONEY,
OLD_ENO INT,
OLD_ENAME VARCHAR(10),
OLD_SAL MONEY
)

create trigger to insert details into emp_audit whenever user insert,update,delete


records
into emp table ?

CREATE OR ALTER TRIGGER T9


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(333,'KKK',4000)


2 DELETE FROM EMP WHERE EMPNO = 108
3 UPDATE EMP SET SAL = 5000 WHERE EMPNO = 333

SELECT * FROM EMP_AUDIT

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

Dynamic SQL :-
----------------------

=> SQL commands generated at runtime are called dynamic sql commands

ex :- DROP TABLE EMP (static sql command)

DECLARE @TNAME VARCHAR(10)


SET @TNAME = 'CUST'
DROP TABLE @TNAME (Dynamic sql command)

=> Dynamic sql is useful when we don't know tablenames and column names until
runtime

=> Dynamic sql commands are executed by using EXEC procedure

EXEC (' Dynamic sql command ' )

=> Dynamic sql that you want to execute should be passed as a string to EXEC.

ex :- create a procedure to drop table from db ?

CREATE OR ALTER PROCEDURE DROP_TABLE


@tname VARCHAR(30)
AS
EXEC (' DROP TABLE ' + @tname)

Execution :-
----------------

execute drop_table 'emp'

20-NOV-23

=> create 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(20)
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

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

Backup & Restore :-


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

=> DB needs to be protected from failures like hardware,software and application


program
=> Backups are created to protect db from failures.
=> copying db from server to a file called backup
=> recovering db from backup file is called restore

BACKUP :-
---------------

CREATE OR ALTER PROCEDURE BACKUP_DBS


AS
DECLARE C1 CURSOR FOR SELECT name
FROM SYS.DATABASES
WHERE DATABASE_ID>4
DECLARE @DBNAME VARCHAR(20) , @file VARCHAR(100)
OPEN C1
FETCH NEXT FROM C1 INTO @DBNAME
WHILE(@@FETCH_STATUS=0)
BEGIN
SET @file = 'D:\BACKUPS\' + @DBNAME + CONVERT(VARCHAR,GETDATE(),112) + '.BAK'
BACKUP DATABASE @DBNAME TO DISK = @file
FETCH NEXT FROM C1 INTO @DBNAME
END
CLOSE C1
DEALLOCATE C1

21-NOV-23

Temporary Tables :-
---------------------------

=> Temporary tables are created for storing data temporaryly .

=> Temporary tables exists upto the session , once session closes temporary
tables are
deleted automatically.

=> Temporary tables are created in temp db

=> Temporary tables are 2 types

1 Local Temp Tables


2 Global Temp Tables

Local Temp Tables :-


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

=> Local Temp Tables are accessed with in the db in which it is created

Method 1 :-

CREATE TABLE #TEMP


(
ENO INT,
ENAME VARCHAR(10),
SAL MONEY
)

INSERT INTO #TEMP


SELECT EMPNO,ENAME,SAL FROM EMP

METHOD 2 :-
SELECT * INTO #TEMP FROM EMP

Global Temporary Tables :-


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

=> Global Temporary Tables created in one connection and can be accessed in
another connection

ex :- SELECT * INTO ##TEMP10 FROM EMP

Table variable :-
----------------------

=> It is a variable that stores table data.


=> scope of the table variable is upto the program
=> after program execution table variables cannot be accessed

DECLARE @t TABLE
(
ENO INT,
ENAME VARCHAR(10),
SAL MONEY
)

INSERT INTO @t
SELECT EMPNO,ENAME,SAL FROM EMP

SELECT * FROM @t

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

=> used to generate sequence number


=> used to auto increment column values

CREATE TABLE STUDENT


(
SID INT IDENTITY,
SNAME VARCHAR(10)
)

INSERT INTO STUDENT(SNAME) VALUES('A')


INSERT INTO STUDENT(SNAME) VALUES('B')
INSERT INTO STUDENT(SNAME) VALUES('C')
INSERT INTO STUDENT(SNAME) VALUES('D')

SELECT * FROM STUDENT

SID SNAME
1 A
2 B
3 C
4 D

22-nov-23
Normalization :-
----------------------

=> Normalization is the process of decomposing table with redundency into


number of well structured tables.

=> Normalization is set of rules and each rule is called one normal form.

=> There are six normal forms

1NF
2NF
3NF
BCNF
4NF
5NF

Ex :-

BILL
BILLNO BDATE CCODE NAME ADDR ICODE NAME RATE QTY VALUE
TBILL
1000 22- 100 A HYD 1
1000 22- 100 A HYD 2
3

20

1NF :-
---------

=> a table said to be in 1NF if there are no multivalued attributes in it or all


the attributes
in table are atomic (single).

BILL
BILLNO BDATE CCODE NAME ADDR ICODE NAME RATE QTY VALUE
TBILL
s s s s s m
m m m m s

=> in the above table some attributes are single valued and some attributes are
multi valued
so the table is not according to 1NF , so decompose the table as follows

BILL
BILLNO BDATE CCODE NAME ADDR TBILL
------------

BILL_ITEMS
BILLNO ICODE NAME RATE QTY VALUE
-----------------------
1000 1 A 50
1000 2
1000 3
1001 1 A 50
1001 2
1002 1 A 50

=> in the above table when icode is repeated name & rate are also repeated ,
so
apply 2NF to reduce redundency.

2NF :-
---------

=> a table said to be in 2NF

1 if it is in 1NF
2 if there are no partial dependencies in it

partial dependency :-
----------------------------

R(A,B,C,D) A => pk

A ---------> B,C,D (full dependency)

R(A,B,C,D) A+B => pk

A,B --------> C (full dependency)

B ------------> D (partial dependency)

TABLE 1 :-

BILL
BILLNO BDATE CCODE NAME ADDR TBILL according to 2NF
------------

TABLE 2 :-

BILL_ITEMS
BILLNO ICODE NAME RATE QTY VALUE
-----------------------

BILLNO,ICODE -------------> QTY , VALUE (full dependency)

ICODE ---------------> NAME,RATE (partial dependency)

=> above table contains partial dependency , so table is not according to 2NF ,
so
decompose the table as follows

TABLE 2 :-

ITEMS
ICODE NAME RATE
----------

TABLE 3 :-

BILL_ITEMS
BILLNO ICODE QTY VALUE
-------------------------

3NF :-
---------

=> a table said to be in 3NF

1 if it is in 2NF
2 if there are no transitive dependencies in it

Transitive dependecy :-
------------------------------

R(A,B,C,D) A => pk

A ------> B,C (full)

C ------> D (transitive dependency) => non key field depends on


another non key field

TABLE 1 :-

BILL
BILLNO BDATE CCODE NAME ADDR TBILL according to 2NF
------------

BILLNO -------> BDATE,TBILL (full)

CCODE -------> NAME,ADDR (transitive)

above table contains transitive dependency , so the table is not according to


3NF , so
decompose the table as follows

CUST
CCODE NAME ADDR
-----------

BILL
BILLNO BDATE TBILL CCODE
-----------

TABLE 2 :-

ITEMS
ICODE NAME RATE
----------

TABLE 3 :-

BILL_ITEMS
BILLNO ICODE QTY VALUE
-------------------------

AFTER 3NF :-
CUST
CCODE NAME ADDR
-----------

BILL
BILLNO BDATE CCODE TBILL
-----------

ITEMS
ICODE NAME RATE
---------

BILL_ITEMS
BILLNO ICODE QTY VALUE
-----------------------

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

EXISTS & NOT EXISTS operator :-


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

=> both operators are used to check whether record exists in the table or not

SELECT columns
FROM tabname
WHERE EXISTS (SELECT STATEMENT)

EXISTS returns TRUE/FALSE

TRUE => if subquery returns atleast one row


FALSE => if subquery returns 0 rows

Example :-

CUSTS CUSTT
CID NAME ADDR CID NAME ADDR
1 A HYD 1 A HYD
2 B MUM 2 B MUM
3 C DEL

display old customers data ?

SELECT *
FROM CUSTS AS S
WHERE EXISTS (SELECT * FROM CUSTT WHERE CID = S.CID)

1 A HYD WHERE EXISTS (RETURNS 1 ROW) TRUE


2 B MUM WHERE EXISTS (RETURNS 1 ROW) TRUE
3 C DEL WHERE EXISTS (RETURNS 0 ROWS) FALSE

display new customers data ?

SELECT *
FROM CUSTS AS S
WHERE NOT EXISTS (SELECT * FROM CUSTT WHERE CID = S.CID)

1 A HYD WHERE NOT EXISTS (RETURNS 1 ROW) FALSE


2 B MUM WHERE NOT EXISTS (RETURNS 1 ROW) FALSE
3 C DEL WHERE NOT EXISTS ( RETURNS 0 ROWS) TRUE

using IN , NOT IN :-
----------------------------

SELECT *
FROM CUSTS
WHERE CID IN (SELECT CID FROM CUSTT)

1 A HYD
2 B MUM

SELECT *
FROM CUSTS
WHERE CID NOT IN (SELECT CID FROM CUSTT)
1
2
3 C DEL

sql server recommends EXISTS ,NOT EXISTS instead of IN, NOT IN because EXISTS,
NOT EXISTS gives good performance than IN,NOT IN

in T-SQL :-
-------------------

DECLARE @acno INT,@amt MONEY


SET @acno=100
SET @amt=1000
/* check account exists or not */
IF NOT EXISTS (SELECT * FROM ACCOUNTS WHERE ACCNO = @acno)
RAISERROR('account does not exists')
ELSE
----------

Assignment :-
-------------------

DEPT EMP
DNO DNAME LOC EMPNO ENAME SAL DNO
10 HR 1 A 4000 10
20 IT 2 B 3000 20
30 SALES

=> display departments which are not empty ?

=> display departments which are empty ?

Roles

=> involved in creating various db objects like tables,views,synonyms,indexes


=> involved in writing complex queries using joins,group by
=> involved in creating t-sql procedures,functions,triggers
=> involved in data export & import operations
=> involved in backup & restore operations

SUMMARY :-

=> knowledge in sql,t-sql languages


=> knowledge in working with various db objects like tables,-------
=> knowledge in writing simple and complex queries using joins,group by etc
=> knowledge in working with t-sql stored procedures,functions,triggers
=> knowledge in data export & import operations
=> knowledge in backup & restore operations

You might also like