100% found this document useful (1 vote)
183 views

SQL Full Class Notes

The document provides examples of SQL commands like UPDATE, DELETE, TRUNCATE, ALTER, DROP, and built-in functions. It discusses updating and deleting rows from tables, modifying table structures, and extracting date/time values. Functions demonstrated include DATEPART, DATEDIFF, DATENAME, and FORMAT. Identity columns are explained as a way to auto-increment values. The differences between DELETE, TRUNCATE, and DROP commands are summarized.

Uploaded by

Red ranger
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
183 views

SQL Full Class Notes

The document provides examples of SQL commands like UPDATE, DELETE, TRUNCATE, ALTER, DROP, and built-in functions. It discusses updating and deleting rows from tables, modifying table structures, and extracting date/time values. Functions demonstrated include DATEPART, DATEDIFF, DATENAME, and FORMAT. Identity columns are explained as a way to auto-increment values. The differences between DELETE, TRUNCATE, and DROP commands are summarized.

Uploaded by

Red ranger
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 83

29-SEP-22

=> update the employee sal with 2000 and comm with 500
whose empno=7369 ?

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

=> increment sal by 20% and comm by 10% those working


as salesman and joined in 1981 year ?

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

scenario :-

PRODUCTS
prodid pname price category brand

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

UPDATE products
SET price = price + (price*0.1)
WHERE category='mobile phones'
AND
brand IN ('samsung','redmi','realme')

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

=> command used to delete row/rows from table.


=> we can delete all rows or specific rows.

syn :- DELETE FROM <tabname> [WHERE cond]

ex :- delete all rows from emp ?

DELETE FROM emp

delete the employee joined in 1980 ?

DELETE FROM emp WHERE hiredate LIKE '1980%'

DDL commands :- (Data Definition Lang)


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

CREATE
ALTER
DROP
TRUNCATE

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


=> by default all DDL commands are auto committed.
=> to stop auto commit execute SET IMPLICIT_TRANSACTIONS ON
ALTER command :-
-----------------

=> command used to modify the table structure


=> using ALTER command we can

1 add columns
2 drop column
3 modify a column
incr/decr field size
changing datatype

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

ALTER TABLE <tabname>


ADD colname DATATYPE(size)

=> add column gender to emp table ?

ALTER TABLE emp


ADD gender CHAR(1)

after adding the column 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=7499

adding multiple columns :-


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

ALTER TABLE emp


ADD DOB DATE,AADHARNO NUMERIC(12)

Droping column :-
-----------------

ALTER TABLE <tabname>


DROP COLUMN colname

ex :- drop column aadharno from emp

ALTER TABLE emp


DROP COLUMN aadharno

drop columns gender,dob ?

ALTER TABLE emp


DROP COLUMN DOB,GENDER

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

ALTER TABLE <tabname>


ALTER COLUMN colname DATATYPE(size)

=> modify the size of ename column to 20 ?


ALTER TABLE emp
ALTER COLUMN ename VARCHAR(20)

=> change the datatype of empno to smallint ?

ALTER TABLE EMP


ALTER COLUMN EMPNO SMALLINT

=> change the dattype of hiredate to date ?

ALTER TABLE EMP


ALTER COLUMN HIREDATE DATE

30-SEP-22

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

=> command used to drop table from database.


=> drops table structure along with data.

syn :- DROP TABLE <tabname>

ex :- DROP TABLE emp

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

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

=> when truncate command is executed sql server goes to memory and
releases all the pages allocated for table , when pages are
released then data stored in the pages also deleted.

DROP VS DELETE VS TRUNCATE :-


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

DROP DELETE TRUNCATE

1 DDL DML DDL

2 drops structure deletes only data deletes only data


along with data but not structure but not structure

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

DELETE TRUNCATE

1 DML DDL

2 can delete specific row/rows can delete only all rows


but cannot delete specific rows
3 where cond can be used where cond cannot be used
with delete 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 :- (SP => stored procedure)


-----------

=> used to change tablename and column name

SP_RENAME 'oldname','newname'

=> rename table emp to employees ?

SP_RENAME 'EMP','EMPLOYEES'

=> rename column comm to bonus ?

SP_RENAME 'EMPLOYEES.COMM','BONUS'

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

=> used to generate sequence numbers.


=> used to auto increment column values.

syn :- IDENTITY(SEED,INCR)

SEED => START


OPTIONAL
DEFAULT 1

INCR => INCREMENT


OPTIONAL
DEFAULT 1

example :-

CREATE TABLE cust


(
cid INT IDENTITY(100,1),
cname VARCHAR(10)
)

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


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

SELECT * FROM cust

CID NAME
100 A
101 B
102 C

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

DELETE TRUNCATE

CUST CUST
CID NAME CID NAME
100 100
101 101
102 102

DELETE FROM CUST TRUNCATE TABLE cust

INSERT INTO CUST(CNAME) VALUES('K') INSERT INTO CUST(CNAME) VALUES('K')

SELECT * FROM CUST SELECT * FROM CUST

CID NAME CID NAME


103 K 100 K

01-oct-22

how to reset identity manually ?

DBCC CHECKIDENT(tablename,reseed,value)

DBCC => DB CONSISTENCY CHECK

EX :- DBCC CHECKIDENT('CUST',RESEED,99)

NOTE :-
-------

=> by default sql server will not allow explicit value into identity
column

INSERT INTO CUST VALUES(200,'B') => ERROR

=> to provide explicit value into identity column execute the


following command

SET IDENTITY_INSERT CUST ON

INSERT INTO CUST(CID,CNAME) VALUES(200,'B')

SELECT * FROM CUST

CID NAME
200 B

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

BUILT-IN FUNCTIONS IN SQL SERVER :-


-----------------------------------
=> a function accepts some input perform some calculation and
must return a value.

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

1 DATE
2 STRING
3 MATHEMATICAL
4 CONVERSION
5 SPECIAL
6 ANALYTICAL
7 AGGREGATE

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

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

=> returns current date & time

SELECT GETDATE() => 2022-10-01 08:13:17.350

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

=> used to extract part of the date

DATEPART(INTERVAL,DATE)

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


MM => 10
DD => 01
DW => 7 (DAY OF THE WEEK)

1 SUNDAY

7 SATURDAY

DAYOFTHEYEAR => 274


HH => 8
MI => 21
SS => 10
QQ => 4 (QUARTER)

1 JAN-MAR
2 APR-JUN
3 JUL-SEP
4 OCT-DEC

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

SELECT *
FROM emp
WHERE DATEPART(mm,hiredate) IN (1,4,12)

=> display employees joined in leap year ?


leap year => year%4 = 0

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

=> display employees joined on sunday ?

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

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

SELECT *
FROM emp
WHERE DATEPART(yy,hiredate) = 1981
AND
DATEPART(qq,hiredate) = 2

FORMAT :-
---------

=> function used to display date in different formats

FORMAT(date,'format')

SELECT FORMAT(GETDATE(),'yyyy-MM-dd') => 2022-10-01


SELECT FORMAT(GETDATE(),'dd-MM-yyyy') => 01-10-2022
SELECT FORMAT(GETDATE(),'MM/dd/yyyy') => 10/01/2022

=> list of employees joined today ?

SELECT * FROM emp WHERE hiredate = GETDATE() => NO ROWS

2022-10-01 = 2022-10-01 8:51:20

SELECT * FROM emp


WHERE hiredate = FORMAT(GETDATE(),'yyyy-MM-dd')

2022-10-01 = 2022-10-01

10-oct-22 :-

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

=> used to extract part of the date

MM DW

DATEPART 10 2

DATENAME OCTOBER MONDAY

=> display on which day india got independence ?


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

=> display smith joined on wednesday


allen joined on friday ?

string concatenation opertor => +

'a' + 'b' => ab

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

SELECT ename + ' joined on ' + DATENAME(dw,hiredate)


FROM emp

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

=> used to find difference between two dates

DATEDIFF(interval,date1,date2)

SELECT DATEDIFF(yy,'2021-10-10',GETDATE()) => 1


SELECT DATEDIFF(MM,'2021-10-10',GETDATE()) => 12
SELECT DATEDIFF(DD,'2021-10-10',GETDATE()) => 365

=> display ENAME EXPERIENCE in YEARS ?

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

=> display ENAME EXPERIENCE ?


M YEARS N MONTHS

EXPERIENCE = 40 MONTHS = 3 YEARS 4 MONTHS

YEARS = MONTHS/12 = 40/12 = 3

MONTHS = MONTHS%12 = 40%12 = 4

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

=> display employees having more than 40 years of experience ?

SELECT *
FROM emp
WHERE DATEDIFF(yy,hiredate,GETDATE()) > 40

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

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

DATEADD(interval,int,date)
SELECT DATEADD(DD,10,GETDATE()) => 2022-10-20
SELECT DATEADD(DD,-10,GETDATE()) => 2022-09-30
SELECT DATEADD(MM,2,GETDATE()) => 2022-12-10

SCENARIO :-
-----------

GOLD_RATES
DATEID RATE
2015-01-01 ??
2015-01-02 ??

2022-10-09 ??
2022-10-10 ??

1 display today's gold rate ?


