Nanda SQL Notes
Nanda SQL Notes
Database :-
---------------
Types of Databases :-
-----------------------------
=> OLTP is for running business and OLAP is for to analyse business.
C create
R read
U update
D delete
DBMS :-
--------------
RDBMS :-
--------------
Information Rule :-
------------------------
CUSTOMER
CID NAME ADDR
100 sachin mum
101 vijay hyd
102 rahul del
RDBMS features :-
---------------------------
NoSQL Databases :-
---------------------------
1 MongoDB
2 Cassandra
23-jan-25
ORDBMS :-
==========
=> object relational DBMS
=> It is the combination of RDBMS & oops
SQL SERVER
ORACLE
POSTGRESQL
Analysis
Design
Development
Testing
Deploy
Maintenance
Design :-
------------
Development :-
-------------------
Developer DBA
creating tables installation of SQL server
creating views creating database
creating synonyms creating logins
creating sequences DB backup & restore
creating indexes DB export & import
creating procedures performance tuning
creating functions creating triggers
writing queries
Testing :-
------------
1 manual testing
2 automation testing
Deployment :-
-----------------
================================================================
SQL SERVER
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
Client
-----------
1 connects to server
2 submit requests to server
3 receive response from server
client tool :-
---------------
USER---SSMS-------------------------------------SQL SERVER---------DB
USER---SQLPLUS--------------------------------ORACLE---------------DB
USER-----MYSQLWORKGENCH---------------MYSQL---------------DB
24-JAN-25
SQL :-
----------
=> SQL stands for structured query language.
user-------SQL plus------------------SQL---------------------Oracle---------------DB
user-------MySQL Bench-------SQL--------------------MYSQL-------------------DB
21-nov-24
=> to connect to SQL server open SSMS and enter following details
server
database
table
data
Creating Database :-
----------------------------
=> In object explorer select Databases => New Database
=> click OK
1 master
2 model
3 Ms Db
4 Temp Db
=> use master DB for server level operations like creating new database
=> open master DB and execute following command
1 SQL server
2 SSMS
SQL server :-
----------------
download :- https://www.microsoft.com/en-in/sql-server/sql-server-
downloads install :-
https://www.mssqltips.com/sqlservertip/7313/install-sql-server-2022
SSMS :-
----------
download :- https://learn.microsoft.com/en-us/sql/ssms/download-sql-
server-management-studio-ssms?view =sql-server-ver16
25-JAN-25
DATA TYPES
char(size) :-
-----------------
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
TG
COUNTRY_CODE CHAR(3)
IND
USA
VARCHAR(size) :-
----------------------------
ex :- NAME VARCHAR(10)
SACHIN - - - -
released
=> char / varchar allows ascii chars (256 chars) that includes A-Z,a-
z,0-9,special chars so char / varchar allows alphanumeric data.
ex :-
PANNO CHAR(10)
VEHNO CHAR(10)
EMAILID VARCHAR(30)
VARCHAR(MAX) :-
---------------------------
=> allows Unicode chars (65536) that includes all ascii chars and chars
belongs to different languages.
INTEGER types :-
-------------------------
tinyint 1 0 to 255
smallint 2 -2^15 to 2^15-1 (-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) :-
-----------------------
ex :- empid NUMERIC(4)
10
100
=>
1000
10000 => ERROR
aadhaarno NUMERIC(12)
phone NUMERIC(10)
accno NUMERIC(12)
NUMERIC(p,s) / DECIMAL(p,s) :-
---------------------------------------------------
ex :- SAL NUMERIC(7,2)
5000
5000.55
50000.55
500000.55 => ERROR
SAVG NUMERIC(5,2)
CURRENCY types :-
---------------------------
=> currency types are used for fields related to money
ex :- SAL SMALLMONEY
BAL MONEY
Ex :- DOB DATE
2003-10-05
LOGIN TIME
9:05:10
TXNDT DATETIME
2025-01-25 10:00:00
=>
CREATE TABLE <tabname>
(
colname datatype(size) ,
colname datatype(size),
----------------------------
)
Rules :-
------------
ex :-
123emp INVALID
emp123 INVALID
emp*123 INVALID
emp_123 VALID
ex :-
=> above command created table structure that includes columns ,datatype
and size
SP_HELP <tabname>
Ex :-
SP_HELP EMP
---------------------------------------
---------
=> "INSERT" command is used to insert data into the table.
1 single row
=>
2 multiple rows
ex :-
inserting nulls :-
----------------------
method 1 :-
method 2 :-
INSERT INTO EMP(EMPID,ENAME,HIREDATE,DEPT)
VALUES(105,'vijay','2017-04-20','hr')
28-JAN-25
Displaying Data :-
==============
SELECT columns / *
FROM tabname
=>
[WHERE cond]
SQL = ENGLISH
QUERIES = SENTENCES
CLAUSES = WORDS
WHERE clause :-
ex :-
compound condition :-
-----------------------------
T T T
T F F
F T F
F F F
T T T
T F T
F T T
F F F
SELECT *
FROM emp
WHERE empid = 100 OR empid = 103 OR empid = 105
=> display hr dept clerk details and earning more than 4000 ?
SELECT *
FROM emp
WHERE dept='hr' AND job='clerk' AND sal>4000
=> employees earning more than 5000 and less than 10000 ?
SELECT *
FROM emp
WHERE sal > 5000 AND sal < 10000
SELECT *
FROM emp
WHERE job='clerk' OR job='manager' AND sal>5000
-------------- -------------------------------------------
SELECT *
FROM emp
WHERE (job='clerk' OR job='manager') AND sal>5000
29-JAN-25
IN operator :-
===========
SELECT *
FROM emp
WHERE empid IN (100,103,105)
BETWEEN operator :-
==================
Ex :-
SELECT *
FROM emp
WHERE sal BETWEEN 5000 AND 10000 ( sal>=5000 and sal<=10000)
LIKE operator:-
============
=> pattern may contain alphabets, digits, special chars and wildcard chars
Wildcard chars :-
=============
SELECT *
FROM emp
WHERE ename LIKE 'a%'
OR
ename LIKE
'e%'
30-jan-25
SELECT *
FROM EMP
WHERE JOB IN ('CLERK','MAN%')
A ERROR
B RETURNS CLERKs & MANAGERs
C RETURNS ONLY CLERKs
D NONE
ANS :- C
SELECT *
FROM EMP
WHERE JOB = 'CLERK' OR JOB LIKE 'MAN%'
ANS :- B
IS operator :-
===========
Ex :-
ALIAS:-
=>alias means another name or alternative name
=>used to change column heading
ORDER BY clause:-
SELECT columns
FROM tabname
[WHERE cond]
ORDER BY colname ASC/DESC , ------------
Ex :-
SELECT *
FROM emp
ORDER BY ename ASC
SELECT *
FROM emp
ORDER BY sal DESC
NOTE :-
=> in order by clause we can use column name or column number
=> column number is not based on table and it is based on select list
31-JAN-25
=> employees joined in 1981 year and arrange list name wise asc ?
SELECT empno,ename,hiredate
FROM emp
WHERE hiredate LIKE '1981%'
ORDER BY ename ASC
DISTINCT clause:-
10
20
30
TOP clause :-
Ex :-
=> display first 5 rows from emp ?
SELECT TOP 5 *
FROM emp
INSERT
UPDATE
DELETE
MERGE
SET IMPLICIT_TRANSACTIONS ON
UPDATE command :-
-------------------------------
UPDATE tabname
SET colname = value , colname = value ,
[WHERE cond]
UPDATE emp
SET sal = sal + (sal*0.2) , comm = comm + (comm*0.1)
WHERE hiredate LIKE '1981%'
AND
job='SALESMAN'
1-feb-25
DELETE command:-
Ex :-
NOTE :-
CREATE
ALTER
DROP
TRUNCATE
DDL DML
SET IMPLICIT_TRANSACTIONS ON
ALTER command :-
1 add columns
2 drop columns
3 modify a column
changing datatype , changing size
Adding columns :-
------------------------
ALTER TABLE tabname
after adding by default the new columns are filled with NULLs,
to insert data into the new columns use update command.
Drop column :-
------------------------
Ex :-
Modifying a column :-
----------------------------
Ex :-
=> modify column empno datatype to int ?
Drop command :-
-----------------------
Ex :-
TRUNCATE command :-
----------------------------------
Ex :-
DELETE VS TRUNCATE :-
-----------------------------------
DELETE TRUNCATE
1 DML DDL
5 slower faster
Ex :-
SP_RENAME 'EMP','EMPLOYEES'
SP_RENAME 'EMPLOYEES.COMM','BONUS'
3-feb-24
Built-in
Functions :-
=> a function accepts some input and perform some calculation and
returns one value.
Types of functions :-
================
1 Date
2 Character
3 Numeric
4 Conversion
5 Special
6 Analytical
7 Aggregate
Date Functions :-
------------------------
1 GETDATE() :-
--------------------
2 DATEPART() :-
--------------------
DATEPART(INTERVAL , DATE)
Ex :-
JAN-MAR 1
APR-JUN 2
JUL-SEP 3
OCT-DEC 4
SELECT *
FROM EMP
WHERE DATEPART(YY,HIREDATE) IN (1980,1983,1985)
SELECT *
FROM EMP
WHERE DATEPART(MM,HIREDATE) IN (1,4,12)
SELECT *
FROM EMP
WHERE DATEPART(YY,HIREDATE)%4=0
SELECT *
FROM EMP
WHERE DATEPART(DW,HIREDATE) = 1
SELECT *
FROM EMP
WHERE DATEPART(YY,HIREDATE) = 1981
AND
DATEPART(QQ,HIREDATE) = 2
DATENAME() :-
-----------------------
MM DW
DATEPART 2 2
Ex :-
FORMAT() :-
-----------------
Ex :-
"=" comparision with GETDATE() always fails because sql server not
only compares dates but it also compares date & time , To overcome
this problme use FORMAT function
SELECT *
FROM EMP
WHERE HIREDATE = FORMAT(GETDATE(),'yyyy-MM-dd')
2025-02-03 = 2025-02-03
DATEADD() :-
--------------------
Ex :-
SELECT *
FROM GOLD_RATES
WHERE DATEID = FORMAT(GETDATE(),'yyyy-MM-dd')
4-FEB-25
DATEDIFF() :-
-------------------
Ex :-
SELECT ENAME ,
DATEDIFF(YY,HIREDATE,GETDATE()) AS EXPERIENCE
FROM EMP
EOMONTH() :-
-------------------------
=> returns end of the month i.e. last day of the month
EOMONTH(DATE,INT)
Ex :-
Character functions :-
--------------------------------
UPPER() :-
------------------
UPPER(string/colname)
Ex :-
SELECT UPPER('welcome') => WELCOME
LOWER() :-
-----------------
LOWER(string)
Ex :-
LEN() :-
-------------
LEN(string / colname)
Ex :-
SELECT *
FROM emp
WHERE LEN(ename) > 5
Ex :-
SELECT empno,
ename,
LEFT(ename,3) +
LEFT(empno,3) +
'@tcs.com' as emailid
FROM emp
UPDATE emp
SET emailid = LEFT(ename,3) + LEFT(empno,3) + '@tcs.com'
5-feb-25
SUBSTRING() :-
-------------------------
Ex :-
CHARINDEX() :-
------------------------
CHARINDEX(char,string,
[start])
Ex :-
scenario :-
-------------
CUST
SELECT CID,
DATEDIFF(YY,DOB,GETDATE()) AS AGE
FROM CUST
REPLICATE() :-
---------------------
REPLICATE(char , length)
Ex :-
REPLACE() :-
-------------------
Ex :-
UPDATE EMP
SET HIREDATE = REPLACE(HIREDATE,'1981','2021')
TRANSLATE() :-
---------------------
TRANSLATE(str1,str2,str3)
Ex :-
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*r@&#%^!') AS SAL
FROM EMP
6-FEB-25
Numeric functions :-
================
ROUND
CEILING
FLOOR
ROUND() :-
----------------
Ex :-
38-------------------------------------38.5--------------------------------------39
300-----------------------------350----------------------------------400
380-------------------------------385----------------------------------390
0-----------------------------------500----------------------------------1000
ROUND(38.5678,0,1) => 38
ROUND(38.5678,2,1) => 38.56
ROUND(38.5678,3,1) => 38.567
CEILING() :-
------------------
CEILING(number)
Ex :-
FLOOR(number)
Ex :-
Conversion functions :-
--------------------------------
1 CAST
2 CONVERT
CAST :-
-----------
CAST(expression AS datatype)
Ex :-
CONVERT() :-
-----------------
CONVERT(TARGET-TYPE , SOURCE-VALUE)
Ex :-
SELECT CONVERT(INT,10.5) => 10
=> to display dates in different formats first convert date to char type
Ex :-
07-feb-25
CONVERT(VARCHAR,MONEY,1)
Ex :-
allen 1,600.00
ward 1,250.00
Special functions :-
--------------------------
ISNULL() :-
---------------
ISNULL(arg1,arg2)
Ex :-
SELECT ENAME, SAL, COMM, SAL+ ISNULL (COMM ,0) AS TOTSAL FROM EMP
Ex :-
=> 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
SELECT EMPNO,ENAME,SAL,
DENSE_RANK() OVER (ORDER BY SAL DESC) AS RNK
FROM EMP
1 rank function generates gaps but dense_rank will not generate gaps.
PARTITION BY clause :-
-----------------------------------
=> partition by clause is used to divide the table based on one or more
columns
=> used to find ranks with in group , for ex to find ranks with in dept
first divide the table dept wise and apply rank/ dense_rank functions
on each dept instead of applying on whole table.
Ex :-
=> the following query finds ranks of the employees with in dept based on
sal ?
ROW_NUMBER() :-
----------------------------
Ex :-
SELECT EMPNO,ENAME,SAL,
ROW_NUMBER() OVER (ORDER BY SAL DESC) AS RNO
FROM EMP
8-FEB-25
Ex 1 :-
SELECT ename,sal,
LAG(sal,1) OVER (ORDER BY empno ASC) as prev_sal
FROM emp
Ex 2 :-
Aggregate Functions :-
-----------------------------------
=> these functions process multiple rows and returns one value
MAX
MIN
SUM
AVG
COUNT
COUNT(*)
MAX() :-
------------
MIN() :-
----------
MIN(arg)
Ex :-
SUM() :-
--------------
SUM(arg)
Ex :-
AVG() :-
-----------
AVG(arg)
Ex :-
NOTE :-
COUNT() :-
---------------
COUNT(arg)
Ex :-
COUNT(*) :-
-------------------
NOTE :-
=> aggregate function are not allowed in where clause and allowed only in
select, having clauses
SELECT deptno
FROM emp
WHERE COUNT(*) > 3 => ERROR
========================================================================
==
1 simplecase
2 searched case
simple case :-
------------------
CASE COLNAME
WHEN VALUE1 THEN RETURN EXPR1
WHEN VALUE2 THEN RETURN EXPR2
WHEN VALUE3 THEN RETURN EXPR3
------
ELSE RETURN EXPR
END
Ex :-
IF DEPTNO = 10 DISPLAY HR
20 IT
30 SALES
OTHERS UNKNOWN
SELECT ENAME,SAL,
CASE DEPTNO
WHEN 10 THEN 'HR'
WHEN 20 THEN 'IT'
WHEN 30 THEN 'SALES'
ELSE 'UNKNOWN'
END AS DEPT
FROM EMP
Searched case :-
------------------------
=> use searched case when conditions not based on "=" operator
CASE
WHEN COND1 THEN RETURN EXPR1
WHEN COND2 THEN RETURN EXPR2
---------------------------
ELSE RETURN EXPR
END
Ex :-
SELECT ENAME,SAL,
CASE
WHEN SAL > 3000 THEN 'HISAL'
WHEN SAL<3000 THEN 'LOSAL'
ELSE 'AVGSAL'
END AS SALRANGE
FROM EMP
========================================================================
==
11-FEB-25
GROUP BY clause :-
================
=> GROUP BY clause is used group rows based on one or more columns to
calculate min, max, sum, avg, count for each group. For ex to calculate dept
wise total sal then first group the records based on deptno and apply sum
function on each dept.
1 A 3000 20
2 B 5000 30 group by 10 7000
3 C 4000 10 =========> 20 9000
4 D 6000 20 30 5000 5E 3000 10
=> GROUP BY clause can be used to convert detailed data into summarized data
which is useful for analysis.
SELECT columns
FROM tabname
[WHERE cond]
GROUP BY col1,col2,----
[HAVING cond]
[ORDER BY col1 ASC/DESC,------]
Execution:-
FROM
WHERE
GROUP BY
HAVING
SELECT
ORDER BY
Ex :-
NOTE :-
20 5
30 6
WHERE VS HAVING:-
WHERE HAVING
=> find southern states having more than 5cr total no of persons ?
PERSONS
AADHARNO NAME GENDER ADDR CITY STATE
SELECT STATE
FROM PERSONS
WHERE STATE IN ('AP','TG','KA','KL','TN')
GROUP BY STATE
HAVING COUNT(*) > 50000000
GROUP BY ROLLUP(col1,col2,--)
GROUP BY CUBE(col1,col2,-----)
ROLLUP :-
----------------
=> rollup displays subtotals for each group (deptno) and also displays
grand total.
CUBE :-
--------------
=> cube displays subtotals for each group by column (deptno,job) and also displays
grand total
GROUPING_ID() :-
--------------------------
=> this function accepts group by columns and returns subtotal belongs to which
group by column
Ex :- GROUPING_ID(deptno,job)
13-feb-25
INTEGRITY CONSTRAINTS
=>Integrity Constraints are rules to maintain data quality or data consistency or data
integrity
=> used to prevent users from entering invalid data.
=> used to enforce rules like min bal must be 1000
Types of constraints :-
1 NOT NULL
2 UNIQUE
3 PRIMARY KEY
4 CHECK
5 FOREIGN KEY
6 DEFAULT
1 column level
2 table level
column level :-
-------------------
NOT NULL :-
-----------------
Ex :-
UNIQUE :-
---------------
ex :-
PRIMARY KEY :-
-----------------------
ex :-
NOTE :-
=> a table can have only one primary key, if we want multiple primary
keys then declare one column with primary key and other columns with
unique not null.
candidate key :-
---------------------
=> while creating table secondary keys are declared with unique not null.
14-feb-25
check constraint :-
-------------------------
check(condition)
FOREIGN KEY :-
-------------------------
=> foreign key is used to establish relationship between two or more tables.
Ex :-
EMP
empid ename sal projid pname duration cost client
1 A 5000 100 TATA 5 800 TATA MOTORS
2 B 4000 100 TATA 5 800 TATA MOTORS
3 C 3000 100 TATA 5 800 TATA MOTORS
PROJECTS
Projid pname duration cost client
100 TATA 5 800 TATA MOTORS
101 L&T 4 600 L&T
EMP
empid ename sal projid REFERENCES projects(projid)
1 A 5000 100
2 B 4000 101
3 C 3000 999 => invalid
4 D 4000 100
5 E 3000 NULL
Relationship Types :-
---------------------------
=> by default SQL server creates one to many relationship between two tables
Ex :-
DEPT
dno dname
10 HR
20 IT
30 SALES
ex :-
STUDENT COURSE
sid sname cid cname
1 A 10 .NET
2 B 11 SQL SERVER
REGISTRATIONS
sid cid dor fee
1 10 ? ?
1 11 ? ?
2 10 ? ?
NOTE :-
=> if relationship is many to many then create 3rd table and add pks of both tables as
foreign keys
2 entities tables
3 attributes fields
Relational model :-
---------------------------
BANK
code name addr
-------
ACCOUNT
accno actype bal branch_id (fk) custid(fk)
---------
15-feb-25
DEFAULT:-
=> while inserting if we skip hiredate then SQL server inserts default value.
Question :-
Rules :-
TRANSACTIONS
TRID TTYPE TDATE TAMT ACCNO
Rules :-
TABLE LEVEL :-
------------------------
=> if constraints are declared after declaring all columns then it is called table level
=> use table level to declare constraints for multiple or combination of columns
Primary key(sid,cid) these two primary keys combined as one composite Primary key
Question :-
SALES
DATEID PRODID CUSTID QTY AMT
2025-02-14 100 10 1 2000
2025-02-14 100 11 1 2000
2025-02-14 101 10 1 1000
2025-02-15 100 10 1 2000
17-feb-25
=> if combination of columns declared foreign key then it is called composite foreign
key.
=> a composite foreign key refers composite primary key.
ex :-
STUDENT COURSE
sid sname c
cname
1 A 10 .NET
2 B 11 SQL SERVER
REGISTRATIONS sid
cid dor fee
------------------
1 10 ? ?
1 11 ? ?
2 10 ? ?
CERTIFICATES
certno doi sid cid
1000 10/ 1 10
1001 11/ 1 11
1002 12/ 2 11
=> In the above example sid,cid combination should match with registrations table
sid,cid combination, so declare this combination as foreign key that references
registrations table primary key (sid,cid).
A UNIQUE
B CHECK
C NOT NULL
D PRIMARY KEY
E FOREIGN KEY
Which statements are true regarding constraints ?
ex :-
WITH NOCHECK :-
-------------------------
=> if constraint is added with "WITH NOCHECK" then sql server will not validate
existing data and it validates only new data.
Adding unique :-
------------------------
Droping constraints :-
-----------------------------
Ex :-
NOTE :-
18-feb-25
DELETE rules :-
----------------------
on delete no action :-
-----------------------------
ex :-
scenario :-
---------------
ACCOUNTS
accno actype bal
100 s 10000
101 s 20000
LOANS
id type amt accno references accounts(accno)
1 H 50 100
1 C 10 100
ON DELETE CASCADE :-
----------------------------------
=> if parent row is deleted then it is deleted along with child rows.
scenario :-
-------------
ACCOUNTS
accno actype bal
100 s 10000
101 s 20000
=> if parent row is deleted then it is deleted but child rows are not deleted but
fk will be set to null.
1 A NULL
2 B NULL
scenario ;-
-------------
projects projid
pname duration
1000
1001
=> if parent row is deleted then it is deleted but child rows are not deleted but
fk will be set to default value.
1 A 20
2 B 20
summary :-
importance of constraints
declaring constraints column
level table level adding
constraints to existing table
droping constraints delete rules
================================================================
JOINS
=====
=> join is an operation performed to display data from two or more tables.
ex :-
orders cust
ordid orddt deldt cid cid cname addr 1000 10-
20- 10 10 A HYD
1001 15- 20- 11 11 B HYD
OUTPUT :-
ordid orddt deldt cname addr
1000 10- 20- A HYD
Types of joins :-
---------------------
1 Inner join
equi join non
equi join self
join 2 Outer join
left join
right join
date
full join
3 Cartisean / Cross join
Equi join :-
--------------
=> To perform equi join between the two tables there must be common field
and name of the common field need not to be same and pk-fk relationship
is not compulsory.
=> Equi join is performed on the common field with same datatype.
SELECT columns
FROM tab1 INNER JOIN tab2
ON join condition
join condition :-
---------------------
=> join condition specifies which record of 1st table should be joined with
which record of 2nd table.
=> based on the given join condition sql server joins the records of two tables.
table1.commonfield = table2.commonfield
=> this join is called equi join because here join condtion is based on "=" operator
Ex :-
EMP DEPT
empno ename sal deptno deptno dname loc
1 A 3000 10 10 ACCOUNTS NEW YORK
2 B 5000 20 20 RESEARCH
3 C 4000 30 30 SALES
4 D 3000 20 40 OPERATIONS
5 E 2000 NULL
SELECT empno,ename,sal,dname,loc
FROM emp INNER JOIN dept
ON emp.deptno = dept.deptno
=> 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.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
19-feb-25
=> display employee details with dept details working at NEW YORK loc ?
SELECT e.ename,d.dname,d.loc
FROM emp as e INNER JOIN dept as d
ON e.deptno = d.deptno /* join cond */
WHERE d.loc = 'NEW YORK' /* filter cond */
SELECT columns
FROM tab1 INNER JOIN tab2
ON join cond
INNER JOIN tab3
ON join cond
INNER JOIN tab4
ON join cond
Ex :-
Outer join :-
----------------
=> Inner join returns only matching records but to display unmatched records
perform outer join.
EMP DEPT
empno ename sal deptno deptno dname loc
1 A 3000 10 10 ACCOUNTS NEW YORK
2 B 5000 20 20 RESEARCH
3 C 4000 30 30 SALES
4 D 3000 20 40 OPERATIONS => unmatched
5 E 2000 NULL => unmatched
1 left join
2 right join
3 full join
LEFT JOIN :-
----------------
=> returns all (matched + unmatched) records from left side table and
matching records from right side table.
SELECT e.ename,d.dname
FROM emp as e LEFT JOIN dept as d
ON e.deptno = d.deptno
A ACCOUNTS
B RESEARCH C SALES
D RESEARCH
E NULL => unmatched from emp
RIGHT JOIN :-
----------------------
=> returns all (matched + unmatched) records from right side table and matching
records from left side table.
SELECT e.ename,d.dname
FROM emp as e RIGHT JOIN dept as d
ON e.deptno = d.deptno
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 OPERATIONS => unmatched from dept
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
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
Question 1 :-
T1 T2
F1 F1
1 1
2 2
1 1
2 2
NULL NULL
NULL NULL
Question 2 :-
emp projects
empno ename sal projid projid pname duration client
100 A 50000 1000 1000
101 B 40000 1001 1001
102 C 30000 NULL 1002
=> non equi join is performed between the tables not sharing a common field.
=> here join conditions are not based on "=" operator and it is based on
> < between operators.
Ex :-
emp salgrade
empno ename sal grade losal hisal
1 A 2500 1 700 1000
2 B 5000 2 1001 2000
3 C 1000 3 2001 3000
4 D 3000 4 3001 4000
5 E 1500 5 4001 9999
SELECT e.ename,e.sal,s.grade
FROM emp as e INNER JOIN salgrade as s
ON e.sal BETWEEN s.losal AND s.hisal
SELECT e.ename,e.sal,s.grade
FROM emp as e INNER JOIN salgrade as s
ON e.sal BETWEEN s.losal AND s.hisal
WHERE s.grade = 4
SELECT e.ename,d.dname,s.grade
FROM emp as e INNER JOIN dept as d
ON e.deptno = d.deptno
INNER JOIN salgrade as s
ON e.sal BETWEEN s.losal AND s.hisal ;
ON e.deptno = d.deptno :-
--------------------------------------
EMP DEPT
empno ename sal deptno deptno dname loc
1 A 3000 10 10 ACCOUNTS NEW YORK
2 B 5000 20 20 RESEARCH
3 C 4000 30 30 SALES
4 D 3000 20 40 OPERATIONS
5 E 2000 10
result
1 :-
---------- SALGRADE
GRADE LOSAL HISAL
1 A 3000 ACCOUNTS 1 700 1000
2 B 5000 RESEARCH 2 1001 2000
3 C 4000 SALES 3 2001 3000
4 D 3000 RESERCH 4 3001 4000
5 E 2000 ACCOUNTS 5 4001 9999
1 A 3000 ACCOUNTS 3
2 B 5000 RESEARCH 5
3 C 4000 SALES 4
4 D 3000 RESEARCH 3
5 E 2000 ACCOUNTS 2
SELECT e.ename,d.dname,s.grade :-
-------------------------------------------------------
output :-
A ACCOUNTS 3
B RESEARCH 5
C SALES 4
D RESEARCH 3
E ACCOUNTS 2
Question :-
----------------
CUSTOMER PRODUCTS
cid name addr prodid pname price category brand
10 A 100 ABC 2000
11 101 XYZ 1000
output :-
SELF JOIN :-
--------------------
=> In self join a record in one table joined with another record of same table.
=> To perform self join the same table must be specified two times with
different alias in FROM clause.
Ex :-
emp x emp y
empno ename mgr empno ename mgr
7369 SMITH 7902 7369 SMITH 7902
7499 ALLEN 7698 7499 ALLEN 7698
7566 JONES 7839 7566 JONES 7839
7698 BLAKE 7839 7698 BLAKE 7839
7839 KING NULL 7839 KING NULL
7902 FORD 7566 7902 FORD 7566
SMITH FORD
ALLEN BLAKE
JONES KING
BLAKE KING
FORD JONES
BLAKE KING
SELECT x.ename,x.sal,
y.ename as manager,y.SAL as mgrsal
FROM emp as x INNER JOIN emp as y
ON x.mgr = y.empno
WHERE x.sal > y.sal
SELECT x.ename,x.hiredate,
y.ename as manager,y.HIREDATE as mgrhire
FROM emp as x INNER JOIN emp as y
ON x.mgr = y.empno
WHERE x.hiredate < y.hiredate
Question :-
TEAMS
ID COUNTRY
1 IND
2 AUS
3 NZ
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
21-FEB-25
=> cross join returns cross product or cartesian product of two tables
A = 1,2
B =3,4
Ex 1 :-
SELECT e.ename,d.dname
FROM emp as e CROSS JOIN dept as d
=> above query joins all 14 employees records with all 4 records of dept table and
query returns 56 rows.
Ex 2 :-
T1 T2
ITEM COST ITEM COST
BURGER 100 COOL DRINK 40
PIZZA 150 JUICE 60
output :-
========================================================================
=====
SET operators :-
-----------------------
1 UNION
2 UNION ALL
3 INTERSECT
4 EXCEPT
A = 1,2,3,4
B = 1,2,5,6
A UNION B = 1,2,3,4,5,6
A UNION ALL B = 1,2,3,4,1,2,5,6
A INTERSECT B = 1,2
A EXCEPT B = 3,4
B EXCEPT A = 5,6
=> In SQL SERVER these operations are performed between the records return by two
queries
SELECT statement 1
UNION / UNION ALL / INTERSECT / EXCEPT
SELECT statement 2
Rules :-
------------
Query 1 :-
CLERK
MANAGER
ANALYST
CLERK
ANALYST
Query 2 :-
SALESMAN
SALESMAN
SALESMAN
MANAGER
SALESMAN
CLERK
UNION :-
--------------
ANALYST
CLERK
MANAGER
SALESMAN
ANALYST 3000.00
CLERK 800.00
CLERK 950.00
CLERK 1100.00
MANAGER 2850.00
MANAGER 2975.00
SALESMAN 1250.00
SALESMAN 1500.00
SALESMAN 1600.00
UNION JOIN
T1 T2
F1 C1
1 10
2 20
3 30
UNION :- JOIN :-
1 1 10 2
2 20
3 3 30
10
20
30
Ex 2 :-
EMP_US eno
ename sal dno
100 A 4000 10
101 B 5000 20
DEPT
EMP_IND dno dname loc eno ename sal dno 10
IT 200 K 6000 10 20 HR
202 B 7000 30 30 SALES
UNION ALL :-
-------------------
=> combines rows return by two queries
=> duplicates are not eliminated
=> result is not sorted
CLERK
MANAGER
ANALYST
CLERK
ANALYST
SALESMAN
SALESMAN
SALESMAN
MANAGER
SALESMAN
CLERK
3 slower faster
INTERSECT :-
-------------------
=> returns common values from the output of two select statements
CLERK
MANAGER
EXCEPT :-
----------------
=> returns values present in 1st query output and not present in 2nd query output
ANALYST
Ex :-
CUSTS CUSTT
CID NAME ADDR CID NAME ADDR
1 A HYD 1 A HYD
2 B BLR 2 B BLR
3 C MUM
display new customers
data ?
method 1 :-
method 2 :-
SELECT S.*
FROM CUSTS AS S LEFT JOIN CUSTT AS T
ON S.CID = T.CID
WHERE T.CID IS NULL
ex :-
=> copy new customers data into custt ?
Question :-
T1 T2
F1 F1
1 1
2 2
3 3
10 40
20 50
30 60
1 EQUI JOIN
2 LEFT JOIN
3 RIGH TJOIN
4 FULL JOIN
5 UNION
6 UNION ALL
7 INTERSECT
8 EXCEPT
24-FEB-25
Types of sub-queries :-
-----------------------------
=> if inner query returns one value then it is called single row sub-query
SELECT columns
FROM tabname
WHERE colname OP (SELECT statement)
Ex :-
SELECT *
FROM emp
WHERE sal > (SELECT sal FROM emp WHERE ename='blake')
-----------------------------------------------------------------
2850
SELECT *
FROM emp
WHERE hiredate < (SELECT hiredate FROM emp WHERE ename='king')
---------------------------------------------------------------------
1981-11-17
SELECT ename
FROM emp
WHERE sal = MAX(sal) => ERROR
SELECT ename,MAX(sal) FROM emp => ERROR
14 1
SELECT ename
FROM emp
WHERE sal = (SELECT MAX(sal) FROM emp) => KING
-------------------------------------------
5000
SELECT ename
FROM emp
WHERE HIREDATE = (SELECT MIN(HIREDATE) FROM EMP)
--------------------------------------------------
1980-12-17
SELECT ename
FROM emp
WHERE HIREDATE = (SELECT MIN(HIREDATE) FROM EMP)
OR
HIREDATE = (SELECT MAX(HIREDATE) FROM EMP)
SELECT ename
FROM emp
WHERE hiredate = (SELECT MIN(hiredate) FROM emp)
UNION
SELECT ename
FROM emp
WHERE hiredate = (SELECT MAX(hiredate) FROM emp)
SAL
5000
1000
3000
2000
2975
SELECT MAX(sal)
FROM emp
WHERE sal <> (SELECT MAX(sal) FROM emp)
SELECT ename,sal
FROM emp
WHERE sal = ( SELECT MAX(sal)
FROM emp
WHERE sal <> (SELECT MAX(sal) FROM emp))
sub-query :-
-----------------
SELECT *
FROM EMP
WHERE DEPTNO = (SELECT DEPTNO
FROM DEPT
WHERE LOC='NEW YORK')
join :-
----------
SELECT E.*
FROM EMP AS E INNER JOIN DEPT AS D
ON E.DEPTNO = D.DEPTNO
WHERE D.LOC = 'NEW YORK'
SELECT E.ENAME,D.DNAME
FROM EMP AS E INNER JOIN DEPT AS D
ON E.DEPTNO = D.DEPTNO
WHERE D.LOC = 'NEW YORK'
sub-query :-
-----------------
no t possible
1 to display data from one table and condition based on another table then we can
use join or sub-query.
SELECT ename
FROM emp
WHERE deptno = (SELECT deptno
FROM dept
WHERE locid = (SELECT locid
FROM locations
WHERE country_id = (SELECT country_id
FROM countries
WHERE country_name='USA')))
NOTE :-
=> outer query can be select / insert / update / delete but inner query must be
always select.
UPDATE emp
SET sal = sal + (sal*0.1)
WHERE hiredate = (SELECT MIN(hiredate) FROM emp)
25-FEB-25
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 880
END
WHERE empno IN (7369,7499)
Multi-row sub-queries :-
-------------------------------
=> if sub-query returns more than one row then it is called multi-row sub-query
SELECT columns
FROM tabname
WHERE colname OP (SELECT statement)
= IN
<> NOT IN
Ex :-
=> employees working at NEW YORK,CHICAGO locations ?
SELECT *
FROM emp
WHERE deptno IN (SELECT deptno
FROM dept
WHERE loc IN ('NEW YORK','CHICAGO'))
=> operators used for > < comparision with multiple values
SELECT *
FROM emp
WHERE sal > ANY (SELECT sal FROM emp WHERE job='MANAGER')
2975.00
2850.00
2450.00
SELECT *
FROM emp
WHERE sal > ALL (SELECT sal FROM emp WHERE job='MANAGER')
co-related sub-queries :-
---------------------------------
=> if inner query references values of outer query then it is called co-related sub-query.
=> execution starts from outer query and inner query is executed no of times depends
on no of rows return by outer query.
=> use co-related sub-query to execute sub-query for each row return by outer query.
Ex :-
EMP
empno ename sal deptno
1 A 5000 10
2 B 3000 20
3 C 4000 30
4 D 6000 20
5 E 3000 10
SELECT *
FROM emp
WHERE sal > (SELECT AVG(sal) FROM emp)
---------------------------------------------
4200
EMP
empno ename sal deptno
1 A 5000 10 5000 > (where deptno = 10) 4000 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 3000 10 3000 > ( where deptno = 10) 4000 FALSE
EMP
SAL
5000
1000
3000
2000
2975
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
26-FEB-25
Derived tables :-
------------------------
SELECT columns
FROM (SELECT statement) AS <alias>
WHERE cond ;
default order :-
--------------------
FROM
WHERE
GROUP BY
HAVING
SELECT
ORDER BY
=> to control this order of execution use derived tables , for ex to control
execution order of where & order by.
SELECT SELECT
FROM =============================> FROM (SELECT
WHERE FROM
ORDER BY ORDER BY )
WHERE
1 WHERE 1 ORDER BY
2 ORDER BY 2 WHERE
Ex 1 :-
=> display ranks of the employees based on sal and highest paid employee
should get 1st rank ?
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
SELECT empno,ename,sal
FROM ( SELECT empno,ename,sal,
dense_rank() over (order by sal desc) as rnk
FROM emp ) AS E
WHERE rnk <= 5
=> display top 3 max salaries ?
SELECT TOP 1 *
FROM (SELECT DISTINCT TOP 3 SAL
FROM EMP
ORDER BY SAL DESC) AS E
ORDER BY SAL ASC
SELECT DEPTNO,SAL,rnk
FROM (SELECT sal,deptno,
DENSE_RANK() over (partition by deptno
order by sal desc) as rnk
FROM emp) AS E
WHERE rnk <= 3
Ex 2 :-
SELECT *
FROM (SELECT empno,ename,sal ,
ROW_NUMBER() OVER (ORDER BY empno asc) as rno
FROM EMP) AS E
WHERE rno <= 5
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)
27-FEB-25
DELETE
FROM (SELECT empno,ename,sal,
ROW_NUMBER() over (order by empno asc) as rno
FROM EMP) AS E
WHERE rno <= 5 => ERROR
in derived tables outer query cannot be DML and outer query must be
always SELECT. To overcome this use CTE
CTEs -
----------
=> using CTE we can give name to the query output and we can refer
that name in another query like INSERT/UPDATE/DELETE/SELECT.
=> using CTE we can use result of one operation in another operation.
WITH <CTE-NAME1>
AS
(SELECT STATEMENT ) ,
<CTE-NAME2)
AS
(SELECT STATEMENT)
WITH E
AS
(SELECT empno,ename,sal,
ROW_NUMBER() OVER (ORDER BY empno ASC) as rno
FROM emp)
Ex 2 :-
EMP44
ENO ENAME SAL
1 A 5000
2 B 6000
3 C 7000
1 A 5000
2 B 6000
select eno,ename,sal,
ROW_NUMBER() over (partition by eno,ename,sal
order by eno asc) 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
WITH E
AS
( select eno,ename,sal,
ROW_NUMBER() over (partition by eno,ename,sal
order by eno asc) as rno from emp44)
Ex 3 :-
CRICKET
TEAMA TEAMB WINNER
ENGLAND NEW ZEALAND NEW ZEALAND
output :-
W
AS
(SELECT WINNER AS COUNTRY,COUNT(*) AS WON
FROM CRICKET
GROUP BY WINNER)
Question 1 :-
SALES
ID SDATE AMT
1 2025-02-01 2000
2 2025-02-02 1000
3 2025-02-06 5000
4 2025-02-07 6000
5 2025-02-12 5000
points
custid date points
1 2025-02-10 40
2 ? 50
1 ? 30
1 ? 50
2 ? 80
28-feb-25
scalar sub-queries :-
---------------------------
Ex 1 :-
EMP DEPT
14 4
Ex 2 :-
10 8750.00
20 7100.00
30 5300.00
10 8750.00 21150.00
20 7100.00 21150.00
30 5300.00 21150.00
PCT = (DEPT_TOTSAL/TOTSAL)*100
student
sno sname marks
1 A 70,90,80,50,40
2 B 60,70,50,40,80
3 C 30,50,90,50,40
STRING_SPLIT() :-
--------------------------
=> It is a table valued function and invoked in from clause.
=> used to split the string into rows based on some seperator.
STRING_SPLIT(string,seperator)
Ex :-
o/p :-
a
b
c
d
sachin
ramesh
tendulkar
SELECT sno,sname,marks,
(select sum(cast(value as int))
from string_split(marks,',')) as total,
(select avg(cast(value as int))
from string_split(marks,',')) as avg
FROM student
Question 1 :-
T1
AMT
1000
-200
3000
-500
4000
-600
output :-
POS NEG
1000 -200
3000 -500
4000 -600
Question 2 :-
T1 T2
F1 C1
1 A
2 B
3 C
output :-
1 A
2 B
3 C
WHERE
ORDER BY
DISTINCT
TOP
FUNCTIONS
GROUP BY
JOINS
SET OPERATORS
SUB-QUERIES
==============================================================
PIVOT operator :-
-------------------------
SELECT columns
FROM (SELECT required data) AS <ALIAS>
PIVOT
(
AGGR-EXPR FOR COLNAME IN (V1,V2,V3,---)
) AS <PIVOT-TAB-NAME>
ORDER BY COL ASC/DESC
Ex 1 :-
10 20 30
ANALYST ? 6000 ?
CLERK ? ? ?
MANAGER
SALESMAN 5600
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 :-
========================================================================
==
1-mar-25
=> a new table is created with no of rows and columns return by query.
Ex 2 :- copying specific rows & cols
Ex :-
MERGE command :-
----------------------------
Ex 1 :-
before merge :-
----------------------
CUSTS CUSTT
CID CNAME CITY CID CNAME CITY
1 A MUM => UPDATED 1 A HYD
2 B BLR => DELETED 2 B BLR
3 C DEL => INSERTED
after merge :-
-------------------
CUSTS CUSTT
CID CNAME CITY CID CNAME CITY
1 A MUM 1 A MUM
3 C DEL 3 C DEL
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)
=> every transaction must guarantee a property called atomocity i.e. all
or none
if transaction contains multiple operations then if all are successful
then it must be saved, if one of the operation fails then entire transaction
must be cancelled.
=> the following commands provided by sql server to handle
transactions called TCL commands.
=> a txn begins implicitly when user submits dml/ddl and ends implicitly with commit.
Ex 1 :-
Ex 2 :-
Ex 3 :-
create table a(a int) => implicitly committed
BEGIN TRANSACTION => txn begins T1
insert into a values(10) insert into a
values(20)
COMMIT => txn ends insert
into a values(30) => implicitly committed insert
into a values(40) => implicitly committed
ROLLBACK => error => trying to end transaction without starting
=> if txn ends with COMMIT then it is called successful txn and operations are saved.
=> if txn ends with ROLLBACK then it is called aborted txn and operations are cancelled.
3-mar-25
SAVE TRANSACTION :-
-------------------------------------
=> we can declare save transaction and we can rollback upto the save transaction.
=> using save transaction we can cancel part of the transaction.
Ex :-
SELECT * FROM a
10
20
========================================================================
=
DB SECURITY :-
=============
SERVER (logins)
DATABASE (users)
TABLE (privileges)
ROWS & COLS (views)
Creating logins :-
-----------------------
=> click OK
NOTE :-
=> a new login is created but cannot access databases , so to access database login
must be associated with a user in database.
creating user in db :-
---------------------------
=> In object explorer expand Databases
DB11AM
Users => New User
Enter Username :- VIJAY
=> click OK
=> open the database in which you want to create user for ex DB9AM
and execute the following command
NOTE :-
PRIVILEGES :-
--------------------
DBO :-
----------
KUMAR :-
-------------
DBO :-
-----------
KUMAR :-
------------
1 SELECT * FROM DEPT
REVOKE command :-
-----------------------------
Ex :-
DBO :-
-------------
5-mar-25
DB objects :-
===========
1 TABLES
2 VIEWS
3 SYNONYMS
4 SEQUENCES
5 INDEXES
VIEWS :-
--------------
=> 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.
1 simple views
2 complex views
Ex 1 :-
CREATE VIEW V1
AS
SELECT EMPNO,ENAME,JOB,DEPTNO FROM EMP
=> sql server creates view "V1" and stores query but not query output i.e. data
SELECT * FROM V1
DBO :-
-----------
VIJAY :-
------------
1 SELECT * FROM V1
EX 2 :-
CREATE VIEW V2
AS
SELECT EMPNO,ENAME,JOB,DEPTNO
FROM EMP
WHERE DEPTNO = 20
Complex views :-
------------------------
Ex 1 :-
=> after creating view whenever user wants data from 4 tables then execute
the following simple query
Ex 2 :-
simple complex
Droping view :-
--------------------
DROP VIEW V1
6-mar-25
SYNONYMS :-
===========
=> a synonym is another name or alternative name for a table or view
=> if tablename is lengthy then we can give a simple and short name to the
table called synonym and instead of using tablename we can use
synonym name in SELECT/INSERT/UPDATE/DELETE queries.
Ex :-
SELECT * FROM E
Question :-
synonym alias
1 permanent temporary
3 scope of the synonym scope of the alias is upto the db is upto the query
E EMP
Droping synonyms :-
--------------------------
DROP SYNONYM E
Question :-
--------------
SEQUENCES :-
----------------------
=> a sequence is also db object created to generate sequence numbers.
=> sequences are mostly used for primary key columns.
Ex 1 :-
CREATE SEQUENCE S1
START WITH 1
INCREMENT BY 1
MAXVALUE 5
using sequence :-
------------------------
Ex 2 :-
CREATE SEQUENCE S2
START WITH 100
INCREMENT BY 1
MAXVALUE 9999
Ex 3 :-
BILL
BILLNO BDATE BAMT
DM/060325/1 2025-03-25 2000
DM/060325/2
CREATE SEQUENCE S3
START WITH 1
INCREMENT BY 1
MAXVALUE 999999
CYCLE option :-
-----------------------
=> by default sequence is created with NOCYCLE i.e. it starts from start with
and generates upto max and after reaching max then it stops.
=> if sequence created with CYCLE then after reaching max then it will be
reset to min.
CREATE SEQUENCE S5
START WITH 1
INCREMENT BY 1
MAXVALUE 5
MINVALUE 1
CYCLE
Droping sequences :-
-----------------------------
DROP SEQUENCE S1
7-MAR-25
INDEXES :-
----------------
=> index is also a db object created to improve the performace of data accessing.
Ex :-
=> after creating index sql server creates a structure called BTREE (balanced binary tree)
EMP 3000
SAL
5000
1000
3000 2000 4000
2000
4000 1000 * 2500 * 4000 * 5000 *
3000 1500 * 3000 *,*
2500 2000 *
1500
Composite index :-
----------------------------
=> if index created on multiple columns then it is called composite index
20
10 30
=> SQL SERVER uses above index when where cond based on leading column
of the index i.e. deptno
UNIQUE index :-
-----------------------
=> unique index doesn't allow duplicates into the column on which index is created
G Q
ADAMS * JAMES * MARTIN * SCOTT *
ALLEN * JONES * MILLER * SMITH *
BLAKE *
NOTE :-
=> primary key / unique columns are implicitly indexed by sql server.
=> sql server creates unique index on primary key / unique columns and
unique index doesn't allow duplicates so primary key / unique also doesn't allow
duplicates.
8-mar-25
clustered index :-
-----------------------
=> a non clustered index stores pointers to actual records but where as
clustered index stores actual records.
=> In non clustered , index and table are two seperate objects but where as
clustered index and table are one object.
Ex :-
30 70
10 A 40 C 60 B 80 D
for the above query sql server goes to index and find the entry cid=40
and returns row from index
for the above query sql server goes to index and access all leaf nodes
from left to right.
NOTE :-
2 index and table are two seperate index and table are
objects not two seperate objects
they are one object
SP_HELPINDEX CUST
Droping index :-
-----------------------
SERVER
DATABASE
TABLE
ROWS & COLS
CONSTRAINTS
INDEXES
TRIGGERS
VIEW
SYNONYM
SEQUENCE
IDENTITY :-
----------------
IDENTITY(SEED,INCR)
Ex :-
CID CNAME
100 A
101 B
102 C
103 D
difference between IDENTITY &
SEQUENCE ?
IDENTITY SEQUENCE
SQL
=================================================================
10-MAR-25
T-SQL PROGRAMMING :-
-----------------------------------
1 Basic programming
2 conditional statements
3 loops
4 cursors
5 error handling
6 stored procedures
7 functions
8 triggers
9 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 and response between
user and sql server are reduced and performane is improved.
3 supports loops :-
----------------------
=> T-SQL supports looping statements like while and with the help of
loops we can execute sql commands repeatedly multiple times.
=> In T-SQL , if any statement causes error then we can handle that error
and we can replace system generated message with our own simple
and user friendly message.
5 supports reusability :-
------------------------------
1 Anonymous Blocks
2 Named Blocks
STORED PROCEDURES
FUNCTIONS
TRIGGERS
Anonymous Blocks :-
-----------------------------
1 DECLARE
2 SET
3 PRINT
DECLARE :-
-----------------
Ex :-
DECLARE @x INT
DECLARE @s VARCHAR(10)
DECLARE @d DATE
OR
SET :-
----------
Ex :-
SET @x = 100
SET @s = 'hello'
SET @d = getdate()
PRINT :-
-------------
PRINT message
Ex :- PRINT 'hello'
PRINT @x
Ex :-
DECLARE @d DATE
SET @d = getdate()
PRINT DATENAME(DW,@d)
Ex 1 :-
Ex 2 :-
o/p :-
Experience = 44 years
11-mar-25
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
Ex :-
=> wap to input empno and increment salary by specific amount and after increment
if salary exceeds 5000 then cancel that increment ?
ACCOUNTS
ACCNO ACTYPE BAL
100 S 10000
101 S 20000
TRANSACTIONS
TRID TTYPE TDATE TAMT ACCNO
12-MAR-25
=> wap to input sno and calculate total,avg,result and insert into result table ?
STUDENT
SNO SNAME S1 S2 S3
1 A 80 90 70
2 B 30 60 50
RESULT
SNO TOTAL AVG RESULT
WHILE loop :-
--------------------
WHILE(cond)
BEGIN
statements
END
DECLARE @x INT = 1
WHILE(@x <= 20)
BEGIN
PRINT @x
SET @x = @x + 1
END
2025-01-01 ?
2025-01-02 ?
2025-12-31 ?
2025-04-05
2035-04-05
INPUT :- WELCOME
output :-
W
E
L
C
O
M
E
INPUT :- WELCOME
output :-
W
WE
WEL
WELC
WELCO
WELCOM
WELCOME
INPUT :- WELCOME
OUTPUT :- EMOCLEW
13-mar-25
CURSORS :-
==========
1 declare cursor
2 open cursor
3 fetch record from cursor
4 close cursor
5 deallocate cursor
Declaring cursor :-
---------------------------
Opening :-
-------------
OPEN <cursor-name>
Ex :- OPEN C1
Ex :-
=> 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 C1 ;
Deallocate cursor :-
---------------------------
DEALLOCATE C1 ;
@@FETCH_STATUS :-
-------------------------------
=> It is a system variable that returns fetch status i.e. fetch is successful or not
=> if fetch is successful then returns 0 otherwise returns -1
=> used for loop condition
Ex :-
smith,allen,ward,jones,---------
STRING_AGG() :-
--------------------------
STRING_AGG(colname,seperator)
Ex :-
o/p :- SMITH,ALLEN,WARD,----------------------
14-mar-25
DECLARE C1 CURSOR FOR SELECT sal FROM EMP ORDER BY sal ASC
DECLARE @max MONEY
OPEN C1
FETCH NEXT FROM C1 INTO @max
PRINT @max
CLOSE C1
DEALLOCATE C1
=> wap to calculate all 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,@total INT,@avg DECIMAL(5,2)
DECLARE @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
SCROLLABLE CURSOR :-
---------------------------------------
=> by default cursor is forward only cursor and supports only forward
navigation but doesn't support backward navigation.
=> a forward only cursor supports only FETCH NEXT statement but
scrollable cursor supports the following fetch statements
==================================================================
15-MAR-25
1 syntax errors
2 logical errors
3 runtime errors (exceptions)
=> errors that are raised during program execution are called runtime errors
ex :- declare @x tinyint
set @x = 1000 => runtim error
print @x
=> if any statement causes runtime error then sql server displays error
message and continues program execution.
=> To replace system generated message with our own simple and user
friendly message then we need to handle that runtime error
=> if any statement in try block causes runtime error then control is transferred
to catch block and executes the statements in catch block.
Ex 1 :-
0 - 10 informational message
11-18 error
19-25 fatal error (connect to server is terminated)
state => 0 to 255 => used when same error raised
at multiple locations by using this state
we can identity.
Ex :-
=> wap to input empno and increment sal but sunday updates are not allowed ?
ACCOUNTS
ACCNO ACTYPE BAL
100 S 10000
101 S 20000
TRANSACTIONS
TRID TTYPE TDATE TAMT ACCNO
17-mar-25
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 :- ------------------
=> proc & func are created with name , so proc & func can be called
from another program.
4 improves performance :-
-----------------------------------
=> proc & func improves performance because of one time compilation i.e.
when we create a procedure program is compiled and stored in db and
whenever we call only execution is repeated but not compilation , so this
improves performance.
STORED PROCEDURES :-
======================
=> procedures are created to perform one to more dml operations on table.
parameters :-
-------------------
1 INPUT (DEFAULT)
2 OUTPUT
ASP.NET PROCEDURE
A ============> X (INPUT)
B <============= Y (OUTPUT)
Ex 1 :-
Execution :-
---------------
1 from ssms
2 another t-sql program 3 front-end applications
from ssms :-
----------------
EXECUTE raise_salary
Execution :-
----------------
Execution :-
18-mar-25
Ex :-
ACCOUNTS
ACCNO ACTYPE BAL
100 S 10000
101 S 20000
TRANSACTIONS
TRID TTYPE TDATE TAMT ACCNO
=> when predefine functions not meeting our requirements then we create
our own functions called user define functions.
=> a function is also a named T-SQL block that accepts some input
performs some calculation and must return a value.
Ex 1 :-
Execution :-
----------------
1 SQL commands
2 another program
3 front-end applications
Ex 2 :-
orders products
ordid pid qty pid pname price
1000 100 2 100 A 2000
1000 101 3 101 B 1000
1000 102 1 102 C 500
1001 100 3
C1
100 2 2000
101 3 1000
102 1 500
Execution :-
------------------
=> create a function that accepts deptno and returns employee list working
for that dept ?
Execution :-
Ex 2 :-
=> create a function that returns top N employee list based on sal ?
Execution :-
=> To return records from procedure take output parameter of type cursor
Ex :-
=> create a procedure that accepts deptno and returns employee list working
for dept ?
Execution :-
ACCOUNTS
ACCNO ACTYPE BAL
TRANSACTIONS
TRID TTYPE TDATE TAMT ACCNO
scalar table
procedures functions
5 cannot be called from sql commands can be called from sql commands
========================================================================
=
TRIGGERS :-
===========
=> a trigger is also a named T-SQL block like procedure but executed implicitly by sql server.
=> triggers are executed automatically when user submits DML commands to sql server.
=> triggers are created
1 to control DMLs
2 to enforce complex rules and validations
3 to audit day-to-day operations on tables
AFTER triggers :-
-------------------------
=> if trigger is after then sql server executes the trigger after executing dml
INSTEAD OF triggers :-
-----------------------------------
=> if trigger is instead of then sql server executes the trigger instead of executing dml
Ex :-
Testing :-
Testing :-
Testing :-
UPDATE EMP SET EMPNO = 9999 WHERE EMPNO = 7369 => ERROR
Magic tables :-
--------------------
1 INSERTED
2 DELETED
=> these tables are called magic tables because they are created and destroyed automatically.
=> these tables exists upto the trigger execution , once trigger execution is completed then
these tables are deleted.
=> with the help of these two tables in triggers we can access data affected by dmls
Ex :-
Testing :-
21-mar-25
=> create a trigger to insert details into emp_resign table when employee resigns ?
EMP_RESIGN
EMPNO ENAME JOB SAL HIREDATE DOR
OR
Auditing :-
---------------
EMP_AUDIT
UNAME OPERATION OPTIME NEW_ENO NEW_ENAME NEW_SAL OLD_ENO
OLD_ENAME OLD_SAL
dbo insert ??? 100 ABC 5000 NULL NULL NULL
dbo update ??? 100 ABC 6000 100 ABC
5000
dbo delete ??? NULL NULL NULL 100 ABC
6000
Testing :-
INSTEAD OF triggers :-
---------------------------------
=> if trigger is instead of then sql server executes the trigger instead of executing DML
i.e. DML is replaced with trigger.
Ex :-
EMP44
ENO ENAME DNO
1 A 10
2 B 10
3 C 10
4 D 10
5 E 10 => not alllowed
Testing :-
------------
AFTER :- INSTEAD OF :-
--------------- ---------------------
IF COND IF COND
BEGIN RAISERROR
ROLLBACK ELSE
RAISERROR DML
END
=> list of triggers created by user ?
SYS.TRIGGERS SYS.TABLES
NAME PARENT_ID NAME OBJECT_ID
T5 814625945 EMP 814625945
Droping :-
--------------
DROP TRIGGER T5
========================================================================
22-MAR-25
Dynamic SQL :-
----------------------
=> sql commands generated at runtime are called dyanmic sql commands
=> Dynamic sql is useful when we don't know tablenames and column names until runtime.
=> Dynamic sql commands are executed by using EXEC procedure
Ex :-
execution :-
24-mar-25
Ex :-
Execution :-
EXECUTE backup_all_dbs
RESTORE :- ===========
===============================================================
Normalization :-
=============
1NF
2NF
3NF
BCNF (boyce-codd NF)
4NF
5NF
Example :-
BILL
BILLNO BDATE CCODE CNAME ADDR ICODE NAME QTY RATE VALUE
TBILL
1000 24/ 100 A HYD 1 ABC 2 100 200
200
2 XYZ
3
20
=> above table contains redundency , to reduce this redundency apply normalization
process
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 CNAME ADDR ICODE NAME QTY RATE VALUE
TBILL
S S S S S M M M M M S
=> In above table some fields are single valued and some fields are multi valueds,
so the table is not according to 1NF then decompose the table as follows
TABLE 1 :-
BILL
BILLNO BDATE CCODE CNAME ADDR TBILL
-------------
1000
1001
TABLE 2 :-
BILL_ITEMS
BILLNO ICODE NAME QTY RATE VALUE
----------------------
1000 1 ABC 3 100
1000 2
1000 3
1001 1 ABC 2 100
1001 2
=> In the above table if ICODE is repeated then NAME,RATE are also repeated
so to reduce this redundency apply 2NF.
2NF :-
------------
partial dependency :-
-----------------------------
R(A,B,C,D) A => pk
TABLE 1 :-
BILL
BILLNO BDATE CCODE CNAME ADDR TBILL
-------------
1000
1001
=> above table saitisfies 2NF because no partial dependencies exists in the table
TABLE 2 :-
BILL_ITEMS
BILLNO ICODE NAME QTY RATE VALUE
----------------------
=> above table contains partial dependency , so the table is not according to 2NF
then decompose the table as follows
TABLE 2 :-
-------------
ITEMS
ICODE NAME RATE
---------
TABLE 3 :-
--------------
BILL_ITEMS
BILLNO ICODE QTY VALUE
----------------------
3NF :-
----------
1 if it is in 2NF
2 if there are no transitive dependencies in it
Transitive dependency :-
----------------------------------
R(A,B,C,D) A => pk
TABLE 1 :-
-------------
BILL
BILLNO BDATE CCODE CNAME ADDR TBILL
-------------
=> above table contains transitive dependency , so the table is not according to
3NF then decompose the table as follows.
CUST
CCODE NAME ADDR
-----------
BILL
BILLNO BDATE TBILL CCODE( FK)
----------
TABLE 2 :-
-------------
ITEMS
ICODE NAME RATE
---------
TABLE 3 :-
--------------
BILL_ITEMS
BILLNO ICODE QTY VALUE
----------------------
note :-
AFTER 3NF :-
-----------------
CUST
CCODE NAME ADDR
-----------
BILL
BILLNO BDATE CCODE( FK)
----------
ITEMS
ICODE NAME RATE
---------
BILL_ITEMS
BILLNO ICODE QTY
----------------------
===============================================================
=> these tables exists upto the session and once session closes these tables
are automtically deleted.
method 1 :-
Method 2 :-
SELECT EMPNO,ENAME,SAL,
DENSE_RANK() OVER (ORDER BY SAL DESC) AS RNK INTO #TEMP
FROM EMP
1 CTE
2 Temporary tables
3 cursor
=> scope of the CTE is upto the query and cannot be referenced in another query =>
scope the Temp table is upto the session
===============================================================