SQL Server Notes
SQL Server Notes
Types of Databases: -
i) OLTP DB (online transaction processing)
Organizations uses OLTP for storing day-to-day transactions.
ii) OLAP DB (online analytical processing)
OLAP for analysis
OLAP for analysing business
DBMS: - (Database Management System)
=> It is a software used to create and to manage database.
Evolution of DBMS: -
YEAR NAME
1960 FMS (File Mgmt. System)
1970 HDBMS (Hierarchical dbms)
NDBMS (Network dbms)
RDBMS: -
RDBMS concepts introduced by E.F.CODD
according to E.F. CODD in RDBMS in database data must be organized tables i.e.,
rows & cols
CUSTOMERS
CID NAME AGE => columns/fields/attributes
10 SACHIN 40
11 VIJAY 30
12 RAVI 25 => row/record/tuple
NOTE: Database = collection of tables
Table = collection of rows & cols
Row = collection of field values
Column = collection of values assigned to one field
RDBMS software’s: -
SOFTWARE NAME ORGANIZATION
SQL SERVER Microsoft
ORACLE Oracle Corp
DB2 IBM
MYSQL Oracle Corp
POSTGRESQL POSTGRESQL forum Dev
RDS amazon
sql server is a rdbms product from Microsoft which is used to create and to manage
database.
sql server can be used for both development and administration.
Development Administration
creating tables installation of sql server
creating views creating database
creating synonyms creating logins
creating sequences db backup & restore
creating indexes export & import
creating procedures db mirroring & replication
creating functions db upgradation & migration
creating triggers performance tuning
writing queries
sql server 2016: - polybase, json, temporal table to save data changes, dynamic data
masking and row level security
sql server 2017: - identity cache, New String functions, Automatic Tuning.
sql server 2019: - Read, write, and process big data from Transact-SQL, Easily
combine and analyse high-value relational data with high-volume big data, Query
external data sources, Store big data in HDFS managed by SQL Server, Query data
from multiple external data sources through the cluster.
CLIENT/SERVER ARCHITECTURE: -
i) SERVER
server is a system where sql server software is installed and running.
inside the server sql server manages databases
ii) CLIENT
client is also system where users can connect to server, submit requests to
server, receives response from server
VARCHAR(MAX): -
allows character data up to 2GB.
using VARCHAR(MAX) we can store large amount of text in db.
NOTE: - char/varchar/varchar(max) allows ascii (American standard code for information
interchange) characters
that includes a-z, A-Z,0-9, special characters.
ex: - PANNO CHAR (10)
VEHNO CHAR (10)
EMAILID VARCHAR (30)
NCHAR/NVARCHAR/NVARCHAR(MAX): - (N => National)
These types allow Unicode characters (65536 chars) that includes all ascii characters
and characters belong to different languages.
ascii character occupies 1 byte but a Unicode character occupies 2 bytes.
Integer Types: -
Integer types allows whole numbers i.e., numbers without decimal part.
sql server supports 4 integer types
Type Size Range
TINYINT 1BYTE 0 TO 255
SMALLINT 2 BYTES -32768 TO 32767
3) VARBINARY(MAX)
allows binary data up to 2GB.
extra bytes are released\
Ex: photo varbinary(max)
Rules: -
1) tabname should start with alphabet
2) tabname should not contain spaces & special chars but allows _, #, @
3) tabname can be up to 128 chars
4) table can have up to 1024 columns
5) table can have unlimited rows
Ex: emp123 valid, 123emp invalid, emp 123 invalid, emp*123 invalid, emp_123 valid
Example: -
a) CREATE TABLE WITH FOLLOWING STRUCTURE?
EMP
EMPID ENAME JOB SAL HIREDATE AGE
Solution: CREATE TABLE emp
(
empid SMALLINT, ename VARCHAR (10),
job VARCHAR (10), sal SMALLMONEY,
hiredate DATE, age TINYINT)
above command created table structure/definition/metadata that includes
columns, datatype and size.
Displaying Data: -
"SELECT" command is used to display data from table.
using SELECT command we can display all rows/cols or specific rows/cols
syntax: - SELECT columns/* FROM tabname
SQL = ENGLISH
QUERIES = SENTENCES
CLAUSES = WORDS
FROM clause => specify tablename
SELECT clause => specify column names
* => all columns
display all the data from emp table? SELECT * FROM emp
display employee names and salaries? SELECT ename, sal FROM emp
display employee names, job, age? SELECT ename, job, age FROM emp
Operators in SQL SERVER: -
1) Arithmetic Operators => + - * / %
2) Relational Operators => > >= < <= = <> or! =
3) Logical Operators => AND OR NOT
4) Special Operators => BETWEEN, IN, LIKE, IS, ANY, ALL, EXISTS,
PIVOT.
5) Set Operators => UNION, UNION ALL, INTERSECT, EXCEPT
WHERE clause: -
where clause is used to get specific row/rows from table based on a condition.
Syntax: - SELECT columns
FROM tabname
WHERE condition
condition: -
COLNAME OP VALUE
OP must be any relational operator like > >= < <= = <>
if condition = true row is selected
if condition = false row is not selected
display employee details whose empid=103?
SELECT * FROM emp WHERE empid=103
display employee details whose name = vinod ?
SELECT * FROM emp WHERE ename='vinod'
display employees earning more than 5000?
SELECT * FROM emp WHERE sal>5000
display employees joined after 2020?
SELECT * FROM emp WHERE hiredate>2020 => ERROR
SELECT * FROM emp WHERE hiredate>'2020-12-31'
display employees joined before 2020?
SELECT * FROM emp WHERE hiredate < '2020-01-01'
Compound condition: -
multiple conditions combined with AND / OR operators is called compound
condition.
WHERE cond1 AND cond2 result
T T T
T F F
F T F
F F F
WHERE cond1 OR cond2 result
T T T
T F T
F T T
F F F
scenario :-
STUDENTS
SNO SNAME S1 S2 S3
1 A 80 90 70
2 B 60 30 50
IN operator :-
--------------
=> use IN operator for list comparision. i.e. "=" comparision with multiple values.
Question :-
A ERROR
B RETURNS ROWS
C RETURNS NO ROWS
D NONE
ANS :- C
SELECT *FROM EMP WHERE SAL BETWEEN 5000 AND 10000 (SAL>=5000 AND
SAL<=10000)
SELECT * FROM EMP WHERE SAL BETWEEN 10000 AND 5000 (SAL>=10000 AND
SAL<=5000)
NOTE :- use between operator with lower and upper but not with upper and lower
21-aug-21
LIKE operator :-
----------------
wildcard characters :-
-----------------------
Question :-
A ERROR
B RETURNS clerk,manager
C RETURNS only clerk
D none
ans :- C
ans :- B
IS operator :-
---------------
summary :-
23-AUG-21
Assignment :-
CUST
CID NAMEGENDER CITY AGE
SELECT ENAME,SAL,
SAL*0.2 AS HRA,
SAL*0.3 AS DA,
SAL*0.1 AS TAX,
SAL+(SAL*0.2)+(SAL*0.3)-(SAL*0.1) AS TOTSAL
FROM EMP
------------------------------------------------------------------------------------
ORDER BY clause :-
--------------------
=> ORDER BY clause is used to sort data based on one or more columns either in asc
or in desc order.
SELECT columns/*
FROM tabname
[WHERE cond]
ORDER BY <COL> [ASC/DESC]
=> default order is ASC for DESC order use DESC option.
SELECT *
FROM emp
ORDER BY ename ASC
SELECT *
FROM emp
ORDER BY sal DESC
=> arrange employee list hiredate wise asc and employee joined on same date should
be sorted age wise asc ?
SELECT *
FROM emp
ORDER BY hiredate ASC ,age ASC
=> arrange employee list hiredate wise asc and employee joined on same date should
be sorted sal desc order ?
SELECT *
FROM emp
ORDER BY hiredate ASC ,sal DESC
SCENARIO :-
STUDENT
SNO SNAME M P C
1 A 80 90 70
2 B 60 70 50
3 C 90 80 70
4 D 90 70 80
SELECT *
FROM student
ORDER BY (M+P+C)/3 DESC,M DESC,P DESC
3 C 90 80 70
4 D 90 70 80
1 A 80 90 70
2 B 60 70 50
=> to display avg in the output ?
NOTE :-
SELECT *
FROM emp
ORDER BY 4 DESC ;
=> above query sorts data based on 4th column in emp table i.e. sal
SELECT empid,ename,sal
FROM emp
ORDER BY 4 ASC ; => ERROR
SELECT empid,ename,sal
FROM emp
ORDER BY 3 ASC ;
=> display employees working as clerk,manager and arrange output sal wise Asc order ?
SELECT *
FROM emp
WHERE job IN ('clerk','manager')
ORDER BY sal ASC
24-AUG-21
TOP clause :-
-------------
SELECT TOP 3 *
FROM emp
SELECT TOP 3 *
FROM emp
ORDER BY sal DESC
=> display top 3 max salaries ?
SELECT TOP 3 *
FROM emp
ORDER BY hiredate ASC
-----------------------------------------------------------------------------------------
insert
update
delete
merge
SET IMPLICIT_TRANSACTIONS ON
syn :-
UPDATE tabname
SET colname = value,colname = value,---------
[WHERE condition]
Ex :-
25-aug-21
4 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%'
DELETE command :-
----------------
CREATE
ALTER
DROP
TRUNCATE
SET IMPLICIT_TRANSACTIONS ON
27-aug-21
ALTER command :-
----------------
1 add columns
2 drop columns
3 modify column
incr/decr field size
changing datatype
Adding column :-
-----------------
=> after adding by default the column is filled with nulls , use update command
to insert data into this column
Droping column :-
----------------
Modifying column :-
------------------
Drop command :-
---------------
TRUNCATE command :-
------------------
=> deletes all the data from table but keeps structure
=> will empty the table
=> releases all the pages (memory) allocated for table.
2 drops structure with data deletes only data deletes only data
but not structure but not structure
DELETE VS TRUNCATE :-
---------------------
DELETE TRUNCATE
1 DML DDL
5 slower faster
SP_RENAME <oldname>,<newname>
SP_RENAME 'STUDENT','STUD'
SP_RENAME 'EMP.COMM','BONUS'
28-AUG-21
syn :-
sp_rename 'temp','emp12'
IDENTITY :-
-----------
syntax :- IDENTITY(SEED,INCR)
Example :-
CREATE TABLE cust
(
cid int IDENTITY(100,1),
cname VARCHAR(10)
)
CID CNAME
100 A
101 B
102 C
103 D
104 E
30-aug-21
DELETE VS TRUNCATE :-
ex :- DBCC CHECKIDENT('CUST',RESEED,99)
=> by default sql server will not allow explicit value for identity column
=> execute the following command to provide explicit value for identity column
=> a function accepts some input performs some calculation and returns one value.
Types of Functions :-
----------------------
1 DATE
2 STRING
3 MATHEMATICAL
4 CONVERSION
5 SPECIAL
6 ANALYTICAL
7 AGGREGATE
DATE functions :-
----------------
DATEPART(interval,DATE)
07 saturday
1 jan-mar
2 apr-jun
3 jul-sep
4 oct-dec
31-aug-21
DATENAME() :-
DATENAME(interval,date)
MM DW
DATEPART 08 03
SELECT DATENAME(DW,'1947-08-15')
=> display SMITH joined on WEDNESDAY
ALLEN joined on FRIDAY ?
DATEDIFF() :-
--------------
MONTHS = MONTHS % 12 = 40 % 12 = 4
SELECT ENAME,
DATEDIFF(MM,HIREDATE,GETDATE())/12 AS YEARS,
DATEDIFF(MM,HIREDATE,GETDATE())%12 AS MONTHS
FROM EMP
DATEADD() :-
------------
DATEADD(interval,int,date)
scenario :-
GOLD_RATES
DATEID RATE
2015-01-01 ?
2015-01-02 ?
2021-08-31 ?
EOMONTH() :-
-----------
EOMONTH(date,int)
Assignment :-
01-SEP-21
string functions :-
-------------------
UPPER() :- converts string to uppercase
UPPER(string)
LEN() :-
---------
LEN(string)
=> display employees name starts with and ends with same char ?
scenario :-
SUBSTRING() :-
---------------
=> used to extract part of the string starting from specific position.
SUBSTRING(string,start,len)
REPLICATE() :-
--------------
=> repeats given char for given no of times
REPLICATE(char,len)
scenario :-
ACCOUNTS
ACCNO
12345678932
REPLICATE('X',4) + RIGHT(ACCNO,4)
REPLACE() :-
------------
REPLACE(str1,str2,str3)
02-SEP-21
TRANSLATE(str1,str2,str3)
e => a
l => b
o => c
=> translate function can be used to encrypt data i.e. changing plain text to
cipher text.
SELECT ename,
TRANSLATE(sal,'0123456789.','$B*T%@p^#K$') as sal
FROM emp
output :- hello
CHARINDEX :-
-----------
CHARINDEX(char,string,[start])
Assignment :-
-------------
CUST
CID CNAME
10 sachin tendulkar
11 virat kohli
37.58948383 => 37
37.58
37.5894
syn :- ROUND(number,decimal places)
37------------------------37.5----------------------------38
300--------------------350-----------------------400
380------------------385---------------------390
0------------------500--------------------1000
03-sep-21
CEILING() :- rounds number always to highest
----------
CEILING(number)
CEILING(3.1) => 4
FLOOR(number)
FLOOR(3.9) => 3
conversion functions :-
------------------------
=> these functions are used to convert one datatype to another datatype
1 CAST
2 CONVERT
CAST :-
-------
CAST(source-expr as target-type)
SELECT ename + ' earns ' + sal FROM emp => ERROR
CONVERT(target-type,source-expr)
SELECT CONVERT(INT,10.5)
=> using CONVERT function we can display dates & numbers in different formats
which is not possible using CAST function.
CONVERT(varchar,DATE,style-number)
Without century With century (yyyy) Standard Input/Output (3)
1 101 U.S. 1 = mm/dd/yy
101 = mm/dd/yyyy
6 106 6 = dd mon yy
106 = dd mon yyyy
8 108 - hh:mi:ss
Note: For a milliseconds (mmm) value of 0, the millisecond decimal fraction value will not
display. For example, the value '2012-11-07T18:26:20.000 displays as '2012-11-
07T18:26:20'.
- 127(6, 7) ISO8601 with time zone Z. yyyy-MM-ddThh:mm:ss.fffZ (no spaces)
Note: For a milliseconds (mmm) value of 0, the millisecond decimal value will not display.
For example, the value '2012-11-07T18:26:20.000 will display as '2012-11-07T18:26:20'.
- 130 (1,2) Hijri (5) dd mon yyyy hh:mi:ss:mmmAM
In this style, mon represents a multi-token Hijri unicode representation of the full month
name. This value does not render correctly on a default US installation of SSMS.
- 131 (2)Hijri (5) dd/mm/yyyy hh:mi:ss:mmmAM
=> display EMPNO ENAME SAL HIREDATE ? display hiredates in dd.mm.yyyy format ?
SELECT empno,ename,sal,CONVERT(varchar,hiredate,104) as hiredate FROM emp
CONVERT(varchar,number,style-number)
0 No commas every three digits to the left of the decimal point, and two digits to the right
of the decimal point
Example: 4235.98.
1 Commas every three digits to the left of the decimal point, and two digits to the
right of the decimal point
Example: 3,510.92.
2 No commas every three digits to the left of the decimal point, and four digits to the
right of the decimal point
Example: 4235.9819.
04-sep-21
Analytical functions :-
------------------------
=> 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.
2 in rank function ranks may not be in sequence but in dense_rank function
ranks will be always in sequence.
=> display ranks of the employees based on sal , if salaries are same then ranking
should be based on experience ?
SELECT empno,ename,hiredate,sal,
DENSE_RANK() OVER (ORDER BY sal DESC,hiredate ASC) as rnk
FROM emp
PARTITION BY clause :-
-----------------------
=> partition by clause is used to find ranks with in group for example to find
ranks with in dept first we need to divide the table dept wise and apply
rank/dense_rank function on each dept instead of applying it on whole table.
06-sep-21
ROW_NUMBER() :-
---------------
SPECIAL FUNCTIONS :-
---------------------
ISNULL() :-
-----------
syn :- ISNULL(arg1,arg2)
totsal = sal+comm
Aggregate functions :-
-----------------------
=> these functions process group of rows and returns one value
MAX() :- returns maximum value
MAX(arg)
MIN(arg)
=> round total sal to hundreds and display with thousand seperator ?
29000--------------29050------------------29100
AVG(arg)
COUNT(arg)
T1
F1
10
NULL
20
NULL
30
COUNT(F1) => 3
COUNT(*) => 5
07-SEP-21
NOTE :- aggregate functions not allowed in where clause and they are allowed only
in select,having clauses.
summary :-
DATE :- datepart,datename,datediff,dateadd,eomonth
STRING :- upper,lower,len,left,right,substring,charindex,replicate,replace,translate
MATH :- abs,power,sqrt,square,sign,round,ceiling,floor
CONV :- cast,convert
special :- ISNULL
analytical :- rank,dense_ran,row_number
aggregate :- max,min,sum,avg,count,count(*)
Assignment :-
--------------
SELECT DATEADD(dd,1,EOMONTH(getdate(),-1))
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.
EMP
EMPNO ENAME SAL DEPTNO
1 A 5000 10
2 B 6000 20 10 12000
3 C 4000 30 --------GROUP BY----------> 20 14000
4 D 8000 20 30 4000
5 E 7000 10
=> GROUP BY clause converts detailed data to summarized data which is useful for analysis
syn :-
SELECT columns
FROM tabname
[WHERE cond]
GROUP BY <col>
[HAVING <COND>]
[ORDER BY <col> ASC/DESC]
Execution :-
FROM
WHERE
GROUP BY
HAVING
SELECT
ORDER BY
EMP
EMPNO ENAME SAL DEPTNO
1 A 5000 10
2 B 6000 20
3 C 4000 30
4 D 8000 20
5 E 7000 10
GROUP BY deptno :-
------------------
10
1 A 5000
5 E 7000
20
2 B 6000
4 D 8000
30
3 C 4000
SELECT deptno,SUM(sal) :-
-------------------------
10 12000
20 14000
30 4000
08-sep-21
NOTE :- sql server cannot calculate dept wise count before group by , it can calculate
only after group by so apply the condition COUNT(*) > 3 after group by using
HAVING clause.
FROM emp :-
-----------
EMP
EMPNO ENAME SAL DEPTNO
1 A 5000 10
2 B 6000 20
3 C 4000 30
4 D 8000 20
5 E 7000 10
GROUP BY deptno :-
------------------
10
1 A 5000
5 E 7000
20
2 B 6000
4 D 8000
30
3 C 4000
10
1 A 5000
5 E 7000
20
2 B 6000
4 D 8000
SELECT deptno,count(*) :-
---------------------------
10 2
20 2
=> 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
WHERE VS HAVING :-
------------------
WHERE HAVING
09-sep-21
=> display dept wise and with in dept job wise total sal ?
10 CLERK 1300
MANAGER 2450
PRESIDENT 5000
20 ANALYST 6000
CLERK 1900
MANAGER 2975
30 CLERK 950
MANAGER 2850
SALESMAN 5600
=> Display year wise and with in year quarter wise no of employees joined ?
=> ROLLUP & CUBE are used to display subtotals and grand total
ROLLUP :-
---------
=> rollup calculates subtotals for each group and also calculates grand total
10 CLERK 1300.00
10 MANAGER 2450.00
10 PRESIDENT 5000.00
10 NULL 8750.00 => subtotal
20 ANALYST 6000.00
20 CLERK 1900.00
20 MANAGER 2975.00
20 NULL 10875.00 => subtotal
30 CLERK 950.00
30 MANAGER 2850.00
30 SALESMAN 5600.00
30 NULL 9400.00 => subtotal
NULL NULL 29025.00 => grand total
CUBE :-
--------
=> CUBE displays subtotals for each group by column (i.e. deptno wise and job wise)
and also displays grand total.
10 CLERK 1300.00
10 MANAGER 2450.00
10 PRESIDENT 5000.00
10 NULL 8750.00 => dept subtoal
20 ANALYST 6000.00
20 CLERK 1900.00
20 MANAGER 2975.00
20 NULL 10875.00 => dept subtotal
30 CLERK 950.00
30 MANAGER 2850.00
30 SALESMAN 5600.00
30 NULL 9400.00 => dept subtotal
NULL ANALYST 6000.00 => job subtotal
NULL CLERK 4150.00 => job subtotal
NULL MANAGER 8275.00 => job subtotal
NULL PRESIDENT 5000.00 => job subtotal
NULL SALESMAN 5600.00 => job subtotal
NULL NULL 29025.00 => grand total
11-SEP-21
GROUPING_ID() :-
---------------
=> grouping_id functions accepts group by columns and returns subtotal belongs to
which group by column
GROUPING_ID(deptno,job)
10 CLERK 1300.00 0
10 MANAGER 2450.00 0
10 PRESIDENT 5000.00 0
10 NULL 8750.00 1
20 ANALYST 6000.00 0
20 CLERK 1900.00 0
20 MANAGER 2975.00 0
20 NULL 10875.00 1
30 CLERK 950.00 0
30 MANAGER 2850.00 0
30 SALESMAN 5600.00 0
30 NULL 9400.00 1
NULL ANALYST 6000.00 2
NULL CLERK 4150.00 2
NULL MANAGER 8275.00 2
NULL PRESIDENT 5000.00 2
NULL SALESMAN 5600.00 2
NULL NULL 29025.00 3
CASE statement :-
-----------------
1 simple case
2 searched case
1 simple case :-
----------------
SELECT empno,ename,
CASE job
WHEN 'CLERK' THEN 'WORKER'
WHEN 'MANAGER' THEN 'BOSS'
WHEN 'PRESIDENT' THEN 'BIG BOSS'
ELSE 'EMPLOYEE'
END as job
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
SELECT CASE
WHEN SAL BETWEEN 0 AND 2000 THEN '0-2000'
WHEN SAL BETWEEN 2001 AND 4000 THEN '2001-4000'
WHEN SAL > 4000 THEN 'ABOVE 4000'
END AS SALRAGE ,COUNT(*) AS CNT
FROM EMP
GROUP BY CASE
WHEN SAL BETWEEN 0 AND 2000 THEN '0-2000'
WHEN SAL BETWEEN 2001 AND 4000 THEN '2001-4000'
WHEN SAL > 4000 THEN 'ABOVE 4000'
END
0-2000 8
2001-4000 5
ABOVE 4000 1
Assignment :-
PERSONS
AADHARNO NAME GENDER AGE ADDR CITY STATE
0-20 ?
21-40 ?
41-60 ?
SALES
DATEID PRODID CUSTID QTY AMOUNT
=> display year wise and with in year quarter wise total amount ? display year wise
subtotals ?
---------------------------------------------------------------------------------------
13-sep-21
Integrity Constraints
----------------------
=> Integrity Constraints are rules to maintain data integrity i.e. data quality
=> used to prevent users from entering invalid data
=> used to enforce rules like min sal must be 3000
Integrity Constraints :-
-------------------------
NOT NULL
UNIQUE
PRIMARY KEY
CHECK
FOREIGN KEY
DEFAULT
1 column level
2 table level
column level :-
-----------------
NOT NULL :-
-----------
=> NOT NULL constraint doesn't accept nulls.
=> a column declared with NOT NULL is called mandatory column
UNIQUE :-
---------
PRIMARY KEY :-
--------------
=> only one primary key is allowed per table , if we want two primary keys then
declare one column with primary key and another column with unique & not null.
14-sep-21
candidate key :-
-----------------
=> a field which is eligible for primary key is called candidate key.
ex :- VEHICLES
VEHNO NAME MODEL COST CHASSISNO
=> while creating table secondary keys are declared with UNIQUE NOT NULL
CHECK constraint :-
--------------------
syn :- CHECK(condition)
Example 1 :- sal must be min 3000
FOREIGN KEY :-
---------------
=> to establish relationship between two tables take primary key of one table and
add it to another table as foreign key and declare with references constraint.
example :-
PROJECTS
projid pname duration client cost
100 ABC 5 YEARS TATA MOTORS 300
101
102
EMP
empid ename sal projid REFERENCES projects(projid)
1 A 5000 100
2 B 6000 101
3 C 7000 999 => not accepted
4 D 3000 100 => accepted
5 E 4000 NULL => accepted
=> values entered in foreign key column should match with values entered in primary key/
unique column
=> foreign key allows duplicates and nulls
=> after declaring foreign key a relationship is established between two tables called
parent & child relationship.
Example :-
15-SEP-21
=> by default sql server creates one to many relationship , to establish one to one
relationship declare foreign key with unique constraint.
Example :-
DEPT
DNO DNAME
10 HR
20 IT
30 SALES
MGR
MGRNO MNAME DNO REFERENCES DEPT(DNO) UNIQUE
1 A 10
2 B 20
3 C 30
DEFAULT :-
----------
=> while inserting if we skip hiredate then sql server inserts default value
100 2021-09-15
101 null
102 2021-01-01
Assignment :-
ACCOUNTS
ACCNO ACTYPE NAMEBAL
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 constraint for multiple or combination of columns.
=> in the above example constraint is based on multiple column so cannot be declared
at column and must be declared at table level.
=> sometimes in tables we can't uniquely identify by using single column and we need
combination of
columns to uniquely identify , so that combination should be declared primary key.
=> if combination of columns declared primary key then it is called composite primary key.
Example :-
ORDERS PRODUCTS
ordid ord_dt del_dt cid prodid pname price
1000 10- 20- 10 100 A 2000
1001 12- 22- 11 101 B 3000
1002 15- 25- 12 102 C 5000
ORDER_DETAILS
ordid prodid qty
1000 100 1
1000 101 1
1000 102 1
1001 100 1
1001 101 1
=> in the above ordid,prodid combination uniquely identifies the records so declare this
combination
as primary key at table level.
A UNIQUE
B CHECK
C NOT NULL
D PRIMARY KEY
E FOREIGN KEY
ANS :- C
STEP 1 :-
STEP 2:-
=> above command fails because some of the values are less than 3000 , while adding
constraint
sql server also validates existing data , if existing data satisifies condition then constraint
is added otherwise not.
WITH NOCHECK :-
---------------
=> if check constraint is added with NO CHECK then sql server will not validate existing
data and
it validates only new data.
17-sep-21
Droping constraints :-
-----------------------
DELETE RULES :-
---------------
ON DELETE NO ACTION :-
---------------------
=> parent row cannot be deleted if associated with child rows
scenario :-
ACCOUNTS
ACCNO BAL
100 10000
101 20000
LOANS
ID TYPE AMT ACCNO
1 H 30 100
2 C 10 100
ON DELETE CASCADE :-
--------------------
=> if parent row is deleted then it is deleted along with child rows
ACCOUNTS
ACCNO BAL
100 10000
101 20000
TRANSACTIONS
TRID TTYPE TDATE TAMT ACCNO
1 W ?/ 1000 100
2 D ?? 2000 100
=> 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
100
101
102
EMP
empid ename projid
1 100
2 101
ON DELETE SET DEFAULT :-
-----------------------
=> if parent row is deleted then it is deleted but child rows are not deleted but fk will be set to
default
UPDATE rules :-
--------------
ON UPDATE NO ACTION
ON UPDATE CASCADE
ON UPDATE SET NULL
ON UPDATE SET DEFAULT
=> specifies how foreign key value is affected if primary key updated
--------------------------------------------------------------------------------------------------
18-SEP-21
JOINS
-----
=> join is an operation performed to fetch data from two or more tables for example to fetch
data from two tables we need to join those two tables.
=> in db tables are normalized i.e. related data stored in multiple tables , to gather or to
combine data stored in multiple tables we need to join those tables.
Types of joins :-
-----------------
20-sep-21
=> to perform equi join between the two tables there must be a common field and name of
the
common field need not to be same and pk-fk relationship is also not compulsory.
=> equi join is performed between the two tables based on the common column with same
datatype.
syntax :-
SELECT columns
FROM tabnames
WHERE join condition
join condition :-
----------------
=> based on the given join condition sql server joins the records of two tables
=> join condition determines which record of 1st table should be joined with record of 2nd
table.
table1.commonfield = table2.commonfield
=> this join is called equi join because here join condition is based on "=" operator.
Example :-
EMP DEPT
EMPNO ENAME SAL DEPTNO DEPTNO DNAME LOC
1 A 5000 10 10 ACCOUNTS
2 B 6000 20 20 RESEARCH
3 C 4000 30 30 SALES
4 D 3000 10 40 OPERATIONS
5 E 4000 NULL
SELECT empno,ename,sal,dname,loc
FROM emp,dept
WHERE emp.deptno = dept.deptno
1 A 5000 ACCOUNTS ??
2 B 6000 RESEARCH ??
3 C 4000 SALES ??
4 D 3000 ACCOUNTS ??
=> display EMPNO ENAME SAL DEPTNO DNAME LOC ?
SELECT empno,ename,sal,deptno,dname,loc
FROM emp,dept
WHERE emp.deptno = dept.deptno => ERROR ambiguous column name 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
=> display employee details with dept details working at NEW YORK loc ?
=> if no of tables increases no of join conditions also increases , to join N tables N-1 join
conditions required.
SELECT columns
FROM tab1,tabl2,tab3,--------
WHERE join cond1
AND
join cond2
AND
join cond3
-----------
Example :-
SELECT e.ename,
d.dname,
l.city,l.state,
c.country_name as country
FROM emp e,
dept d,
locations l,
countries c
WHERE e.deptno= d.deptno
AND
d.locid=l.locid
AND
l.country_id = c.country_id
21-sep-21
join styles :-
--------------
ANSI style :-
-------------
SELECT e.ename,d.dname
FROM emp e INNER JOIN dept d
ON e.deptno = d.deptno
SELECT e.ename,
d.dname,
l.city,l.state,
c.country_name as country
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 , to get
unmatched
records also perform outer join.
1 left join
2 right join
3 full join
left join :-
-------------
=> returns all rows (matched + unmatched) from left side and matching rows from right side
table.
SELECT e.ename,d.dname
FROM emp e LEFT JOIN dept d
ON e.deptno = d.deptno
=> returns all rows from emp table and matching rows from dept table
A ACCOUNTS
B RESEARCH
C SALES
D ACCOUNTS
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
=> returns all rows from dept table and matching rows from emp table
A ACCOUNTS
B RESEARCH
C SALES
D ACCOUNTS
null OPERATIONS => unmatched from dept
FULL JOIN :-
-------------
SELECT e.ename,d.dname
FROM emp e FULL JOIN dept d
ON e.deptno = d.deptno
=> returns all rows from emp & dept
A ACCOUNTS
B RESEARCH
C SALES
D ACCOUNTS
E NULL => unmatched from emp
NULL OPERATIONS => unmatched from dept
22-sep-21
SELECT e.ename,d.dname
FROM emp e LEFT JOIN dept d
ON e.deptno = d.deptno
WHERE d.dname IS NULL
SELECT e.ename,d.dname
FROM emp e RIGHT JOIN dept d
ON e.deptno = d.deptno
WHERE e.ename IS NULL
SELECT e.ename,d.dname
FROM emp e FULL JOIN dept d
ON e.deptno = d.deptno
WHERE d.dname IS NULL
OR
e.ename IS NULL
Assignment :-
---------------
PROJECTS
projid name duration
100
101
102
EMP
empid ename sal projid
1 100
2 101
3 null
=> display employee details with project details and also display employees
not assigned to any project ?
=> display employee details with project details and also display projects
where no employee assigned to it ?
Non-Equi Join :-
----------------
=> non equi join is performed when tables are not sharing a common field
=> this join is called non equi join because here join condition is not based on "=" operator
and it is based on > < between operators.
Example :-
EMP SALGRADE
EMPNO ENAME SAL GRADE LOSAL HISAL
1 A 5000 1 700 1000
2 B 2500 2 1001 2000
3 C 1000 3 2001 3000
4 D 3000 4 3001 4000
5 E 1500 5 4001 9999
SELECT e.empno,e.ename,e.sal,
s.grade
FROM emp e JOIN salgrade s
ON e.sal BETWEEN s.losal AND s.hisal
1 A 5000 5
2 B 2500 3
3 C 1000 1
4 D 3000 3
5 E 1500 2
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
23-sep-21
SELF JOIN :-
-------------
Example :-
EMP
EMPNO ENAME MGR
7369 SMITH 7902
7499 ALLEN 7698
7521 WARD 7698
7566 JONES 7839
7654 MARTIN 7698
7698 BLAKE 7839
7782 CLARK 7839
7788 SCOTT 7566
7839 KING NULL
7902 FORD 7566
=> above table contains manager numbers but to display manager names we need to perform
self join
=> to perform self join the same table must be declared two times with different alias
EMP X EMP Y
SMITH FORD
ALLEN BLAKE
WARD BLAKE
JONES KING
MARTIN BLAKE
Assignment :-
=>
TEAMS
ID COUNTRY
1 IND
2 AUS
3 RSA
IND VS AUS
IND VS RSA
AUS VS RSA
=> cross join returns cross product or cartesian product of two tables
A=1,2
B=3,4
=> if cross join is performed between two tables then each record of table1 joined with each
and
every record of table2.
=> to perform cross join , submit the join query without join condition.
SELECT e.ename,d.dname
FROM emp e CROSS JOIN dept d
=> display dept wise no of employees in the output display dept names ?
---------------------------------------------------------------------------------------------------------
24-sep-21
Types of 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 > >= < <= = <>
SELECT *
FROM emp
WHERE hiredate < (SELECT hiredate FROM emp WHERE ename='king')
SELECT ename
FROM emp
WHERE sal = (SELECT MAX(sal) FROM emp)
SELECT ename
FROM emp
WHERE hiredate = (SELECT MIN(hiredate) FROM emp)
UPDATE emp
SET sal = CASE empno
WHEN 7499 THEN (SELECT sal FROM emp WHERE empno=7521)
WHEN 7521 THEN (SELECT sal FROM emp WHERE empno=7499)
END
WHERE empno IN (7521,7499)
27-sep-21
Multi-row subqueries :-
------------------------
=> if subquery returns more than one value then it is called multi row subquery
SELECT columns
FROM tabname
WHERE colname OP (SELECT STATEMENT)
SELECT *
FROM emp
WHERE job IN (SELECT job FROM emp WHERE ename IN ('smith','blake'))
ANY operator :-
----------------
=> use ANY operator when comparision with any value i.e. atleast one
IF X=800 FALSE
1500 TRUE
4500 TRUE
IF X=800 TRUE
X=1500 TRUE
X=4500 FALSE
ALL operator :-
-----------------
IF X=800 FALSE
1500 FALSE
4500 TRUE
IF X=800 TRUE
1500 FALSE
4500 FALSE
SELECT *
FROM emp
WHERE sal > ALL(SELECT sal FROM emp WHERE job='MANAGER')
single multi
= IN
co-related subqueries :-
--------------------------
=> if inner query references values of outer query then it is called co-related subquery
=> in co-related subquery execution starts from outer query and inner query is executed
for each return by outer query
=> use co-related subquery to execute subquery for each row return by outer query
Example :-
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 empno,ename,sal,deptno
FROM emp x
WHERE sal > (SELECT AVG(sal)
FROM emp
WHERE deptno = x.deptno)
1 A 5000 10 5000 > (select avg(sal) from emp where deptno=10) 4000 TRUE
2 B 3000 20 3000 > (select avg(sal) from emp where deptno=20) 4500
FALSE
3 C 4000 30 4000 > (select avg(sal) from emp where deptno=30) 4000
FALSE
4 D 6000 20 6000 > (select avg(sal) from emp where deptno=20) 4500 TRUE
5 E 3000 10 3000 > (select avg(sal) from emp where deptno=10) 4000
FALSE
=> display employees earning max(sal) in their dept ?
SELECT empno,ename,sal,deptno
FROM emp x
WHERE sal = (SELECT MAX(sal)
FROM emp
WHERE deptno = x.deptno)
28 -sep-21
EMP A EMP B
SAL SAL
5000 5000 3 > (0) TRUE
1000 1000 3 > (4) FALSE
3000 3000 3 > (2) TRUE
2000 2000 3 > (3) FALSE
4000 4000 3 > (1) TRUE
Derived tables :-
------------------
Examples :-
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 employee but to display top 5 employees
SELECT empno,ename,sal,
dense_rank() over (order by sal desc) as rnk
FROM emp
WHERE rnk<=5 => ERROR
column alias cannot be used in where clause because where clause is executed before
select
to overcome this problem use derived tables
SELECT *
FROM (SELECT empno,ename,sal,
dense_rank() over (order by sal desc) as rnk
FROM emp) E
WHERE rnk<=5
SELECT *
FROM (SELECT empno,ename,sal,
dense_rank() over (order by sal desc) as rnk
FROM emp) E
WHERE rnk=5
SELECT *
FROM ( SELECT empno,ename,sal ,
ROW_NUMBER() OVER (ORDER BY empno ASC) AS rno
FROM emp ) E
WHERE rno<=5
SELECT *
FROM ( SELECT empno,ename,sal ,
ROW_NUMBER() OVER (ORDER BY empno ASC) AS rno
FROM emp ) E
WHERE rno=5
SELECT *
FROM ( SELECT empno,ename,sal ,
ROW_NUMBER() OVER (ORDER BY empno ASC) AS rno
FROM emp ) E
WHERE rno%2=0
SELECT *
FROM ( SELECT empno,ename,sal ,
ROW_NUMBER() OVER (ORDER BY empno ASC) AS rno
FROM emp ) E
WHERE rno = (SELECT COUNT(*) FROM emp)
29-sep-21
note :- in derived tables outer query cannot be DML and it must be always SELECT , to
overcome this
problem use CTEs
CTE :-
--------
=> A Common Table Expression, also called as CTE in short form, is a temporary named
result
set that you can reference within a SELECT, INSERT, UPDATE, or DELETE statement.
=> in derived tables outer query cannot be dml but in CTEs outer query can be DML.
Syn :-
WITH <NAME>
AS
(SELECT STATEMENT),
-------------------
SELECT/INSERT/UPDATE/DELETE
WITH E
AS
(SELECT empno,ename,sal ,
ROW_NUMBER() OVER (ORDER BY empno ASC) AS rno
FROM emp)
DELETE FROM E WHERE RNO<=5
METHOD 1 :-
EMP22
ENO ENAME SAL
1 A 5000
2 B 6000
1 A 5000 => duplicate row
2 B 6000 => duplicate row
3 C 7000
step 1 :- group the rows whose eno,ename,sal are same then with in group generate row
numbers
SELECT eno,ename,sal,
ROW_NUMBER() OVER (PARTITION BY eno,ename,sal ORDER BY eno ASC) as rno
FROM emp22
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 emp22)
DELETE FROM E WHERE RNO>1
METHOD 2 :-
scalar subqueries :-
--------------------
SELECT (subquery1),(subquery2),----
FROM tabname
WHERE condition
Example 1 :-
SELECT (SELECT COUNT(*) FROM emp) as emp ,(SELECT COUNT(*) FROM DEPT)
as dept
emp dept
14 4
Example 2 :-
SELECT deptno,SUM(sal)
FROM emp
GROUP BY deptno
10 8750
20 10875
30 9400
display deptno,dept_totsal,totsal ?
Assignments :-
T1 T2
F1 C1
1 A
2 B
3 C
=> join the above two tables and display following output ?
1 A
2 B
3 C
T1
AMT
1000
-500
2000
-1000
3000
-5000
POS NEGATIVE
1000 -500
2000 -1000
3000 -5000
30-SEP-21
PIVOT operator :-
------------------
Syntax :-
SELECT *
FROM (SELECT STATEMENT) <ALIAS>
PIVOT
(
AGGR-EXPR FOR COLNAME IN (V1,V2,V3,--)
) AS <PIVOT_TABLE_NAME>
ORDER BY COL ASC/DESC
Example 1 :-
10 20 30
ANALYST ? ? ?
CLERK ? ? ?
MANAGER ? ? ?
SALESMAN ? ? ?
SELECT *
FROM (SELECT deptno,job,sal FROM emp) E
PIVOT
(
SUM(sal) FOR deptno IN ([10],[20],[30])
) AS PIVOT_TABLE
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_TBL
ORDER BY year ASC
STUDENT
SNO SNAME SUBJECT MARKS
1 A MAT 80
1 A PHY 90
1 A CHE 70
2 B MAT 60
2 B PHY 80
2 B CHE 70
OUTPUT :-
--------------------------------------------------------------------------------------------------------
01-oct-21
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 gurantee a property called atomocity i.e. all or none , if
transaction contains multiple dmls if all are successful then it must be saved , if
one of the dml fails then entire transaction must be cancelled.
=> the following commands provided sql server to handle transactions called
TCL(transaction control lang) commands
=> in sql server a txn begins implicitly and ends implilcitly with commit
=> user can also start transaction explicitly by using "BEGIN TRANSACTION" command
and end explicitly with COMMIT/ROLLBACK.
Example 1 :-
Example 2 :-
=> if txn ends with rollback then all the changes made in transaction are cancelled
Example 3 :-
SAVE TRANSACTION :-
--------------------
=> we can declare save transaction and we can cancel upto the save transaction
=> using this we can cancel part of the transaction
example 1 :-
SELECT * FROM a
10
20
30
40
example 2 :-
CREATE TABLE a(a int)
BEGIN TRANSACTION
INSERT INTO a VALUES(10)
INSERT INTO a VALUES(20)
SAVE TRANSACTION ST1
INSERT INTO a VALUES(30)
INSERT INTO a VALUES(40)
SAVE TRANSACTION ST2
INSERT INTO a VALUES(50)
INSERT INTO a VALUES(60)
ROLLBACK TRANSACTION ST1
SELECT * FROM a
10
20
02-oct-21
DB security :-
---------------
TABLES
VIEWS
SEQUENCES
INDEXES
VIEWS :-
---------
1 to provide security
2 to reduce complexity
=> view provides another level of security by granting specific rows and columns to users
1 simple views
2 complex views
simple views :-
---------------
example :-
CREATE VIEW V1
AS
SELECT empno,ename,job,deptno
FROM emp
=> sql server creates view "V1" and stores query but not query output
SELECT * FROM V1
=> when above query is submitted to sql server ,it rewrite the query as follows
VIJAY :-
1 SELECT * FROM V1
2 INSERT INTO V1 VALUES(9999,'ABC','CLERK',20) => 1 ROW AFFECTED
3 UPDATE V1 SET JOB='MANAGER' WHERE EMPNO=9999
4 UPDATE V1 SET SAL=5000 WHERE EMPNO=9999 => ERROR
CREATE VIEW V2
AS
SELECT empno,ename,job,deptno
FROM emp
WHERE deptno=20
VIJAY :-
=> above insert command executed successfully even though it is violating where condition
=> if view created with "WITH CHECK OPTION" then any dml command through view
violates where condition
that dml is not accepted
CREATE VIEW V3
AS
SELECT empno,ename,job,deptno
FROM emp
WHERE deptno=20
WITH CHECK OPTION
VIJAY :-
complex views :-
-----------------
=> view reduces complexity , with the help of views complex queries can be converted into
simple queries
Example 1 :-
=> after creating view whenever we want data from emp & dept tables instead of writing
join query write
the simple query as follows
Example 2 :-
=> after creating view , whenever we want dept wise summary simply execute the following
query
simple complex
Droping views :-
--------------
DROP VIEW V1
=> if base table is dropped what about views created on base table ?
WITH SCHEMABINDING :-
----------------------
=> if view created with schemabinding then sql server will not allow user to drop table if any
view
exists on the table.
Rules :-
-------------------------------------------------------------------------------------------------------
SEQUENCE :-
-----------
syn :-
Ex :-
CREATE SEQUENCE S1
START WITH 1
INCREMENT BY 1
MAXVALUE 5
SID SNAME
1 A
2 B
3 C
4 D
5 E
CREATE SEQUENCE S2
START WITH 100
INCREMENT BY 1
MAXVALUE 1000
INVOICE
INVNO INV_DT
MLN/1005/01 ?
MLN/1005/02 ?
CREATE SEQUENCE S3
START WITH 100
INCREMENT BY 1
MAXVALUE 1000
1 manually
2 automatically
manual :-
-----------
=> by default sequence created with NOCYCLE , it starts from start with and generates upto
to max
after reaching max then it stops.
=> if sequence created with cycle then it starts from start with and generates upto max and
afer
reaching max then it will be reset to min.
CREATE SEQUENCE S4
START WITH 100
INCREMENT BY 1
MAXVALUE 1000
MINVALUE 1
CYCLE
08-oct-21
INDEXES :-
----------
=> 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
=> when we submit a query to sql server , it goes through following phases
1 parsing
2 optimization
3 execution
parsing :-
----------
1 checks syntax
2 checks semantics
checks table exists or not
checks columns belongs to table or not
checks whether user has got permission to access the table or not
optimization :-
---------------
1 table scan
2 index scan
=> estimates the cost of each plan and selects best plan i.e. plan that takes less cost
execution :-
-------------
Types of Indexes :-
-------------------
1 Non Clustered
simple
composite
unqiue
2 Clustered
EMP
SAL 3000 ROOT
5000
1000 2000 4000
INTERMEDIATE
3000
2000
4000 1000 * 2500 * 4000 * 5000 * LEAF
1500 1500 * 3000 *,*
3000 2000 *
2500
composite index :-
------------------
=> if index created on multiple columns then index is called composite index
=> 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
G Q
=> primary key/unique columns are implicitly indexed by sql server and sql server creates a
unique
index on primary key/unique columns and unique index doesn't allow duplicate so primary
key/unique
also doesn't allow duplicates.
CLUSTERED INDEX :-
------------------
=> a non clustered index stores pointers to actual records but where as clustered 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 but where as in clustered in this order will be same.
50
30 70
10 A 50 E 60 D 80 B
20 C
SELECT * FROM cust => sql server goes to clustered index and reads all the nodes
from left to right
sp_helpindex emp
Droping index :-
----------------
---------------------------------------------------------------------------------------------------------
Features :-
-------------
1 improves performance :-
--------------------------
=> in tsql , sql commands can be grouped into one program and we submit that program to
sql server
so in tsql no of requests and response between user and sql server are reduced and
performance
is improved.
3 supports loops :-
------------------
=> loops are used to execute statements repeatedly multiple times. TSQL supports loops like
while loop
=> in tsql programs if any statement causes runtime 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 :-
-------------------------
=> tsql programs can be stored in db and applications which are connected to db can reuse
these programs
6 supports security :-
-----------------------
=> because these programs are stored in db so only authorized users can execute these
programs.
1 anonymous blocks
2 named blocks
stored procedures
stored functions
triggers
Anonymous blocks :-
-------------------
1 DECLARE
2 SET
3 PRINT
DECLARE statement :-
--------------------
Ex :- DECLARE @a int
DECLARE @s varchar(10)
DECLARE @d date
SET statement :-
----------------
ex :- SET @a = 1000
SET @s = 'abc'
SET @d = GETDATE()
PRINT statement :-
-------------------
PRINT @a
PRINT @s
PRINT @d
=> write a prog to input date and print day of the week ?
DECLARE @d date
SET @d='2022-01-01'
PRINT DATENAME(dw,@d)
=> to perform operations over db execute sql commands from tsql program
=> the following commands can be executed from tsql program.
1 DML (insert,update,delete,merge)
2 DRL (select)
3 TCL (commit,rollback,save transaction)
SELECT @var1=col1,
@var1=col2,
@var3=col3,-------
FROM tabname
[WHERE condition]
ex :-
1
SELECT @s=sal
FROM emp
WHERE empno=7369
SELECT @n=ename,@s=sal
FROM emp
WHERE empno=7369
=> write a prog to input empno and print name & salary ?
18-oct-21
conditional statements :-
--------------------------
1 IF-ELSE
2 MULTI IF
3 NESTED IF
IF-ELSE :-
-----------
IF COND
BEGIN
STATEMENTS
END
ELSE
BEGIN
STATEMENTS
END
MULTI-IF :-
-----------
IF COND1
BEGIN
STATEMENTS
END
ELSE IF COND2
BEGIN
STATEMENTS
END
ELSE IF COND3
BEGIN
STATEMENTS
END
ELSE
BEGIN
STATEMENTS
END
NESTED IF :-
-------------
IF COND
BEGIN
IF COND
BEGIN
STATEMENTS
END
ELSE
BEGIN
STATEMENTS
END
END
ELSE
BEGIN
STATEMENTS
END
=> write a prog to input empno and increment employee sal by specific amount and after
increment if
sal exceeds 5000 then cancel that increment ?
DECLARE @eno int,@amt money,@sal money
SET @eno=107
SET @amt=1000
BEGIN TRANSACTION
UPDATE emp SET sal=sal+@amt WHERE empno=@eno
SELECT @sal=sal FROM emp WHERE empno=@eno
IF @sal>5000
ROLLBACK
ELSE
COMMIT
=> write a prog to input empno and increment employee sal as follows
ACCOUNTS
ACCNO BAL
100 10000
101 20000
19-oct-21
Assignment :-
------------------
STUDENT
SNO SNAME S1 S2 S3
1 A 80 90 70
2 B 30 50 70
RESULT
SNO TOTAL AVG RESULT
=> write a prog to input sno and calculate total,avg,result and insert into result table ?
WHILE LOOP :-
-------------
WHILE(cond)
BEGIN
statements
END
DECLARE @x int=1
WHILE(@x<=20)
BEGIN
PRINT @x
SET @x = @x + 1
END
Assignment :-
----------------
=> write a prog to input string and print in the following pattern ?
input :- NARESH
output :-
N
A
R
E
S
H
INPUT :- NARESH
OUTPUT :-
N
NA
NAR
NARE
NARES
NARESH
Assignment :-
1
22
333
4444
55555
20-oct-21
CURSORS :-
----------
=> from tsql program if we submit a query to sql server , it goes to db and fetch the data and
copy
that data into temporary memory and using cursor we can give name to that memory and
access
row-by-row into tsql program and process the row.
1 DECLARE CURSOR
2 OPEN CURSOR
3 FETCH RECORDS FROM CURSOR
4 CLOSE CURSOR
5 DEALLOCATE CURSOR
DECLARE CURSOR :-
-----------------
OPEN CURSOR :-
---------------
Ex :- OPEN C1
=> a FETCH statement fetches one row at a time but to process multiple rows fetch
statement should
be executed multiple times , so fetch statement should be inside a loop.
CLOSE CURSOR :-
---------------
DEALLOCATE CURSOR :-
---------------------
ex :- DEALLOCATE C1
@@FETCH_STATUS :-
-----------------
Example 1 :-
Example 2 :-
-----------
Assignment :-
---------------
21-oct-21
=> write a prog to calculate all the students total,avg,result and insert into result table ?
STUDENT
SNO SNAME S1 S2 S3
1 A 80 90 70
2 B 30 50 70
RESULT
SNO TOTAL AVG RESULT
Assignment :-
-------------
RAISE_SALARY
EMPNO PCT
7369 15
7499 20
7521 10
7566 20
7654 15
=> write a prog to increment employee salaries based on the pct in raise_salary table ?
SCROLLABLE CURSOR :-
---------------------
=> by default cursor is FORWARD ONLY cursor and it supports forward navigation but
doesn't support
backward navigation.
=> if cursor declared with SCROLL then it is called SCROLLABLE cursor and it supports
both forward
backward navigation.
=>forward only cursor supports only FETCH NEXT statement but SCROLLABLE cursor
supports the following
fetch statements.
Example 1 :-
Example 2 :-
Assignment :-
-----------
---------------------------------------------------------------------------------------------------
23-oct-21
1 syntax errors
2 logical errors
3 runtime errors
=> errors that are raised during program execution are called runtime errors
ex :- declare @a tinyint
set @a=1000 => runtime error
=> if any statement causes runtime error then sql server display error message and continues
program
execution , to replace system generated error message with our own simple and user
friendly message
we need to handle runtime error.
BEGIN TRY
statement 1
statement 2
statement 3 => statements causes exception
statement 4
END TRY
BEGIN CATCH
statements => statements handles exception
END CATCH
=> if any statement in try block causes exception control is transferred to catch block and
executes
the statements in catch block.
Example 1 :-
DECLARE @a tinyint,@b tinyint,@c tinyint
BEGIN TRY
SET @a=100
SET @b=20
SET @c=@a/@b
PRINT @c
END TRY
BEGIN CATCH
PRINT 'ERROR'
END CATCH
Example 2 :-
Example 3 :-
RAISERROR :-
------------
state – the unique identification number that you can use to identify the code section
that is causing the error and values are between 0 and 255.
25-oct-21
1 stored procedures
2 stored functions
3 triggers
sub-programs :-
---------------
1 stored procedures
2 stored functions
Advantages :-
--------------
1 modular programming :-
-------------------------
=> with the help of procedures & function a big tsql program can be divided into small
modules
2 reusability :-
-----------------
=> proc & func can be centralized i.e. stored in db and applications which are connected to
db can
reuse procedures & functions.
3 security :-
------------
=> because these programs are stored in db so they are secured only authorized users can
executes
these programs
=> proc & func can be invoked from front-end applications like java,.net,php
5 improves performance :-
---------------------------
=> procedures improves performance because they are precompiled i.e. compiled already and
ready for
execution. when we create a procedure program is compiled and stored in db and whenever
we call
procedure only execution is repeated but not compilation.
stored procedures :-
----------------------
=> procedure is a named tsql block that accepts some input performs some action and may or
may not
returns a value.
=> procedures are created to perform one or more dml operations on db.
syn :-
parameters :-
--------------
1 INPUT
2 OUTPUT
INPUT :-
---------
OUTPUT :-
-----------
Example 1 :-
Execution :-
------------
Example 2 :-
Execution :-
declare @s money
execute raise_salary 101,1000,@s output
print @s
26-oct-21
Example 3 :-
ACCOUNTS
ACCNO ACTYPE BAL
100 S 10000
101 S 20000
EXECUTION :-
DECLARE @B MONEY
EXEC DEBIT 100,1000,@B OUTPUT
PRINT @B
Example 4 :-
=> create a
DECLARE @s VARCHAR(100)
EXECUTE insert_emp44 2,'C',1000,@s OUTPUT
PRINT @s
USER DEFINE FUNCTIONS :-
-----------------------
1 for calculations
2 to fetch value from db
=> these functions accepts some input performs some calculation and must return a value
=> return type of the functions is scalar types like int,varchar
=> return expression must be a scalar variable
Example 1 :-
CREATE OR ALTER FUNCTION CALC(@a int,@b int,@op char(1)) RETURNS int
AS
BEGIN
DECLARE @c int
IF @op='+'
SET @c=@a+@b
ELSE IF @op='-'
SET @c=@a-@b
ELSE IF @op='*'
SET @c=@a*@b
ELSE
SET @c=@a/@b
RETURN @c
END
Execution :-
-----------
1 sql commands
2 another tsql programs
3 front-end applications
27-oct-21
PRODUCTS
prodid pnameprice
100 A 2000
101 B 1000
102 C 1500
ORDERS
ordid prodid qty
1000 100 2
1000 101 1
1000 102 2
1001 100 2
1001 101 3
C1
prodid qty price
100 2 2000
101 1 1000
102 2 1500
SELECT DBO.GETORDAMT(1000) => 8000
example 1 :- create function to return list of employees working for specific dept ?
28-oct-21
Assignment :-
-------------
CUSTOMERS
CUSTID NAME ADDR DOB PHONE EMAILID
ACCOUNTS
ACCNO ACTYPE BAL CUSTID
TRANSACTIONS
TRID TTYPE TDATE TAMT ACCNO
CREATE SEQUENCE S1
START WITH 1
INCREMENT BY 1
MAXVALUE 99999
=> create following procedures & functions to implement various bank transactions ?
procedure function
3 returns values using out parameter returns value using return statement
5 cannot be executes from sql commands can be executed from sql commands
----------------------------------------------------------------------------------------------------------
TRIGGERS :-
----------
=> a trigger is also named TSQL block like procedure but executed implicitly by sql server
=> sql server executes trigger automatically whenever user submits DML/DDL commands
1 to control dml/ddls
2 to enforce complex rules & validations
3 to audit tables
4 to manage replicas
5 to generate values for primary key columns
syntax :-
---------
CREATE OR ALTER TRIGGER <NAME>
ON <TABNAME>
AFTER/INSTEAD OF INSERT,UPDATE,DELETE
AS
STATEMENTS
AFTER triggers :-
-----------------
=> if trigger is after then sql server executes the trigger after executing DML
INSTEAD OF trigger :-
--------------------
=> if trigger is instead of trigger then sql server executes the trigger instead of executing dml
29-oct-21
Magic tables :-
--------------
1 INSERTED
2 DELETED
=> these two tables are called magic tables because they can be accessed only with in trigger
=> using these two tables in triggers we can access data affected by dml
=> record user is trying to insert is copied to INSERTED table.
=> record user is trying to delete is copied to DELETED table.
=> record user is trying to update is copied to both INSERTED & DELETED table
DELETED
empno sal
555 5000
Example 4 :-
Example 5 :-
=> create trigger to insert details into emp_resign whenever employee resigns from
organization ?
EMP_RESIGN
empnoename hiredate dor
Auditing :-
----------
30-oct-21
INSTEAD OF triggers :-
----------------------
=> if trigger is instead of then sql server executes the trigger instead of executing dml
EMP99
ENO DNO
1 10
2 10
3 10
4 10
5 10 => not allowed
AFTER :- INSTEAD OF :-
--------- -------------
IF COND IF COND
BEGIN RAISERROR
ROLLBACK ELSE
RAISERROR DML
END
Dynamic SQL :-
-------------
=> SQL commands build at runtime are called dynamic sql commands
=> Dynamic SQL is useful when we don't know tablenames and column names until runtime.
1 EXEC
2 SP_EXECUTESQL
=> dynamic sql that we want to execute should be passed as a string to EXEC
01-nov-21
USING SP_EXECUTESQL :-
------------------------
=> Write a prog to print no of rows in each and every table ?
EMP ??
DEPT ??
CUST ??
----------------------------------------------------------------------------------------------------------
02-nov-21
MERGE command :-
----------------
scenario :-
02/11/21
CUSTS
CID CNAME CITY
10 A HYD
11 B MUM
CUSTT
CID CNAME CITY
10 A HYD
11 B MUM
03/11/21
CUSTS
CID CNAME CITY
10 A BLR => updated
11 B MUM
12 C DEL => inserted
syntax :-
Example :-
SELECT *
FROM TABNAME
WHERE EXISTS (SELECT STATEMENT )
Example :-
PRODUCTS
prodid pname price
100
101
102
SALES
dateid prodid custid qty amount
2021-11-03 100 10 1 2000
101 11 1 3000
SELECT *
FROM products p
WHERE EXISTS (SELECT * FROM sales WHERE prodid = p.prodid)
100
101
SELECT *
FROM products p
WHERE propdid IN (SELECT prodid FROM sales)
SELECT *
FROM products p
WHERE NOT EXISTS (SELECT * FROM sales WHERE prodid = p.prodid)
102