2 display yesterdays' gold rate ?
3 display last month same day gold rate ?
4 display last year same day gold rate ?
5

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 SELECT * FROM GOLD_RATES


WHERE DATEID BETWEEN DATEADD(MM,-1,GETDATE()) AND GETDATE()

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

=> returns end of the month i.e. last day of the month

EOMONTH(DATE,INT)

SELECT EOMONTH(GETDATE(),0) => 2022-10-31


SELECT EOMONTH(GETDATE(),1) => 2022-11-30
SELECT EOMONTH(GETDATE(),-1) => 2022-09-30

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

1 display current month 1st day ?


2 display next month first day ?
3 display current year first day ?
4 display next 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

11-oct-22

=> convert all the employee names into lowercase ?

UPDATE emp SET ename = LOWER(ename)

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

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

LEN(arg)

SELECT LEN('hello') => 5


SELECT LEN('hello welcome') => 13

=> display employee list name contains 5 chars ?

SELECT *
FROM emp
WHERE ename LIKE '_____'

WHERE LEN(ename)=5

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

=> used to extract part of the string.

SUBSTRING(string,start,length)

SELECT SUBSTRING('hello welcome',10,3) => com


SELECT SUBSTRING('hello welcome',7,4) => welc

LEFT & RIGHT :-


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

LEFT(string,len) => returns chars from left side


RIGHT(string,len) => returns chars from right side

SELECT LEFT('hello welcome',5) => hello


SELECT RIGHT('hello welcome',7) => welcome

=> employees name starts with 's' ?

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

=> employees name ends with 's' ?

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

=> employees name starts and ends with same char ?

WHERE ename LIKE 'A%A'


or
ename LIKE 'B%B'
or

SELECT * FROM emp


WHERE LEFT(ename,1) = RIGHT(ename,1)

=> generate emailids as follows ?

EMPNO ENAME EMAILID


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

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

=> store emailids in db ?

step 1 :- add emailid column to emp table

ALTER TABLE emp


ADD emailid VARCHAR(20)

step 2 :- update the column with emailids

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

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

=> repeats character for given no of times

REPLICATE(char,len)

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

display ENAME SAL ?


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

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

ACCOUNTS
ACCNO
1234567891234

your a/c no XXXX1234 debited

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

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

=> used to replace one string with another string

REPLACE(str1,str2,str3)

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


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

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

=> used to translate one char to another char

TRANSLATE(str1,str2,str3)

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

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

=> TRANSLATE function used to encrypt data i.e. converting


plain text to cipher text.

SELECT ename,
TRANSLATE(sal,'0123456789.','$hP*t&U@#%^') as sal
FROM emp

JONES 2975.00 P%@&^$$

Assignment :-

1 remove all special chars from '@#he*&LL^%o$*' ?

output :- hello

2
CUST
CID NAME
10 sachin tendulkar
11 virat kohli

display CID FNAME LNAME ?


10 sachin tendulkar

12-oct-22

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

=> returns position of a character 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

=> display employee list name contains 'a' ?

SELECT *
FROM emp
WHERE CHARINDEX('a',ename) <> 0

MATHEMATICAL FUNCTIONS :-
-------------------------

1 POWER :- calculate power

POWER(3,2) => 9

2 SQRT :- returns square root

SQRT(16) => 4

3 SQUARE :- returns square

SQUARE(5) => 25

4 ABS :- returns absolute value

ABS(-10) => 10
ABS(10) => 10

5 SIGN() :- returns whether given number is positive or negative

SIGN(10) => 1
SIGN(-10) => -1
SIGN(10-10) => 0

6 rounding numbers :-

ROUND => rounds number based on avg


CEILING => rounds number always to highest
FLOOR => rounds number always to lowest
38.4747383 => 38
38.47
38.4747

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

ROUND(number,decimal places)

ROUND(38.5678,0) => 39

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

number >= avg => rounded to highest


number < avg => rounded to lowest

ROUND(38.5678,2) => 38.57

ROUND(38.5678,3) => 38.568

ROUND(386,-2) => 400

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

ROUND(386,-1) => 390

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

ROUND(386,-3) => 0

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

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

4570 4600 5000

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 :-
------------------------
=> used to convert one datatype to another datatype

1 CAST
2 CONVERT

CAST :-
--------

CAST(source-expr as target-type)

SELECT CAST(10.5 AS INT) => 10

=> display smith earns 800


allen earns 1600 ?

SELECT ename + ' earns ' + sal FROM emp => ERROR

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

SELECT CONVERT(INT,10.5) => 10

diff b/w CAST & CONVERT ?

1 using convert we can display dates in different formats which is


not possible using cast function

2 using convert we can display numbers in different formats which is


not possible using cast function

Displaying dates in different formats :-


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

CONVERT(VARCHAR,DATE,STYLE-NUMBER)

SELECT CONVERT(VARCHAR,GETDATE(),101) => 10/12/2022


102 => 2022.10.12

114 => 08:41:43:037

display ENAME,HIREDATE ?
display hiredate in mm/dd/yyyy format ?

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


FROM EMP

FORMAT :-
----------
FORMAT(DATE,FORMAT)

SELECT FORMAT(GETDATE(),'dd/MM/yyyy hh:mm:ss') => 12/10/2022 08:48:35

13-oct-22

money & smallmoney styles :-


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

CONVERT(VARCHAR,MONEY/SMALLMONEY,STYLE-NUMBER)

0 => displays 2 decimal places


1 => displays thousand seperator
2 => displays 4 decimal places

display ENAME SAL ?


display salaries with thousand seperator ?

SELECT ENAME,CONVERT(VARCHAR,SAL,1) AS SAL FROM EMP

SMITH 800.00
ALLEN 1,600.00

special functions :-
--------------------

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

=> used to convert null values

ISNULL(arg1,arg2)

if arg1 = null returns arg2


if arg1 <> null returns arg1 only

SELECT ISNULL(100,200) => 100


SELECT ISNULL(NULL,200) => 200

display ENAME SAL COMM TOTSAL ?

TOTSAL = SAL + COMM

SELECT ENAME,SAL,COMM,SAL+COMM AS TOTSAL FROM EMP

SMITH 800 NULL NULL


ALLEN 1690 300 1900

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

=> display ENAME SAL COMM ?


if COMM = NULL display NO COMM ?

SELECT ENAME,SAL,
ISNULL(CAST(COMM AS VARCHAR),'NO COMM') AS COMM
FROM EMP
Analytical Functions / window functions :-
-------------------------------------------

rank & dense_rank :-


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

=> both functions are used to find ranks


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

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


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

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

diff b/w rank & dense_rank ?

1 rank function generates gaps but dense_rank will not generate gaps.

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


ranks will be 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

=> display ranks of the employees based on sal desc , if salaries


are same then ranking should be based on hiredate asc ?

SELECT ename,hiredate,sal,
DENSE_RANK() OVER (ORDER BY sal DESC,hiredate ASC) as rnk
FROM emp

king 1981-11-17 5000.00 1


ford 1981-12-03 3000.00 2
scott 1982-12-09 3000.00 3
jones 1981-04-02 2975.00 4
blake 1981-05-01 2850.00 5

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

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

=> find ranks of the students based on total desc,m desc,p desc ?

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

=> used to find ranks with in group for ex to find ranks with in
dept first we need to divide the table dept wise and apply
rank functions on each dept instead of applying it on whole table.

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

king 5000.00 10 1
clark 2450.00 10 2
miller 1300.00 10 3

ford 3000.00 20 1
scott 3000.00 20 1
jones 2975.00 20 2
adams 1100.00 20 3

14-oct-22

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

=> returns record numbers


=> row_number 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 SAL DESC) AS RNO
FROM EMP

7839 king 5000.00 1


7902 ford 3000.00 2
7788 scott 3000.00 3
7566 jones 2975.00 4
7698 blake 2850.00 5

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

AGGREGATE FUNCTIONS :-
----------------------

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

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

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

=> returns total

SUM(arg)

SELECT SUM(SAL) FROM EMP => 29025

=> round the total sal to hundreds ?

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

29000------------29050-----------------29100

=> after rounding display total sal with thousand seperator ?

SELECT
CONVERT(VARCHAR,ROUND(SUM(SAL),-2),1)
FROM EMP

=> display total sal paid to managers ?

SELECT SUM(SAL)
FROM EMP
WHERE JOB='MANAGER'

=> calculate total sal including comm ?

SELECT SUM(SAL+COMM) FROM EMP => 7800

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

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

AVG(arg)

SELECT AVG(sal) FROM emp => 2073.2142

=> round avg(sal) to lowest integer ?

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

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


can be applied only on numeric columns

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

=> returns no of rows in a table.

SELECT COUNT(*) FROM EMP => 14

=> display no of employees joined in 1981 year ?

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

=> display no of employees joined on sunday ?

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

SELECT COUNT(EMPNO) FROM EMP => 14

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

SELECT COUNT(DEPTNO) FROM EMP => 14

SELECT COUNT(DISTINCT DEPTNO) FROM EMP => 3 (after eliminating


duplicates)

NOTE :-

=> aggregate,window functions are not allowed in where clause


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

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

SELECT * FROM EMP


WHERE DENSE_RANK() OVER (ORDER BY SAL DESC) = 3 => ERROR

15-oct-22

date :- getdate,datepart,datename,dateadd,datediff,eomonth

string :- upper,lower,len,left,right,substring,charindex,
replicate,replace,translate

math :- power,sqrt,square,abs,sign,round,ceiling,floor

conv :- cast,convert

special :- isnull

analytical :- rank,dense_rank,row_number

aggregate :- min,max,sum,avg,count

SELECT col1,col2 FROM tabname

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

1 SELECT ename,max(sal) FROM emp => error


14 1

2 SELECT ename,ROUND(sal,0) FROM emp => executed


14 14

3 SELECT min(sal),max(sal) FROM emp => executed


1 1

4 SELECT ROUND(sal,0),max(sal) FROM emp => error


14 1

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

=> used to implement IF-THEN-ELSE


=> useful to return expressions 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 DNAME ?

if deptno=10 display ACCOUNTS


20 RESEARCH
30 SALES
OTHERS UNKNOWN

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

=> DISPLAY ENAME JOB ?

if job=CLERK display WORKER


MANAGER BOSS
PRESIDENT BIG BOSS
ELSE EMPLOYEE

=> increment employee salaries as follows ?

if job=CLERK incr sal by 10%


SALESMAN 15%
MANAGER 20%
others 5%

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

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

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

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

=> display ENAME SAL SALRANGE ?


if sal>3000 display Hisal
sal<3000 display Losal
otherwise Avgsal

SELECT ENAME,SAL,
CASE
WHEN SAL>3000 THEN 'Hisal'
WHEN SAL<3000 THEN 'Losal'
ELSE 'Avgsal'
END as SALRANGE
FROM EMP

=> Display SNO SNAME TOTAL AVG RESULT ?

STUDENT
sno sname s1 s2 s3
1 A 80 90 70
2 B 30 60 50

SELECT SNO,SNAME,
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 EMP

17-oct-22

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

=> GROUP BY clause 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 5000 10
2 B 4000 20 GROUP BY 10 8000
3 C 6000 30=====================> 20 9000
4 D 5000 20 30 6000
5 E 3000 10

detailed data summarized data

=> GROUP BY clause converts detailed data into summarized data


which is useful for data analysis.

syntax :-
---------

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

execution :-
----------

FROM
WHERE
GROUP BY
HAVING
SELECT
ORDER BY

=> display dept wise total salary ?

SELECT deptno,SUM(sal) as totsal


FROM emp
GROUP BY deptno

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

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

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

10
1 A 5000
5 E 3000

20
2 B 4000
4 D 5000

30
3 C 6000

SELECT deptno,SUM(sal) as totsal :-


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

10 8000
20 9000
30 6000

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

=> display no of employees joined in each month 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)

April 1
December 2
February 2
June 1
May 1
November 1
September 2

=> display depts having more than 3 employees working ?

SELECT deptno,COUNT(*)
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(*)
FROM emp
GROUP BY deptno
HAVING COUNT(*) > 3

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

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

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

10
1 A 5000
5 E 3000

20
2 B 4000
3 C 6000
4 D 5000
6 F 2000

HAVING COUNT(*) > 3 :-


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

20
2 B 4000
3 C 6000
4 D 5000
6 F 2000

SELECT deptno,COUNT(*) :-
--------------------------

20 4

18-oct-22

=> display job wise no of employees where job=clerk,manager and


no of employees > 3 ?

SELECT job,COUNT(*)
FROM emp
WHERE job IN ('clerk','manager')
GROUP BY job
HAVING COUNT(*) > 3

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

PERSONS
AADHARNO NAME GENDER AGE ADDR CITY STATE

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

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

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

1 selects specific rows selects specific groups

2 conditions applied conditions applied


before group by after group by

3 use where clause if use having clause


condition not if condition based
based on aggregate function on aggregate function

=> display dept wise and job wise total salary ?

SELECT deptno,job,SUM(sal) as totsal,COUNT(*) as cnt


FROM emp
GROUP BY deptno,job
ORDER BY deptno ASC

10 CLERK 1430.00 1
10 MANAGER 2940.00 1
10 PRESIDENT 5250.00 1

20 ANALYST 6300.00 2
20 CLERK 2090.00 2
20 MANAGER 3570.00 1

30 CLERK 1045.00 1
30 MANAGER 3420.00 1
30 SALESMAN 6440.00 4

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,COUNT(*) as cnt


FROM emp
GROUP BY ROLLUP(deptno,job)
ORDER BY deptno ASC

NULL NULL 32485.00 14 => GRAND TOTAL

10 CLERK 1430.00 1
10 MANAGER 2940.00 1
10 PRESIDENT 5250.00 1
10 NULL 9620.00 3 => SUBTOTAL

20 ANALYST 6300.00 2
20 CLERK 2090.00 2
20 MANAGER 3570.00 1
20 NULL 11960.00 5 => SUBTOTAL

CUBE :-
--------

=> displays subtotals for each group by column (deptno,job)


and also displays grand total.

SELECT deptno,job,SUM(sal) as totsal,COUNT(*) as cnt


FROM emp
GROUP BY CUBE(deptno,job)
ORDER BY deptno ASC,job ASC

NULL NULL 32485.00 14 => grand total

NULL ANALYST 6300.00 2 => job subtotal


NULL CLERK 4565.00 4 => job subtotal
NULL MANAGER 9930.00 3
NULL PRESIDENT 5250.00 1
NULL SALESMAN 6440.00 4

10 NULL 9620.00 3 => dept subtotal


10 CLERK 1430.00 1
10 MANAGER 2940.00 1
10 PRESIDENT 5250.00 1

20 NULL 11960.00 5 => dept subtotal


20 ANALYST 6300.00 2
20 CLERK 2090.00 2
20 MANAGER 3570.00 1

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

PERSONS
AADHARNO NAME GENDER AGE ADDR CITY STATE

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

SELECT state,gender,count(*)
FROM persons
GROUP BY CUBE(state,gender)
ORDER BY state ASC,gender ASC

NULL NULL 130

MALE ? => gender subtotal


FEMALE ? => gender subtotal

AP MALE ?
FEMALE ?
? => state subtotal

TS MALE ?
FEMALE ?
19-oct-22

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

=> this function accepts group by columns and returns subtotal


belongs to which group by column.

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 subtotal
FROM emp
GROUP BY CUBE(deptno,job)
ORDER BY deptno ASC,job ASC

summary :-

importance of group by
where vs having clause
rollup & cube
grouping_id

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

Integrity Constraints :-
------------------------

=> Integrity Constraints are the rules to maintain Data Integrity


i.e. Data Quality

=> used to prevent users from entering invalid data.

=> used to enforce rules like min bal must be 1000.

=> different integrity constraints in sql server

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
then it is called column level.

CREATE TABLE <tabname>


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

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

=> NOT NULL constraint doesn't accept null values.


=> a column declared with NOT NULL is called mandatory column.

example :-

CREATE TABLE emp22


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

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


INSERT INTO emp22 VALUES(101,'A')

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

=> UNIQUE constraint doesn't accept duplicates

example :-

CREATE TABLE cust


(
cid int,
cname varchar(10),
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.


=> PRIMARY KEY is the combination of UNIQUE & NOT NULL.

PRIMARY KEY = UNIQUE + NOT NULL

=> in DB tables one column must be there to uniquely identify the


records and that column must be declared with primary key.

example :-
-----------

CREATE TABLE emp33


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

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


INSERT INTO emp33 VALUES(100,'B',4000) => ERROR
INSERT INTO emp33 VALUES(NULL,'C',3000) => ERROR

=> because empid doesn't allow duplicates and nulls so using empid
we can uniquely identify the employees.

=> 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,
NAME VARCHAR(10) NOT NULL,
AADHARNO NUMERIC(12) UNIQUE NOT NULL,
PANNO CHAR(10) UNIQUE NOT NULL
)

20-oct-22

diff b/w unique & primary key ?

unique primary key

1 allows one null doesn't allow nulls

2 multiple columns only one column can b


can be declared declared with primary key
with unique

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

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

VEHICLE
VEHNO VNAME MODEL PRICE CHASSISNO

candidate keys :- vehno,chassisno


primary key :- vehno
secondary key :- chassisno
or
alternate key

=> while creating table secondary keys are declared with UNIQUE & NOT NULL.

CHECK :-
--------
=> use check constraint when rule based on condition.

CHECK(condition)

ex 1 :- sal must be min 3000

CREATE TABLE emp44


(
EMPID INT PRIMARY KEY,
ENAME VARCHAR(10) NOT NULL,
SAL MONEY CHECK(SAL>=3000)
)

INSERT INTO EMP44 VALUES(1,'A',1000) => ERROR


INSERT INTO EMP44 VALUES(2,'B',6000) => ACCEPTED
INSERT INTO EMP44 VALUES(3,'C',NULL) => ACCEPTED

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 VARCHAR2(10) CHECK(LEN(PWD)>=6)

ex 5 :- emailid must contain '@'


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

EMAILID VARCHAR2(30)
CHECK(EMAILID LIKE '%@%'
AND
(
EMAILID LIKE '%.COM'
OR
EMAILID LIKE '%.CO'
OR
EMAILID LIKE '%.IN'
))

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

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

PROJECTS
projid name duration cost client
100 A 5 YEARS 300 TATA MOTORS
101 B 4 YEARS 250 DBS BANK
102 C 3 YEARS 200 L&T

EMP
empid ename sal projid REFERENCES PROJECTS(PROJID)
1 K 4000 100
2 J 5000 101
3 D 3000 999 => INVALID
4 V 2000 100
5 M 3000 NULL

=> to establish relationship take primary key of one table and


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

=> values entered in foreign key column should match with values
entered in primary key column.

=> foreign key allows duplicates & nulls.

=> after declaring foreign key a relationship is established between


two tables called parent/child relationship.

=> PK table is parent and FK table is child.

CREATE TABLE projects


(
projid INT PRIMARY KEY,
pname VARCHAR2(10),
client VARCHAR2(20)
)

INSERT INTO projects VALUES(100,'A','TATA MOTORS')


INSERT INTO projects VALUES(101,'B','DBS BANK')

CREATE TABLE emp_proj


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

INSERT INTO emp_proj VALUES(1,'K',5000,100)


INSERT INTO emp_proj VALUES(2,'T',4000,999) => ERROR
INSERT INTO emp_proj VALUES(3,'J',3000,100) => ALLOWED
INSERT INTO emp_proj VALUES(4,'M',4000,NULL) => ALLOWED

Assignment :-

ACCOUNTS
ACCNO ACTYPE BAL

Rules :-
--------

1 accno should not be duplicate & null


2 actype must be 's' or 'c'
3 bal must be min 1000

TRANSACTIONS
TRID TTYPE TAMT TDATE ACCNO
Rules :-
-------

1 trid must be auto incremented


2 ttype must be 'w' or 'd'
3 tamt must be multiple of 100
4 tdate must be system date
5 accno should match with accounts table accno

write create table script ?

Types of Relationships :-
-------------------------

one to one (1:1)


one to many (1:m)
many to one (m:1)
many to many (m:n)

=> in sql server by default one to many relationship is created


between two tables.

=> To establish one to one (1:1) relationship between two tables


declare foreign key with unique constraint.

example :- (1:1)
----------

DEPT
DNO DNAME
10 HR
20 IT

MGR
MGRNO MNAME DNO REFERENCES DEPT(DNO) UNIQUE
1 A 10
2 B 20
3 C 10 => INVALID

=> in the above example one dept is managed by one manager and
one manager manages one dept so relationship between two
tables is 1:1

Many to Many :- (M:N)


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

=> by default sql server doesn't support many to many relationship

=> here many to many relationship is divided into 2 one to many


relationships.

example :-
----------

PRODUCTS CUSTOMERS
prodid pname price cid name addr
100 A 1000 10 X HYD
101 B 2000 11 K HYD
=> relationship between products and customer is many to many
because one product can be purchased by many customers and
one customer can purchase many products.

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

SALES
DATEID PRODID CUSTID QTY AMOUNT
15/ 100 10
15/ 100 11
15/ 101 10

22-oct-22

ER MODEL RELATIONAL MODEL

1 used in design used in development

2 entities tables

3 attributes fields

4 relationships foreign keys

relational model for the above er model :-


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

BANK
CCODE NAME ADDR
-----

BRANCH
BRANCH_ID NAME ADDR CCODE(FK)
---------

LOANS
LOAN_ID LOAN_TYPE AMOUNT BRANCH_ID(FK) CUSTID(FK)
-------

ACCOUNTS
ACCNO ACTYPE BAL BRANCH_ID(FK) CUSTID(FK)
------

CUSTOMERS
CUSTID NAME PHONE ADDR
------

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 emp66


(
empno INT,
hiredate DATE DEFAULT GETDATE()
)

INSERT INTO emp66(empno) VALUES(100)


INSERT INTO emp66 VALUES(101,'2022-01-01')
INSERT INTO emp66 VALUES(102,null)

SELECT * FROM emp66

empno hiredate
100 2022-10-22
101 2022-01-01
102 NULL

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

=> if constraints are declared after declaring all columns then it


is called table level.

CREATE TABLE <tabname>


(
COL1 DATATYPE(SIZE),
----------------,
CONSTRAINT(COL1,COL2,--)
)

=> use table level to declare constraint for multiple


or combination of columns .

Declaring check constraint at table level :-


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

PRODUCTS
prodid pname mfd_dt exp_dt
100 A 2022-10-22 2022-01-01 => INVALID

RULE :- exp_dt > mfd_dt

CREATE TABLE products


(
prodid INT PRIMARY KEY,
pname VARCHAR(10),
mfd_dt DATE ,
exp_dt DATE ,
CHECK(exp_dt>mfd_dt)
)

composite primary key :-


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

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


called composite primary key.

=> in composite primary key combination should not be duplicate

=> in some tables we may not be able to uniquely identify


by using single column and we need combination of columns
to uniquely identify and that combiation should be
declared primary key at table level.

example :-

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

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

=> in the above example sid,cid combination uniquely identifies


records so declare this combination as primary key at
table level.

CREATE TABLE student


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

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

CREATE TABLE course


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

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

CREATE TABLE registrations


(
sid INT REFERENES 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

25-oct-22
composite foreign key :-
------------------------

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


composite foreign key.

=> a composite foreign key references composite primary key.

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

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


registrations table priamry key i.e. SID,CID combination.
so declare this combination as foreign key at table level.

CREATE TABLE certificates


(
certno INT PRIMARY KEY,
doi DATE,
sid INT,
cid INT,
FOREIGN KEY(sid,cid) REFERENCES REGISTRATIONS(sid,cid)
)

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

Adding constraints to existing table :-


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

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

CREATE TABLE emp88


(
empno INT,
ename VARCHAR(10),
sal MONEY,
dno INT
)
Adding check constraint :-
---------------------------

=> add check constaint with condition sal>=3000 ?

ALTER TABLE EMP88


ADD CHECK(SAL>=3000)

ALTER TABLE EMP


ADD CHECK(SAL>=3000) => ERROR

=> because 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 "WITH NOCHECK" then sql server
will not validate existing data and it validates new data.

ALTER TABLE EMP


WITH NOCHECK ADD CHECK(SAL>=3000)

Adding primary key :-


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

=> primary key can be added only to not null column but cannot be
added nullable column.

=> to add primary key

1 change the column to not null


2 add primary key

=> add primary key to empno ?

ALTER TABLE emp88


ALTER COLUMN empno INT NOT NULL

ALTER TABLE emp88


ADD PRIMARY KEY(empno)

Adding foreign key :-


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

=> add foreign key to dno that references dept table primary key
i.e. deptno ?

ALTER TABLE EMP88


ADD FOREIGN KEY(DNO) REFERENCES DEPT(DEPTNO) ;

changing column from NULL to NOT NULL :-


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

ALTER TABLE EMP88


ALTER COLUMN ENAME VARCHAR(10) NOT NULL
26-oct-22

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

ALTER TABLE <TABNAME>


DROP CONSTRAINT <NAME>

EX :-

=> drop check constraint in emp88 table ?

ALTER TABLE EMP88


DROP CONSTRAINT CK__emp88__sal__6477ECF3

=> drop primary key in dept table ?

ALTER TABLE DEPT


DROP CONSTRAINT PK__DEPT__E0EB08D7B829E841 => ERROR

DROP TABLE DEPT => ERROR

TRUNCATE TABLE DEPT => ERROR

NOTE :- primary key cannot be dropped if referenced by some fk


primary key table cannot be dropped if referenced by some fk
primary key table cannot be truncated if referenced by some fk

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

ON DELETE NO ACTION (DEFAULT)


ON DELETE CASCADE
ON DELETE SET NULL
ON DELETE SET DEFAULT

=> these rules are declared with foreign key.


=> these rules 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 dept99


(
dno INT PRIMARY KEY,
dname VARCHAR(10) UNIQUE NOT NULL
)

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

CREATE TABLE emp99


(
empno INT PRIMARY KEY,
dno INT REFERENCES dept99(dno)
)
INSERT INTO emp99 VALUES(1,10),(2,10)

DELETE FROM DEPT99 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 :-
--------------------

=> if parent row is deleted then it is deleted along with


child rows.

CREATE TABLE dept99


(
dno INT PRIMARY KEY,
dname VARCHAR(10) UNIQUE NOT NULL
)

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

CREATE TABLE emp99


(
empno INT PRIMARY KEY,
dno INT REFERENCES dept99(dno)
ON DELETE CASCADE
)

INSERT INTO emp99 VALUES(1,10),(2,10)

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

SELECT * FROM EMP99 => NO ROWS

scenario :-

ACCOUNTS
ACCNO ACTYPE BAL
100 S 10000

TRANSACTIONS
TRID TTYPE TDATE TAMT ACCNO REFERENCES ACCOUNTS(ACCNO)
1 W ? 2000 100 ON DELETE CASCADE
2 D ? 5000 100

RULE :- when account is closed then along with account delete


transactions.
ON DELETE SET NULL :-
---------------------

=> if parent row deleted then it is deleted without deleting


child rows but foreign key will be set to null

CREATE TABLE dept99


(
dno INT PRIMARY KEY,
dname VARCHAR(10) UNIQUE NOT NULL
)

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

CREATE TABLE emp99


(
empno INT PRIMARY KEY,
dno INT REFERENCES dept99(dno)
ON DELETE SET NULL
)

INSERT INTO emp99 VALUES(1,10),(2,10)

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

SELECT * FROM EMP99

EMPNO DNO
1 NULL
2 NULL

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

PROJECTS
projid pname duration
100
101

EMP
empid name projid
1 100
2 100

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

ON DELETE SET DEFAULT :-


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

=> if parent row deleted then it is deleted without deleting


child rows but foreign key will be set to default value.

CREATE TABLE dept99


(
dno INT PRIMARY KEY,
dname VARCHAR(10) UNIQUE NOT NULL
)

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


CREATE TABLE emp99
(
empno INT PRIMARY KEY,
dno INT DEFAULT 20
REFERENCES dept99(dno)
ON DELETE SET DEFAULT
)

INSERT INTO emp99 VALUES(1,10),(2,10)

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

SELECT * FROM EMP99

EMPNO DNO
1 20
2 20

update rules :-
---------------

ON UPDATE NO ACTION
ON UPDATE CASCADE
ON UPDATE SET NULL
ON UPDATE SET DEFAULT

=> update rules specifies how foreign key value is


affected if we update primary key value.

CREATE TABLE dept99


(
dno INT PRIMARY KEY,
dname VARCHAR(10) UNIQUE NOT NULL
)

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

CREATE TABLE emp99


(
empno INT PRIMARY KEY,
dno INT REFERENCES dept99(dno)
ON DELETE SET NULL
ON UPDATE CASCADE
)

INSERT INTO emp99 VALUES(1,10),(2,10)

summary :-

=> importance of constraints


=> types of constraints
=> declaring constraints
column level
table level
=> relationship types
=> adding constraints
=> droping constraints
=> delete rules & update rules
===================================================================

27-oct-22

JOINS :-
--------

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

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


data stored in multiple tables we need to join those tables.

example :-

ORDERS CUSTOMERS
ordid orddt deldt cid cid name addr
1000 ? ? 10 10 A HYD
1001 11 11 B HYD
1002 12 12 C HYD

output :-

ordid orddt deldt name addr


1000 ? ? A HYD
1001 B HYD

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

1 Inner join / Equi Join


2 Outer Join
Left
Right
Full
3 Non Equi Join
4 Self 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.

=> Inner Join is performed on common field with same datatype.

SELECT columns
FROM tab1 INNER JOIN tab2
ON join condition

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

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

table1.commonfield = table2.commonfield
example :-

EMP DEPT
EMPNO ENAME SAL DEPTNO DEPTNO DNAME LOC
1 A 3000 10 10 ACCTS NEW YORK
2 B 4000 20 20 RESEARCH
3 C 5000 30 30 SALES
4 D 3000 20 40 OPERATIONS
5 E 2000 NULL

=> display ENAME SAL DNAME LOC ?


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

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

A 3000 ACCTS ???


B 4000 RESEARCH ???
C 5000 SALES ???
D 3000 RESEARCH ???

NOTE :-
-------

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

1 to avoid ambiguity
2 for faster execution

SELECT e.ename,e.sal,d.deptno,d.dname,d.loc as city


FROM emp e INNER JOIN dept d
ON e.deptno = d.deptno

=> display employee details working at NEW YORK loc ?

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

28-oct-22

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.

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
FROM emp e INNER JOIN dept d
ON e.deptno = d.deptno
INNER JOIN locations l
ON d.locid = l.locid
INNER JOIN countries c
ON l.country_id = c.country_id

outer join :-
-------------

=> inner join returns only matching records but won't return
unmatched records but to display unmatched records perform
outer join.

EMP DEPT
EMPNO ENAME SAL DEPTNO DEPTNO DNAME LOC
1 A 3000 10 10 ACCTS NEW YORK
2 B 4000 20 20 RESEARCH
3 C 5000 30 30 SALES
4 D 3000 20 40 OPERATIONS => unmatched
5 E 2000 NULL => unmatched

=> outer join is 3 types

1 LEFT JOIN
2 RIGHT JOIN
3 FULL JOIN

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

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

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

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

A ACCT
B RESEARCH
C SALES
D ACCT
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 e RIGHT JOIN dept d
ON e.deptno = d.deptno

A ACCTS
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 e FULL JOIN dept d
ON e.deptno = d.deptno

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

Displaying unmatched records :-


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

left side table :-


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

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

E NULL

right side table :-


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

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

NULL OPERATIONS

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

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

E NULL
NULL OPERATIONS

29-oct-22

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 1000 2 1001 2000
3 C 5000 3 2001 3000
4 D 2000 4 3001 4000
5 E 2500 5 4001 9999

=> DISPLAY ENAME SAL GRADE ?

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

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

=> display grade 3 employee list ?

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

A 3000 3
E 2500 3

=> display ENAME DNAME GRADE ?


----- ------ ------
EMP DEPT SALGRADE

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

execution :-

STEP 1 :- emp join salgrade

EMP SALGRADE
EMPNO ENAME DEPTNO SAL GRADE LOSAL HISAL
1 A 10 3000 1 700 1000
2 B 20 1000 2 1001 2000
3 C 30 5000 3 2001 3000
4 3001 4000
5 4001 9999
result :-

EMPO ENAME DEPTNO SAL GRADE


1 A 10 3000 3
2 B 20 1000 1
3 C 30 5000 5

STEP 2 :- (emp join salgrade) inner join dept

DEPT
EMPO ENAME DEPTNO SAL GRADE DEPTNO DNAME LOC
1 A 10 3000 3 10 ACCTS
2 B 20 1000 1 20 RESEARCH
3 C 30 5000 5 30 SALES

result :-

1 A 10 3000 3 ACCTS
2 B 20 1000 1 RESEARCH
3 C 30 5000 5 SALES

STEP 3 :- (SELECT)

A ACCTS 3
B RESEARCH 1
C SALES 5

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

=> joining a table to itself is called self join

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

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

FROM EMP X JOIN EMP Y

EMP X EMP Y
EMPNO ENAME MGR EMPNO ENAME MGR
1 A NULL 1 A NULL
2 B 1 2 B 1
3 C 1 3 C 1
4 D 2 4 D 2

=> display ENAME MGRNAME ?

SELECT X.ENAME,Y.ENAME AS MGRNAME


FROM EMP X JOIN EMP Y
ON X.MGR = Y.EMPNO

B A
C A
D B

31-oct-22

=> display employees reporting to blake ?

SELECT X.ENAME,Y.ENAME AS MGRNAME


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

=> display blake's manager name ?

SELECT X.ENAME,Y.ENAME AS MGRNAME


FROM EMP X JOIN EMP Y
ON X.MGR = Y.EMPNO
WHERE x.ENAME='BLAKE'

=> display employees earning more than their manager ?

SELECT X.ENAME,Y.ENAME AS MGRNAME


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

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

TEAMS
ID COUNTRY
1 IND
2 AUS
3 NZ

write the query to display following output ?

IND VS AUS
IND VS NZ
AUS VS NZ

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

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

IND IND IND AUS AUS IND IND AUS


AUS AUS IND NZ NZ IND IND NZ
NZ NZ AUS IND NZ AUS AUS NZ
AUS NZ
NZ IND
NZ AUS
SELECT A.COUNTRY + ' VS ' + B.COUNTRY
FROM TEAMS A JOIN TEAMS B
ON A.ID < .BID

CROSS JOIN / CARTESIAN JOIN :-


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

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

A = 1,2
B = 3,4

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

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

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

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

GROUP & JOIN :-


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

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

SELECT d.dname,SUM(e.sal) as totsal


FROM emp e INNER JOIN dept d
ON e.deptno = d.deptno
GROUP BY d.dname

FROM :-

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

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

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

GROUP BY d.dname :-
-------------------

ACCTS
1 A 3000
5 E 2000
RESEARCH
2 B 4000
4 D 3000

SALES
3 C 5000

SELECT d.dname,SUM(e.sal) as totsal :-


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

ACCTS 5000
RESEARCH 7000
SALES 5000

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

SALES
DATEID PRODID CUSTID QTY AMOUNT
2022-10-31 100 10 1 1000

PRODUCTS
PRODID PNAME PRICE CATEGORY
100 AAA 1000 ELECTRONICS

CUSTOMERS
CUSTID NAME ADDR COUNTRY
10 KK HYD IND

=> display quarter wise total amount in year 2022 ?


=> display category wise total amount ?
=> display country wise total amount ?
=> display country wise,category wise,year 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 server set operations performed between set of rows


return by two queries.

SELECT STATEMENT 1
UNION/UNION ALL/INTERSECT/EXCEPT
SELECT STATEMENT 2
01-NOV-22

Rules :-

1 both queries must return same no of columns


2 corresponding columns datatype must be same

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

=> combines rows return by two queries


=> eliminates duplicates
=> sorts result

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

SELECT job FROM emp WHERE deptno=20


UNION
SELECT job FROM emp WHERE deptno=30

ANALYST
CLERK
MANAGER
SALESMAN

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

UNION JOIN

1 horizontal merge vertical merge

2 combines rows combines columns

3 performed between can be performed between


two similar structures two dissimilar structures

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

EMP_US
EMPNO ENAME DNO
100 A 10
101 B 20
DEPT
EMP_IND DNO DNAME
EMPNO ENAME DNO 10 HR
200 K 10 20 IT
201 X 20

=> total employees list ?

SELECT * FROM EMP_US


UNION
SELECT * FROM EMP_IND

=> employee list working at US loc with dept details ?

SELECT E.*,D.*
FROM EMP_US E INNER JOIN DEPT D
ON E.DNO = D.DNO

=> total employee list with dept details ?

SELECT E.*,D.*
FROM EMP_US E INNER JOIN DEPT D
ON E.DNO = D.DNO
UNION
SELECT E.*,D.*
FROM EMP_IND E INNER JOIN DEPT D
ON E.DNO = D.DNO

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

=> combines rows return by two queries


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

SELECT job FROM emp WHERE deptno = 20


UNION ALL
SELECT job FROM emp WHERE deptno = 30

CLERK
MANAGER
ANALYST
CLERK
ANALYST
SALESMAN
SALESMAN
SALESMAN
MANAGER
SALESMAN
CLERK

=> diff b/w UNION & UNION ALL ?

UNION UNION ALL

1 eliminates duplicates duplicates are not eliminated

2 result is sorted result is not sorted


3 slower faster

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

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

SELECT job FROM emp WHERE deptno = 20


INTERSECT
SELECT job FROM emp WHERE deptno = 30

CLERK
MANAGER

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

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

SELECT job FROM emp WHERE deptno = 20


EXCEPT
SELECT job FROM emp WHERE deptno = 30

ANALYST

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

=> display first day of the year ?

SELECT DATEADD(yy, datediff(yy,0,getdate()), 0)

0 means 1900-01-01

DATEADD(interval,int,date)

SUBQUERIES / NESTED QUERIES :-


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

=> a query in another query is called subquery or nested query.


=> one query is called inner/child/sub query.
=> other query is called outer/parent/main query.
=> first sql server executes inner query then it executes outer query
and result of inner query is input to outer query.
=> use subquery when where cond based on unknown value.

Types of subqueries :-
---------------------

1 SINGLE ROW SUBQUERIES


2 MULTI ROW SUBQUERIES
3 CO-RELATED SUBQUERIES
4 DERIVED TABLES
5 SCALAR SUBQUERIES
single row subqueries :-
-------------------------

=> if inner query returns one value then it is called single row subquery

SELECT columns
FROM tabname
WHERE colname OP (SELECT STATEMENT)

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

03-nov-22

co-related subqueries :-
-------------------------

=> if inner query refers values of outer query then it is called


co-related subquery.

=> here 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 every row


return by outer query.

steps :-
--------

1 returns a row from outer query


2 pass value to inner query
3 executes inner query
4 send the output to outer query
5 executes outer query where cond

example 1 :-
----------

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

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

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

1 A 3000 10 3000 > (where deptno = 10) 4500 FALSE


2 B 5000 20 5000 > (where deptno = 20) 4000 TRUE
3 C 4000 30 4000 > (where deptno = 30) 4000 FALSE
4 D 3000 20 3000 > (where deptno = 20) 4000 FALSE
5 E 6000 10 6000 > (where deptno = 10) 4500 TRUE
example 2 :-

=> employees earning max sal in their dept ?

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

EMPNO ENAME SAL DEPTNO


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

example 3 :-
-------------

=> display top 3 max salaries ?

EMP A EMP B
SAL SAL
5000 5000
1000 1000
3000 3000
2000 2000
4000 4000

SELECT DISTINCT A.SAL


FROM EMP A
WHERE 3 > (SELECT COUNT(DISTINCT B.SAL)
FROM EMP B
WHERE A.SAL < B.SAL)
ORDER BY SAL DESC

5000 3 > (0) TRUE


1000 3 > (4) FALSE
3000 3 > (2) TRUE
2000 3 > (3) FALSE
4000 3 > (1) TRUE

=> display 3rd max salary ?

SELECT DISTINCT A.SAL


FROM EMP A
WHERE (3-1) = (SELECT COUNT(DISTINCT B.SAL)
FROM EMP 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) <alias>
WHERE cond

=> subquery output acts like a table for outer query

=> derived tables are used in following scenarios

1 to control order of execution of clauses


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

04-nov-22

controlling order of execution :-


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

=> by default sql sever executes the clauses in the following order

FROM
WHERE
GROUP BY
HAVING
SELECT
ORDER BY

=> use derived tables to control this order of execution

example 1 :-
-------------

=> display ENAME ANNUAL SALARY ?

SELECT ename,sal*12 as annsal FROM emp

above query returns annual salaries of all the employees


but to display employees whose annual salary > 20000 then

SELECT ename,sal*12 as annsal


FROM emp
WHERE annsal > 20000 => ERROR

column alias cannot be used in where clause because where


clause is executed before select , to overcome this use
derived table

SELECT *
FROM (SELECT ename,sal*12 as annsal FROM emp) AS E
WHERE annsal>20000

example 2 :-
------------

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

SELECT 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 ENAME,SAL,
DENSE_RANK() OVER (ORDER BY SAL DESC) AS RNK
FROM EMP
WHERE rnk<=5 => ERROR

SELECT *
FROM (SELECT ENAME,SAL,
DENSE_RANK() OVER (ORDER BY SAL DESC) AS RNK
FROM EMP ) AS E
WHERE RNK<=5

=> display top 5 max salaries ?

SELECT DISTINCT SAL


FROM (SELECT ENAME,SAL,
DENSE_RANK() OVER (ORDER BY SAL DESC) AS RNK
FROM EMP ) AS E
WHERE RNK<=5
ORDER BY SAL DESC

WHERE rnk=5 => display 5th max salary

example 3 :-

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

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. To overcome this use CTEs.

CTE :-
-------

=> CTE stands for common table expression , It is a named query


that can be referenced in another query like SELECT/INSERT/UPDATE/
DELETE

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


outer query can be SELECT/INSERT/UPDATE/DELETE

WITH <name>
AS
(SELECT STATEMENT)
SELECT/INSERT/UPDATE/DELETE

Example :-

=> delete first 5 rows from emp ?

WITH E
AS
(SELECT empno,ename,
ROW_NUMBER() OVER (ORDER BY empno ASC) as rno
FROM emp)
DELETE FROM E WHERE rno<=5

05-nov-22

=> delete duplicate records ?

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

step 1 :-

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

1 A 5000 1
1 A 5000 2

2 B 6000 1
2 B 6000 2

3 C 7000 1

STEP 2 :- delete the records whose rno > 1

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

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

1
T1
AMT
1000
-500
2000
-1000
3000
-800

OUTPUT :-

POS NEG
1000 -500
2000 -1000
3000 -800

2
T1 T2
F1 C1
1 A
2 B
3 C

OUTPUT :-

1 A
2 B
3 C

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

=> subqueries in SELECT clause are called scalar subqueries

SELECT (SELECT STATEMENT),(SELECT STATEMENT),---


FROM TABNAME
WHERE COND

=> subquery output acts like a column for outer query

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

example 1 :-

SELECT COUNT(*) FROM EMP => 9


SELECT COUNT(*) FROM DEPT => 4

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


(SELECT COUNT(*) FROM DEPT) AS DEPT

EMP DEPT
9 4
example 2 :-

D10 D20 D30


? ? ? => total salary

SELECT (SELECT SUM(SAL) FROM EMP WHERE DEPTNO=10) AS D10,


(SELECT SUM(SAL) FROM EMP WHERE DEPTNO=20) AS D20,
(SELECT SUM(SAL) FROM EMP WHERE DEPTNO=30) AS D30

D10 D20 D30


8750.00 7100.00 5300.00

example 3 :-

=> display dept wise total salary ?

SELECT DEPTNO,SUM(SAL) AS DEPT_TOTSAL


FROM EMP
GROUP BY DEPTNO

10 8750
20 7100
30 5300

=> display DEPTNO DEPT_TOTSAL TOTSAL ?

SELECT DEPTNO,SUM(SAL) AS DEPT_TOTSAL,


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

10 8750 21150
20 7100 21150
30 5300 21150

=> display DEPTNO DEPT_TOTSAL TOTSAL PCT ?

PCT = PERCENTAGE = (DEPT_TOTSAL/TOTSAL) * 100

SELECT DEPTNO,SUM(SAL) AS DEPT_TOTSAL,


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

10 8750.00 21150.00 41.000000


20 7100.00 21150.00 34.000000
30 5300.00 21150.00 25.000000

Question :-
--------

PRODUCTS
prodid pname price category brand

SALES
dateid prodid custid qty amount
OUTPUT :-

CATEGORY CAT_TOTAL_AMT TOTAL_AMT PCT


ELECTRONICS 20 100
MENS 10 100
WOMENS 20 100

07-nov-22

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

=> used to convert rows into columns


=> used for cross tabulation
=> used to display data in matrix form

example :-

10 20 30

ANALYST ?? ?? ??

CLERK ?? ?? ??

MANAGER ?? ?? ??

SALESMAN ?? ?? ??

syntax :-

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

example :-

SELECT *
FROM (SELECT deptno,job,sal FROM emp) AS E
PIVOT
(
SUM(sal) FOR deptno IN ([10],[20],[30])
) AS PIVOT_EXPR
ORDER BY job ASC

example 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_EXPR
ORDER BY YEAR ASC

example 3 :-

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

output :-

SNO SNAME MAT PHY CHE


1 A 80 50 60
2 B 70 40 50

SELECT *
FROM STUDENT
PIVOT
(
SUM(MARKS) FOR SUBJECT IN ([MAT],[PHY],[CHE]))
) AS PIVOT_EXPR
ORDER BY SNO ASC

UNPIVOT operator :-
--------------------

=> reverse of PIVOT is called UNPIVOT operator.


=> converts columns into rows

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

OUTPUT :-

SNO SNAME SUBJECT MARKS


1 A MAT 80
1 A PHY 90
1 A CHE 70
2 B MAT 60
2 B PHY 50
2 B CHE 70

SELECT SNO,SNAME,SUBJECT,MARKS
FROM STUDENT
UNPIVOT
(
MARKS FOR SUBJECT IN ([MAT],[PHY],[CHE])
) AS UNPIVOT_EXPR
ORDER BY SNO ASC

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

creating a new table from existing table :- (replica)


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

SELECT columns/* INTO <new-tabname>


FROM <old-tabname>
WHERE cond

=> the new table is created with rows and columns return by query

example 1 :- (copying whole table)

SELECT * INTO emp10


FROM emp

example 2 :- (copying specific rows & cols)

SELECT empno,ename,job,sal INTO emp11


FROM emp
WHERE deptno IN (10,20)

example 3 :- (copy only structure(cols) but not data(rows))

SELECT * INTO emp12


FROM emp
WHERE 1=2

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

=> command used to merge data into a table.


=> it is the combination of insert,update and delete.
=> widely used in ETL applications.
=> used to manage replicas.

E => EXTRACT
T => TRANSFORM
L => LOAD

syntax :-

MERGE INTO <TARGET-TABLE> <ALIAS>


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

08-nov-22

example :-

step 1 :- create source table

CUSTS
CID NAME ADDR
1 A HYD
2 B MUM

step 2 :- create replica for custs

SELECT * INTO CUSTT FROM CUSTS

CUSTT
CID NAME ADDR
1 A HYD
2 B MUM

step 3 :- modify the source table

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

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

CUSTS
CID NAME ADDR
1 A BLR => UPDATED
2 B MUM
3 C DEL => INSERTED

step 4 :- replicate changes to custt

MERGE INTO CUSTT AS T


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

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

DB SECURITY :-
--------------

1 LOGINS => provides security at server level


2 USERS => provides security at db level
3 PRIVILEGES => provide security at table level
4 VIEWS => provides security at row & col level
09-nov-22

DB OBJECTS :-
-------------

TABLES
VIEWS
SYNONYMS
SEQUENCES
INDEXES

PROCEDURES
FUNCTIONS
TRIGGERS

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

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

=> views are created

1 for security
2 to reduce complexity

=> views provides another level of security by granting specific


rows & columns to users.

=> views are 2 types

1 simple views
2 complex views

simple views :-
----------------

=> if view created on single table then it is called simple view

CREATE VIEW <NAME>


AS
SELECT STATEMENT

example :-

CREATE VIEW V1
AS
SELECT EMPNO,ENAME,JOB,DEPTNO FROM EMP

=> when above command is executed 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='SALESMAN' WHERE EMPNO=7698

3 UPDATE V1 SET SAL=4000 WHERE EMPNO=7698 => 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

=> user "VIJAY" can access only the employees belongs to 20th dept

complex views :-
-----------------

=> a view said to be complex view

1 if based on multiple tables (joins)


2 if query contains group by clause
distinct clause
aggregate functions
set operators
subqueries

=> with the help of views complex queries are converted into simple
queries

Example 1 :-

CREATE VIEW CV1


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

=> after creating view whenever we want data from emp & dept tables
instead of writing join query write the simple query as follows
SELECT * FROM CV1

Example 2 :-

CREATE VIEW CV2


AS
SELECT D.DNAME,MIN(E.SAL) AS MINSAL,
MAX(E.SAL) AS MAXSAL,
SUM(E.SAL) AS TOTSAL,
AVG(E.SAL) AS AVGSAL,
COUNT(*) AS CNT
FROM EMP E INNER JOIN DEPT D
ON E.DEPTNO = D.DEPTNO
GROUP BY D.DNAME

=> after creating view whenever we want dept wise summary

SELECT * FROM CV2

Display list of tables created by user ?

SELECT * FROM INFORMATION_SCHEMA.TABLES

Display list of views created by user ?

SELECT * FROM INFORMATION_SCHEMA.VIEWS

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

DROP VIEW V1

=> if we drop base table what about views created on base table ?

ans :- views are not dropped but views cannot be queried

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

=> if view created with "SCHEMABINDING" then sql server will not
users to drop base table if any view exists on the base table.

Rules :-
--------

1 '*' is not allowed in schemabinding.


2 tablename should be prefixed with schemaname.

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

DROP TABLE DEPT => ERROR

10-NOV-22
SYNONYMS :-
------------

=> a synonym is another name or alternative name for a table or view

=> if tablename/viewname is lengthy then we can give a simple


and short name to the table/view called synonym and instead
of using tablename we can use synonym name.

CREATE SYNONYM <NAME> FOR <TABNAME>/<VIEWNAME>

EX :- CREATE SYNONYM E FOR EMP

=> after creating synonym instead of using tablename we can use


synonym name in SELECT/INSERT/UPDATE/DELETE queries.

1 SELECT * FROM E

2 UPDATE E SET COMM=500 WHERE EMPNO=7369

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

CREATE SYNONYM E FOR EMP

SELECT * FROM EMP AS E

SP_RENAME 'EMP','E'

=> diff b/w synonym and alias ?

SYNONYM ALIAS

1 permanent not permanent

2 stored in db not stored in db

3 scope of the scope of the alias


synonym is upto is upto the query
the schema in which it is declared

=> display list of synonyms created by user ?

SELECT NAME,BASE_OBJECT_NAME FROM SYS.SYNONYMS

Droping synonym :-
----------------

DROP SYNONYM E

SEQUENCES :-
-------------

=> sequence is also a db object created to generate sequence numbers


=> sequence can be used to auto increment column values.

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

CREATE TABLE student


(
sid INT,
sname VARCHAR(10)
)

=> use above sequence s1 to generate values for sid ?

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 NAME
1 A
2 B
3 C
4 D
5 E

example 2 :- (calling sequence in update command)

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

INVOICE
INVNO INVDT
NIT/1122/1 2022-11-10
/2

CREATE TABLE INVOICE


(
INVNO VARCHAR(20),
INVDT DATETIME
)

CREATE SEQUENCE S3
START WITH 1
INCREMENT BY 1
MAXVALUE 9999

INSERT INTO INVOICE VALUES('NIT/' +


FORMAT(GETDATE(),'MMyy') + '/' +
CAST(NEXT VALUE FOR S3 AS VARCHAR),GETDATE())

SELECT * FROM INVOICE

INVNO INVDT
NIT/1122/1 2022-11-10 08:37:44.010
NIT/1122/2 2022-11-10 08:37:46.987
NIT/1122/3 2022-11-10 08:37:48.450

11-nov-22

CYCLE/NOCYCLE :-
----------------

=> by default sequence is created with NOCYCLE.

=> if sequence created with NOCYCLE then it 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 to max and after reaching max then it
reset to min

CREATE SEQUENCE S5
START WITH 1
INCREMENT BY 1
MAXVALUE 5
MINVALUE 1
CYCLE
CACHE 4

SELECT NEXT VALUE FOR S5

CACHE size :-
--------------

CREATE SEQUENCE S10


START WITH 1
INCREMENT BY 1
MAXVALUE 1000
MINVALUE 1
CYCLE
CACHE 100

=> sql server preallocates 100 values in cache memory , so when


we call "next value for seq" then sql server goes to cache
memory and gets the value and return that value from cache memory.
so no of requests going to db are reduced and performance is
improved.

=> list of sequences created by user ?

SELECT * FROM INFORMATION_SCHEMA.SEQUENCES

how to change sequence parameters :-


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

ALTER SEQUENCE S3 MAXVALUE 100

how to reset sequence manually :-


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

ALTER SEQUENCE S1 RESTART WITH 1

Droping sequence :-
------------------

DROP SEQUENCE S1

INDEXES :-
-----------

=> index is also a db object created to improve the performance


data accessing

=> index improves performance of search operation.

=> index in db is similar to index in textbook. In textbook using


index a particular topic can be located fastly and 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 used in join operation

Types of Indexes :-
-------------------

1 Non Clustered
simple
composite
unique
2 Clustered

simple non clustered index :-


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

=> if index created on single column then it is called simple index

syn :- CREATE INDEX <NAME> ON <TABNAME>(COLNAME)

EX :- CREATE INDEX I1 ON EMP(SAL)


EMP 3000
SAL
1000
5000 2000 4000
3000
2000 1000 * 2500 * 4000 * 5000 *
1500 1500 * 3000 *,*
3000 2000 *
4000
2500

=> when we submit query to sql server it uses following 2 methods


to locate the record

1 TABLE SCAN
2 INDEX SCAN

=> in table scan sql server scans complete table i.e. each and every
record but in index scan on avg sql server scans only half of the
table.

SELECT * FROM EMP (TABLE SCAN)


SELECT * FROM EMP WHERE ENAME='BLAKE' (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)

12-nov-22

composite index :-
------------------

=> if index created on multiple columns then it is called composite


index.

CREATE INDEX I2 ON EMP(DEPTNO,JOB)

EMP
DEPTNO JOB
20 CLERK
30 SALESMAN
10 MANAGER
20 ANALYST
30 SALESMAN
10 CLERK
20 CLERK
30 CLERK

20

10 30

10 CLERK * 20 ANALYST * 30 CLERK *


10 MANAGER * 20 CLERK *,* 30 SALESMAN *,*

SELECT * FROM EMP WHERE DEPTNO = 20 (INDEX SCAN)


SELECT * FROM EMP WHERE DEPTNO = 20 AND JOB = 'CLERK' (INDEX SCAN)
SELECT * FROM EMP WHERE JOB='CLERK' (TABLE SCAN)
NOTE :- sql server uses above index when where condition based
on leading column of the index i.e. deptno.

UNIQUE INDEX :-
----------------

=> unique index doesn't allow duplicate values into the column
on which index is created.

EX :- CREATE UNIQUE INDEX I3 ON EMP(ENAME)

G Q

ADAMS * JAMES * MARTIN * SCOTT *


ALLEN * JONES * MILLER * SMITH *
BLAKE *

SELECT * FROM EMP WHERE ENAME='BLAKE'

INSERT INTO EMP(EMPNO,ENAME,SAL)


VALUES(777,'BLAKE',4000) => ERROR

what are the diff methods to enforce uniqueness ?

1 declare primary key/unqiue constraint


2 create unique index

NOTE :- primary key/unique columns are automatically indexed by


sql server and it creates 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 cluster index stores pointers to actual records where as


clsutered index stores actual records.

=> in non clustered index order of the records in table and


order of the records in index will not be same where as
in clustered index order will be same.

example :-

CREATE TABLE CUST


(
CID INT,
CNAME VARCHAR(10)
)

CREATE CLUSTERED INDEX I10 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

SELECT * FROM CUST => sql server goes to clustered index


and access records from left to right

10 A
40 C
60 D
80 B

SELECT * FROM CUST WHERE CID=40

NOTE :-

=> only one clustered index allowed per table.


=> by default sql server creates clustered index on primary key column

diff b/w non clustered & clustered indexes ?

non clustered clustered

1 stores pointers to actual records stores actual records

2 order of the records in table order will be same.


and order of the records in
index may not be same.

3 requires two lookups to requires one lookup


find desired record to find desired record

4 needs extra storage doesn't need extra storage

5 sql server allows only one clustered index


999 non clustered allowed per table
indexes per table

6 created on non sql server implicitly


primary key columns creates clustered index
on primary key column

how to see the list of indexes ?

SP_HELPINDEX <tabname>

ex :- SP_HELPINDEX EMP

Droping index :-
-----------------

DROP INDEX EMP.I1


if we drop table what about indexes created on table ?

ans :- indexes are also dropped

SERVER
DATABASE
TABLES
ROWS & COLS
CONSTRAINTS
INDEXES
TRIGGERS
VIEWS
SYNONYMS
SEQUENCES
PROCEDURES
FUNCTIONS

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

14-nov-22 TSQL programming (Transact-SQL)


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

1 improves performance :-
---------------------------

=> in TSQL, sql commands can be grouped into one block and we
submit that block to sql server , so in TSQL no of requests
and response between user and sql server are reduced and
performance is improved.

2 supports conditional statements :-


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

=> tsql supports conditional statements like if-then-else. So in


tsql we can execute sql commands based on conditions.

3 supports loops :-
-------------------

=> tsql supports looping statements like while , using loops we can
executes statements repeatedly multiple times.

4 supports error handling :-


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

=> in TSQL , if any statement causes error then we can handle that
error and we can display our own simple and user friendly
messages.

5 supports reusability :-
--------------------------

=> TSQL programs can be stored in db and applications which are


connected to db can reuse those programs.

6 supports security :-
-----------------------
=> because these programs are stored in db so only authorized
users can execute these programs.

TSQL programming :-
--------------------

basic programming
conditional statements
loops
cursors
error handling
stored procedures
stored functions
triggers
dynamic sql

=> TSQL blocks are 2 types

1 anonymous blocks
2 named blocks
stored procedures
stored functions
triggers

Anonymous blocks :-
-------------------

=> a tsql block without name is called anonymous block.

=> the following statements are used in tsql programming

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

=> used to assign value to variable.

SET @varname = value

ex :- SET @x = 100
SET @s = 'abc'
SET @d = GETDATE()
PRINT statement :-
-------------------

=> used to print variable values or messages

PRINT 'hello'
PRINT @x

example 1 :-

DECLARE @a tinyint,@b tinyint,@c tinyint


SET @a=10
SET @b=20
SET @c=@a+@b
PRINT @c

example 2 :-

=> write a prog to input and print day of the week ?

DECLARE @d DATE
SET @d = '2023-01-01'
PRINT DATENAME(dw,@d)

output :- sunday

DB programming with TSQL :-


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

=> to perform operations on db execute sql commands from tsql program.


and the following commands can be executed from tsql program.

1 DML (INSERT,UPDATE,DELETE,MERGE)
2 DQL (SELECT)
3 TCL (COMMIT,ROLLBACK,SAVETRANSACTION)

SELECT stmt syntax :-


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

=> in tsql , we get data from db tables and copy that values into
variables declared in tsql program.

SELECT @var1=col1,
@var2=col2
FROM tabname
WHERE condition

example :-

1 SELECT @s=ename FROM emp WHERE empno = 7844

2 SELECT @n=ename,@s=sal FROM emp WHERE empno = 7844

16-nov-22

=> write a prog to input empno and print name & salary ?

DECLARE @eno INT,@name VARCHAR(10),@sal MONEY


SET @eno=108
SELECT @name=ename,@sal=sal FROM emp WHERE empno = @eno
PRINT @name + ' ' + CAST(@sal AS VARCHAR)

=> write a prog to input empno and print experience ?

DECLARE @eno INT,@hire DATE,@expr INT


SET @eno=104
SELECT @hire=hiredate FROM emp WHERE empno=@eno
SET @expr = DATEDIFF(yy,@hire,getdate())
PRINT 'Experience = ' + CAST(@expr AS VARCHAR) + ' Years'

=> write a prog to input empno and print total salary ?

total sal = sal + comm

conditional statements :-
-------------------------

1 IF-ELSE
2 MULTI-IF
3 NESETD-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 salary as follows

if job=CLERK incr sal by 10%


SALESMAN 15%
MANAGER 20%
others 5%

DECLARE @eno INT,@job VARCHAR(10),@pct INT


SET @eno=107
SELECT @job=job FROM EMP WHERE EMPNO=@eno
IF @job='CLERK'
SET @pct=10
ELSE IF @job='SALESMAN'
SET @pct=15
ELSE IF @job='MANAGER'
SET @pct=20
ELSE
SET @pct=5
UPDATE emp SET sal = sal + (sal*@pct/100) WHERE empno=@eno

=> write a prog to process bank transaction (w/d) ?

ACCOUNTS
ACCNO ACTYPE BAL
100 S 10000
101 S 20000

DECLARE @acno INT,@ttype CHAR(1),@tamt MONEY,@bal MONEY


SET @acno=100
SET @ttype='w'
SET @amt=1000
IF @ttype='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 @ttype='d'
UPDATE accounts SET bal=bal+@amt WHERE accno=@acno
ELSE
PRINT 'invalid transaction type'

=> write a prog to transfer amount from one account to another account ?

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

NOTE :-

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

@@ROWCOUNT :-
------------------------

=> It is a system variable that returns no of rows affected by dml


=> if dml is successful then it returns no of rows affected
=> if dml fails then returns 0

WHILE loop :-
-------------------

=> loops are used to execute statements repeatedly multiple times.


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 2023 calendar ?

2023-01-01 sunday
2023-01-02 ???

2023-12-31 ???

DECLARE @d1 DATE,@d2 DATE


SET @d1 = '2023-01-01'
SET @d2 = '2023-12-31'
WHILE(@d1<=@d2)
BEGIN
PRINT CAST(@d1 AS VARCHAR) + ' ' + DATENAME(dw,@d1)
SET @d1 = DATEADD(dd,1,@d1)
END

=> write a prog to print sundays between two given dates ?

DECLARE @d1 DATE,@d2 DATE


SET @d1 = '2022-11-17'
SET @d2 = '2022-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

844 8440 6214

314469

You might also like