SQL Server 6pm
SQL Server 6pm
SQL Server 6pm
------------
30-NOV-21
Database :-
-----------
Types of Databases :-
----------------------
=> OLTP db are used for storing day-to-day transactions and OLAP db are
used for analysis.
=> OLTP db are used to run business and OLAP db are used to analyze business
C create
R read
U update
D delete
DBMS :-
--------
Evolution of DBMS :-
--------------------
01-dec-21
=> every table must contain primary key to uniquely identify the records
EX :- ACCNO,EMPID,CUSTID,AADHARNO,PANNO
RDBMS features :-
----------------
RDBMS softwares :-
------------------
ORDBMS softwares :-
--------------------
oracle
sql server
postgresql
summary :-
what is db ?
what is dbms ?
what is rdbms ?
what is ordbms ?
-------------------------------------------------------------------------------
02-DEC-21 SQL SERVER
-----------
Development Administration
version year
1 polybase
2 json
3 temporal table to save data changes.
4 dynamic data masking and row level security
1 identity cache
2 New String functions
3 Automatic Tuning
1 SERVER
2 CLIENT
SERVER :-
---------
=> server is a system where sql server software is installed and running.
=> inside the server sql server manages database.
=> inside the server sql server recieves requests from client and
process the requensts and sends response to client.
CLIENT :-
---------
1 connects to server
2 submit the requests to server
3 recieves response from server
client tool :-
--------------
LINKS :-
---------
https://www.microsoft.com/en-in/sql-server/sql-server-downloads
https://computingforgeeks.com/install-sql-server-developer-edition-on-windows-
server/
SSMS :-
download :-
https://docs.microsoft.com/en-us/sql/ssms/download-sql-server-management-studio-
ssms?view=sql-server-ver15
=> to connect to sql server open SSMS and enter following details
=> click OK
=> Data File stores data and log file stores operations
system database
master => New Query
DATATYPES
char(size) :-
-------------
=> allows character data upto 8000 chars
=> recommended for fixed length char columns
ex :- NAME CHAR(10)
sachin----
wasted
ravi------
wasted
=> in char datatype extra bytes are wasted , so char is not recommended
for variable length fields and char is recommended for fixed length
fields
ex :- STATE_CODE CHAR(2)
AP
TS
MH
COUNTRY_CODE CHAR(3)
IND
USA
07-dec-21
VARCHAR(size) :-
-----------------
ex :- NAME VARCHAR(10)
SACHIN----
released
RAVI------
released
VARCHAR(max) :-
---------------
ex :- TEXT VARCHAR(MAX)
ex :- PANNO CHAR(10)
VEHNO VARCHAR(10)
EMAIL VARCHAR(30)
PWD VARCHAR(10)
=> allows unicode characters (65536 chars) that includes all ASCII chars
and characters belongs to different languages.
Integer Types :-
-----------------
EX :- AGE TINYINT
EMPID SMALLINT
ACCNO INT
AADHARNO BIGINT
DECIMAL(p,s) :-
----------------
ex :- SALARY DECIMAL(7,2)
5000
5000.50
50000.50
500000.50 => NOT ACCEPTED
CURRENCY types :-
------------------
EX : SAL SMALLMONEY
BAL MONEY
ex :- DOB DATE
1998-10-05
LOGIN TIME
10:00:00
TXN_DT DATETIME
2021-12-07 11:00:00
Binary Types :-
---------------
BINARY
VARBINARY
VARBINARY(MAX)
binary :-
---------
ex :- photo binary(1000)
varbinary :-
-------------
ex :- photo varbinary(1000)
varbinary(max) :-
-----------------
ex :- photo varbinary(max)
08-dec-21
Rules :-
---------
Example :-
EMP
empid ename job sal age hiredate
SP_HELP :-
---------
EX :- SP_HELP emp
empid tinyint 1
ename varchar 10
job varchar 10
sal smallmoney 4
age tinyint 1
hiredate date 3
09-dec-21
inserting nulls :-
-------------------
method 1 :-
method 2 :-
Displaying Data :-
----------------
WHERE clause :-
---------------
SELECT columns
FROM tabname
WHERE condition
condition :-
-----------
COLNAME OP VALUE
=> OP must be any relational operator like > >= < <= = <>
=> if cond = true row is selected
=> if cond = false row is not selected
10-dec-21
compound condition :-
---------------------
=> display employees working as clerk and earning more than 4000 ?
=> display employees earning more than 5000 and less than 10000 ?
IN operator :-
--------------
BETWEEN operator :-
-------------------
SELECT * FROM emp WHERE hiredate NOT BETWEEN '2020-01-01' AND '2020-12-31'
scenario :-
-----------
PRODUCTS
prodid pname price category brand
=> display list of mobiles phones price between 10000 and 20000
and brand = redmi,realme,samsung ?
SELECT *
FROM products
WHERE category='mobiles'
AND
price BETWEEN 10000 AND 20000
AND
brand IN ('redmi','realme','samsung')
13-DEC-21
=> display employees working as clerk,manager and earning between 5000 and
10000 and joined in 2021 year ?
scenario :-
STUDENT
sno sname s1 s2 s3
1 A 80 90 70
2 B 30 70 60
SELECT *
FROM student
WHERE s1>=35 AND s2>=35 AND s3>=35
SELECT *
FROM student
WHERE s1<35 OR s2<35 OR s3<35
LIKE operator :-
----------------
=> display employees where 'a' is the 3rd char from last ?
IS operator :-
----------------
summary :-
-----------
14-dec-21
ORDER BY clause :-
-----------------
=> ORDER BY clause is used to sort data based on one or more columns
either in ascending or in descending order.
SELECT columns
FROM tabname
[WHERE cond]
ORDER BY <col> [ASC/DESC]
SELECT *
FROM emp
ORDER BY ename ASC
SELECT *
FROM emp
ORDER BY sal DESC
SELECT *
FROM emp
ORDER BY hiredate ASC
=> arrange employee list dept wise asc and with in dept sal wise desc ?
SELECT *
FROM emp
ORDER BY deptno ASC,sal DESC
1 A 3000 20 4 D 5000 10
2 B 4000 10 2 B 4000 10
3 C 3000 30 ------> 5 E 6000 20
4 D 5000 10 1 A 3000 20
5 E 6000 20 6 F 4000 30
6 F 4000 30 3 C 3000 30
scenario :-
-----------
STUDENT
sno sname mat phy che
1 A 80 90 70
2 B 60 70 50
3 C 90 80 70
4 D 90 70 80
=> arrange student list avg wise desc ,mat desc,phy desc ?
SELECT *
FROM student
ORDER BY (mat+phy+che)/3 DESC,mat DESC,phy DESC
3 C 90 80 70
4 D 90 70 80
1 A 80 90 70
2 B 60 70 50
SELECT empno,ename,job,sal
FROM emp
WHERE job IN ('CLERK','MANAGER')
ORDER BY sal DESC
15-DEC-21
DISTINCT clause :-
-------------------
ANALYST
CLERK
MANAGER
PRESIDENT
SALESMAN
SELECT DISTINCT deptno FROM emp
10
20
30
TOP clause :-
--------------
SELECT TOP 5 *
FROM emp
ORDER BY sal DESC
INSERT
UPDATE
DELETE
SET IMPLICIT_TRANSACTIONS ON
=> to save operation then execute COMMIT and to cancel operation execute ROLLBACK
UPDATE command :-
-------------------
NULL assignment =
NULL comparision IS
UPDATE emp
SET sal = sal + (sal*0.2) , comm = comm + (comm*0.1)
WHERE job='salesman'
AND
hiredate LIKE '1981%'
16-DEC-21
DELETE command :-
------------------
CREATE
ALTER
DROP
TRUNCATE
ALTER command :-
-----------------
1 add columns
2 drop columns
3 modify a column
Adding column :-
-----------------
after adding by default the column is filled with NULL , to insert data
into the new column use UPDATE command.
Droping Column :-
------------------
Modifying column :-
--------------------
1 changing size
2 changing datatype
DROP command :-
----------------
TRUNCATE command :-
---------------------
=> deletes all the data from table but keeps structure
=> will empty the table.
=> releases memory allocated for table.
=> when truncate command is executed then sql server goes to memory and
releases all the pages allocated for table and when pages are released
then data stored in the pages are also deleted.
DELETE VS TRUNCATE :-
----------------------
DELETE TRUNCATE
5 slower faster
SP_RENAME 'OLD-TABNAME','NEW-TABNAME'
=> rename table emp to employees ?
SP_RENAME 'EMP','EMPLOYEES'
SP_RENAME 'EMPLOYEES.COMM','BONUS'
IDENTITY :-
----------
syntax :- IDENTITY(SEED,INCR)
Example :-
CID CNAME
100 A
101 B
102 C
103 D
104 E
DELETE VS TRUNCATE :-
DELETE TRUNCATE
-------- ----------
DBCC CHECKIDENT(tablename,reseed,value)
DBCC CHECKIDENT('CUST',RESEED,99)
18-dec-21
Types of functions :-
---------------------
1 date
2 string
3 mathematical
4 conversion
5 special
6 analytical
7 aggregate
Date functions :-
-----------------
syn :- DATEPART(interval,date)
07 SATURDAY
01 JAN-MAR
02 APR-JUN
03 JUL-SEP
04 OCT-DEC
DATEPART(hh,GETDATE()) => 8
DATEPART(mi,GETDATE()) => 22
DATEPART(ss,GETDATE()) => 20
DATENAME() :-
MM DW
DATEPART 04 07
SELECT DATENAME(dw,'1947-08-15')
21-dec-21
DATEDIFF() :-
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-12-21 ?
EOMONTH() :-
------------
Questions :-
STRING functions :-
--------------------
UPPER() :-
----------
UPPER(string/colname)
LOWER() :-
-----------
LOWER(string/colname)
22-dec-21
=> display employees name starts and ends with same char ?
scenario :-
-----------
SELECT empno,ename,
as emailid
FROM emp
UPDATE emp
SET emailid = LEFT(ename,3)+LEFT(empno,3)+'@microsoft.com'
REPLICATE() :-
--------------
REPLICATE(str,no of times)
****
scenario :-
------------
ACCOUNTS
ACCNO ACTYPE BAL
12345678936 S 10000
REPLICATE('X',4) + RIGHT(ACCNO,4)
12XXXX4567
23-dec-21
REPLACE() :-
------------
REPLACE(str1,str2,str3)
TRANSLATE() :-
-------------
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 empno,ename,
TRANSLATE(sal,'0123456789.','$Kp*H@b&#%^') as sal
FROM emp
Assignment :-
------------
SUBSTRING() :-
--------------
=> used to extract part of the string starting from specific position.
SUBSTRING(string,start,length)
CHARINDEX() :-
--------------
CHARINDEX(char,string,[start])
Assignment :-
CUST
CID NAME
10 sachin tendulkar
11 virat kohli
Mathematical Functions :-
-------------------------
ABS(number)
POWER(num1,num2)
SQUARE(number)
ROUND(number,decimal places)
38------------------38.5-----------------------39
300---------------350-------------------400
380---------------385--------------------390
0-----------------500----------------------1000
24-DEC-21
conversion functions :-
-----------------------
=> these functions are used to convert one type to another type
1 CAST
2 CONVERT
CAST :-
--------
CAST(source-expr AS target-type)
SELECT CAST(10.5 AS INT) => 10
SELECT ename + ' earns ' + sal FROM emp => ERROR
SELECT ename + ' joined on ' + CAST(hiredate as VARCHAR) + ' as '+ job
FROM emp
CONVERT() :-
-------------
CONVERT(target-type,source-expr)
CONVERT(varchar,date,style-number)
SELECT ename,
CONVERT(varchar,hiredate,104) as hiredate
FROM emp
CONVERT(varchar,expr,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
1 Commas every three digits to the left of the decimal point, and two digits
to the right of the decimal point
2 No commas every three digits to the left of the decimal point, and four
digits to the right of the decimal point
special functions :-
--------------------
ISNULL() :-
------------
ISNULL(arg1,arg2)
27-dec-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.
=> 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 :-
-----------------------
=> used to find ranks with in group for example to find ranks with in dept
first we need to divide the table dept wise using PARTITION BY clause
and apply dense_rank function on each partition instead of applying it on
whole table.
SELECT empno,ename,sal,deptno,
DENSE_RANK() OVER (PARTITION BY deptno ORDER BY sal DESC) as rnk
FROM emp
ROW_NUMBER() :-
----------------
SELECT empno,ename,sal,
ROW_NUMBER() OVER (ORDER BY empno ASC) as rno
FROM emp
Aggregate Functions :-
-----------------------
=> all these functions process group of rows and returns one value
MAX(arg)
MIN(arg)
=> round total sal to hundreds and display with thousand seperator ?
SELECT CONVERT(VARCHAR,ROUND(SUM(sal),-2),1)
FROM emp => 29,000
29000---------29050-----------29100
28-dec-21
AVG(arg)
COUNT(expr)
SELECT COUNT(empno) FROM emp => 14
COUNT(*) :-
-----------
T1
F1
10
NULL
20
NULL
30
COUNT(F1) = 3
COUNT(*) = 5
summary :-
date :- getdate,datepart,datename,datediff,dateadd,eomonth
string :- upper,lower,len,left,right,substring,charindex,replicate,
replate,translate
math :- abs,power,sqrt,square,round,ceiling,floor
convesion :- cast,convert
special :- ISNULL
analytical :- RANK,DENSE_RANK,ROW_NUMBER
aggregate :- MAX,MIN,SUM,AVG,COUNT,COUNT(*)
-----------------------------------------------------------------------------
GROUP BY clause :-
------------------
=> GROUP BY clause is used to group rows based on one or more columns to
calculate min,max,sum,avg,count for each group.
EMP
empno ename sal deptno
1 A 5000 10
2 B 4000 20 10 8000
3 C 6000 30-------GROUP BY-------> 20 6000
4 D 2000 20 30 10000
5 E 3000 10
6 F 4000 30
=> GROUP BY clause is used to convert detailed data into summarized data
which is useful for analysis.
syntax :-
SELECT columns
FROM tabname
[WHERE condition]
GROUP BY colname
[HAVING condition]
[ORDER BY colname ASC/DESC]
Execution :-
------------
FROM
WHERE
GROUP BY
HAVING
SELECT
ORDER BY
FROM emp :-
EMP
empno ename sal deptno
1 A 5000 10
2 B 4000 20
3 C 6000 30
4 D 2000 20
5 E 3000 10
6 F 4000 30
GROUP BY deptno :-
10
1 A 5000
5 E 3000
20
2 B 4000
4 D 2000
30
3 C 6000
6 F 4000
10 8000
20 6000
30 10000
29-dec-21
NOTE :- sql server cannot calculate dept wise count before group by
and it can calculate only after group by. so apply the condition
COUNT(*) > 3 after group by by using HAVING clause.
SELECT job,COUNT(*)
FROM emp
WHERE job IN ('CLERK','MANAGER')
GROUP BY job
WHERE VS HAVING :-
------------------
WHERE HAVING
=> display dept wise and with in dept job wise total salary ?
10 CLERK 1300
MANAGER 2450
PRESIDENT 5000
20 ANALYST 6000
CLERK 1900
MANAGER 2975
30 CLERK 950
MANAGER 2860
SALESMAN 5600
=> both functions are used to calculate subtotals and grand total
ROLLUP :-
--------
=> rollup displays subtotals for each group and also displays grand total
30-dec-21
CUBE :-
-------
=> cube displays subtotals for each group by column (deptno,job) and also
displays grand total.
Assignment :-
-------------
PERSONS
AADHARNO NAME GENDER AGE ADDR CITY STATE
SALES
DATEID PRODID CUSTID QTY AMOUNT
2021-12-30 100 10 1 1000
=> display year wise and with in year quarter wise total sales amount and
display year wise subtotals ?
summary :-
----------
1 importance of group by
2 writing queries using group by clause
3 where vs having
4 rollup & cube
------------------------------------------------------------------------------
CASE statement :-
------------------
1 simple case
2 searched case
simple case :-
--------------
CASE expr/colname
WHEN value1 THEN return expr1
WHEN value2 THEN return expr2
------------------
ELSE return expr
END
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
UPDATE emp
SET sal = CASE deptno
WHEN 10 THEN sal+(sal*0.1)
WHEN 20 THEN sal+(sal*0.15)
WHEN 30 THEN sal+(sal*0.2)
ELSE sal+(sal*0.05)
END
searched case :-
-----------------
=> use searched case when conditions not based on "=" operator
CASE
WHEN cond1 THEN return expr1
WHEN cond2 THEN return expr2
--------------
ELSE return expr
END
SELECT ename,sal,
CASE
WHEN sal>3000 THEN 'Hisal'
WHEN sal<3000 THEN 'Losal'
ELSE 'Avgsal'
END as salrange
FROM emp
31-dec-21
Integrity 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 :-
-----------
example :-
UNIQUE :-
----------
example :-
PRIMARY KEY :-
--------------
=> in rdbms in tables one column must be there to uniquely identify the
records and that column must be declared with primary key.
Example :-
=> 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.
03-jan-22
CHECK constraint :-
-------------------
syn :- CHECK(condition)
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.
PROJECTS
projid name duration cost client
100 A 5 YEARS 200 TATA MOTORS
101 B 3 YEARS 150 DBS
102 C 4 YEARS 250 L&T
EMP
empid ename sal projid REFERENCES projects(projid)
1 A 5000 100
2 B 3000 101
3 C 4000 999 => invalid
4 D 3000 100 => valid
5 E 2000 NULL => valid
=> values entered in foreign key column should match with values entered in
primary key column.
=> after declaring foreign key a relationship is created between two tables
called parent/child relationship.
=> primary key table is parent and foreign key table is child.
Assignment :-
---------------
ACCOUNTS
ACCNO ACTYPE BAL
rules :-
TRANSACTIONS
TRID TTYPE TDATE TAMT ACCNO
Rules :-
DEFAULT :-
---------
=> while inserting if we skip hiredate then sql server inserts default value
empno hiredate
100 2022-01-03
101 2021-12-31
102 null
04-jan-22
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
PRODUCTS
prodid pname mfd_dt exp_dt
100 ABC 2022-01-01 2021-01-01 invalid
=> in some tables we may not uniquely identify the records by using single
column and we need combination of columns to uniquely identify the records.
if combination of columns uniquely identify records then declare that
combination
as primary key at table level.
example :-
ORDERS PRODUCTS
ordid ord_dt del_dt prodid pname price
1000 2022-01-03 2022-01-10 100 A 1000
1001 2022-01-04 2022-01-10 101 B 2000
ORDER_DETAILS
ordid prodid qty
1000 100 1
1000 101 2
1001 100 2
1001 101 1
=> in the above example ordid & prodid combination uniquely identifies the
records so declare this combination as primary key at table level.
Assignment :-
-------------
PRODUCTS
prodid pname price
100 A 1000
101 B 2000
CUSTOMERS
custid name addr
1 A HYD
2 B HYD
SALES
DATEID PRODID CUSTID QTY AMOUNT
2022-01-03 100 1 1 1000
2022-01-03 101 1 1 2000
2022-01-03 100 2 1 1000
2022-01-04 100 1 1 1000
=> identify PRIMARY KEY & FOREIGN KEY in above examples and write create
table script ?
05-jan-21
=> primary key cannot be added to nullable column , to add primary key
=> above command fails because in emp table some of the employee salaries
are less than 3000. while adding constraint sql server also validates
existing data.
WITH NOCHECK :-
--------------
=> if check constraint is added with "WITH NOCHECK" then sql server will not
validate existing data it validates only new data.
=> add fk to column dno that refers dept table primary key ?
Adding UNIQUE :-
------------------
Droping constraints :-
----------------------
example :-
06-jan-21 :-
------------
DELETE rules :-
----------------
ON DELETE NO ACTION :-
----------------------
scenario :-
-----------
ACCOUNTS
ACCNO ACTYPE BAL
100 S 10000
101 S 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.
CREATE TABLE dept77
(
dno int primary key,
dname varchar(10)
)
scenario :-
-----------
ACCOUNTS
ACCNO ACTYPE BAL
100 S 10000
101 S 20000
TRANSACTIONS
TRID TTYPE TDATE TAMT ACCNO
1 W /// 2000 100
2 D /// 5000 100
=> if parent row is deleted then child rows are not deleted but fk will be
set to null.
1 A NULL
2 B NULL
=> if parent row is deleted then child rows are not deleted but fk will be
set to default value.
1 A 20
2 B 20
UPDATE rules :-
----------------
1 ON UPDATE NO ACTION
2 ON UPDATE CASCADE
3 ON UPDATE SET NULL
4 ON UPDATE SET DEFAULT
=================================================================================
07-jan-21 JOINS
------
=> join is an operation performed to fetch data from two or more tables.
=> 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 combine data stored in multiple tables we need to join those
tables.
example :-
ORDERS CUSTOMERS
ordid ord_dt del_dt cid CID NAME ADDR
1000 05/ 8/ 10 10 A HYD
1001 06/ 9/ 11 11 B MUM
1002 07/ 9/ 12 12 C DEL
report :-
Types of joins :-
-----------------
=> To perform equi join between the two tables there must be a common field
and name of the common field need not to be same and pk-fk relationship is
not compulsory.
=> Equi join is performed based on the common field with same datatype.
SELECT columns
FROM tab1 INNER JOIN tab2
ON join-condition ;
join condition :-
------------------
=> based on the given join condition sql server joins the records of two tables
=> join condition decides which record of 1st table joined with which record of
2nd table
table1.commonfield = table2.commonfield
Example :-
EMP DEPT
EMPNO ENAME SAL DEPTNO DEPTNO DNAME LOC
1 A 3000 10 10 ACCOUNTS ?
2 B 5000 20 20 RESEARCH ?
3 C 4000 30 30 SALES ?
4 D 2000 10 40 OPERATIONS ?
5 E 3000 NULL
SELECT empno,ename,sal,dname,loc
FROM emp INNER JOIN dept
ON emp.deptno = dept.deptno
SELECT empno,ename,sal,deptno,dname,loc
FROM emp INNER JOIN dept
ON emp.deptno = dept.deptno => ERROR
=> 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 e INNER JOIN dept d
ON e.deptno = d.deptno
08-jan-22
SELECT columns
FROM tab1 INNER JOIN tab2
ON cond1
INNER JOIN tab3
ON cond2
INNER JOIN tab4
ON cond3
example :-
SELECT e.ename,d.dname,l.city,l.state,c.country_name
FROM emp e INNER JOIN dept d
ON e.deptno = d.deptno
INNER JOIN locations l
ON d.locid = l.locid
INNER JOIN countries c
ON l.country_id = c.country_id
Assignment :-
-------------
ORDERS CUSTOMERS
ordid ord_dt del_dt cid CID NAME ADDR
1000 05/ 8/ 10 10 A HYD
1001 06/ 9/ 11 11 B MUM
1002 07/ 9/ 12 12 C DEL
OUTER JOIN :-
------------
=> inner join returns only matching records but cannot return unmatched
records but to get unmatched records also perform outer join.
EMP DEPT
EMPNO ENAME SAL DEPTNO DEPTNO DNAME LOC
1 A 3000 10 10 ACCOUNTS ?
2 B 5000 20 20 RESEARCH ?
3 C 4000 30 30 SALES ?
4 D 2000 10 40 OPERATIONS ? => unmatched record
5 E 3000 NULL => unmatched record
LEFT JOIN :-
------------
=> returns all rows (matched + unmatched ) from left side table and
matching rows from right side table
SELECT e.ename,d.dname
FROM emp e LEFT JOIN dept d
ON e.deptno = d.deptno
=> above query returns all rows from emp and matching rows from dept
A 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
=> above query returns all rows from emp & dept
A ACCOUNTS
B RESEARCH
C SALES
D ACCOUNTS
E NULL => unmatched from emp
NULL OPERATIONS => unmatched from dept
10-jan-22
Assignment :-
-------------
PROJECTS
projid pname duration cost client
100
101
102
EMP
empid ename sal projid
1 100
2 101
3 100
4 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 is performed between two tables not sharing a common field.
=> here join conditions 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.empno,e.ename,e.sal,
s.grade
FROM emp e JOIN salgrade s
ON e.sal BETWEEN s.losal and s.hisal
WHERE s.grade = 3
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
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
7839 KING NULL
7902 FORD 7566
=> above table contains manager number but to display manager name
perform self join.
=> to perform self join the same table must be declared two times with
different alias in from clause.
EMP X EMP Y
EMPNO ENAME MGR EMPNO ENAME MGR
7369 SMITH 7902 7369 SMITH 7902
7499 ALLEN 7698 7499 ALLEN 7698
7521 WARD 7698 7521 WARD 7698
7566 JONES 7839 7566 JONES 7839
7654 MARTIN 7698 7654 MARTIN 7698
7698 BLAKE 7839 7698 BLAKE 7839
7839 KING NULL 7839 KING NULL
7902 FORD 7566 7902 FORD 7566
SMITH FORD
ALLEN BLAKE
WARD BLAKE
17-jan-22 :-
SELECT x.ename,y.ename
FROM emp x JOIN emp y
ON x.mgr = y.empno
WHERE y.ename='blake'
SELECT x.ename,y.ename
FROM emp x JOIN emp y
ON x.mgr = y.empno
WHERE x.ename='blake'
SELECT x.ename,y.ename
FROM emp x JOIN emp y
ON x.mgr = y.empno
WHERE x.sal > y.sal
SELECT x.ename,y.ename
FROM emp x JOIN emp y
ON x.mgr = y.empno
WHERE x.hiredate < y.hiredate
Assignment :-
-------------
TEAMS
ID COUNTRY
1 IND
2 AUS
3 ENG
OUTPUT :-
IND VS AUS
IND VS ENG
AUS VS ENG
Display ENAME DNAME GRADE MNAME ?
----- ----- ------- -------
EMP DEPT SALGRADE EMP
=> cross join returns cross product or cartesian product of two tables
A=1,2
B=3,4
=> if cross join performed between two tables then each record of 1st table
joined with each and every record of 2nd table.
SELECT e.ename,d.dname
FROM emp e CROSS JOIN dept d
10 3
20 5
30 6
Assignment :-
-------------
SALES
DATEID PRODID CUSTID QTY AMOUNT
2022-01-17 100 10 1 1000
PRODUCTS
PRODID PNAME PRICE CATEGORY BRAND
100 AAA 1000 ELECTRONICS SAMSUNG
CUSTOMERS
CUSTID NAME ADDR COUNTRY
10 XYZ HYD IND
18-jan-22
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 set operations are performed between set of rows return
by two select statements.
SELECT STATEMENTS 1
UNION/UNION ALL/INTERSECT/EXCEPT
SELECT STATEMENT 2
Rules :-
CLERK
MANAGER
ANALYST
CLERK
ANALYST
SALESMAN
SALESMAN
SALESMAN
MANAGER
SALESMAN
CLERK
UNION :-
---------
ANALYST
CLERK
MANAGER
SALESMAN
ANALYST 3450.00
ANALYST 3950.00
CLERK 920.00
CLERK 1140.00
CLERK 1265.00
MANAGER 3420.00
MANAGER 4421.25
SALESMAN 1500.00
SALESMAN 1920.00
SALESMAN 4160.00
UNION JOIN
scenario :-
-----------
EMP_US
ENO ENAME SAL DNO
DEPT
EMP_IND DNO DNAME LOC
ENO ENAME SAL DNO
SELECT e.*,d.*
FROM emp_us e INNER JOIN dept d
ON e.dno = d.dno
SELECT e.*,d.*
FROM emp_us e INNER JOIN dept d
ON e.dno = d.dno
UNION
SELECT e.*,d.*
FROM emp_ind e INNER JOIN dept d
ON e.dno = d.dno
UNION ALL :-
------------
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 from the 1st query output and not present in 2nd query output
ANALYST
SALESMAN
19-jan-22 :-
T1 T2
F1 C1
1 1
2 2
3 3
10 40
20 50
30 60
1 inner join
2 left join
3 right join
4 full join
5 union
6 union all
7 intersect
8 except
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 can be any relational operator like > >= < <= = <>
Examples :-
SELECT *
FROM emp
WHERE sal > (SELECT sal FROM emp WHERE ename='blake')
SELECT *
FROM emp
WHERE hiredate < (SELECT hiredate FROM emp WHERE ename='king')
SELECT ename
FROM emp
WHERE sal = MAX(sal) => ERROR
aggregate functions are not allowed in where clause and they are allowed
only in select,having clauses.
SELECT ename
FROM emp
WHERE sal = (SELECT MAX(sal) FROM emp)
SELECT ename
FROM emp
WHERE hiredate = (SELECT MIN(hiredate) FROM emp)
=> update employee sal to max(sal) of 30th dept whose empno = 7499 ?
UPDATE emp
SET sal = (SELECT MAX(sal) FROM emp WHERE deptno=30)
WHERE empno=7499
20-jan-22
multirow subqueries :-
-----------------------
=> if inner query returns more than one value then it is called multirow
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 for > < comparision with multiple values
IF X=800 FALSE
X=1500 TRUE
X=4500 TRUE
IF X=800 TRUE
1500 TRUE
4500 FALSE
ALL operator :-
---------------
=> use ALL operator for > < comparision with multiple values
IF X=800 FALSE
1500 FALSE
4500 TRUE
IF X=800 TRUE
1500 FALSE
4500 FALSE
SINGLE MULTI
= IN
> >ANY >ALL
SELECT *
FROM emp
WHERE sal > (SELECT sal FROM emp WHERE job='MANAGER')
SELECT *
FROM emp
WHERE sal > ANY(SELECT sal FROM emp WHERE job='MANAGER')
CO-RELATED SUBQUERIES :-
------------------------
=> execution starts from outer query and inner query is executed no of times
depends on no of rows return by outer query.
=> use co-related subquery to execute subquery for each row return by outer query
Example 1 :-
EMP
EMPNO ENAME SAL DEPTNO
1 A 5000 10
2 B 3000 20
3 C 4000 30
4 D 6000 20
5 E 3000 10
SELECT *
FROM emp e
WHERE sal > (SELECT AVG(sal) FROM emp WHERE deptno=e.deptno)
Example 2 :-
=> display employees earning max sal in their dept ?
SELECT *
FROM emp e
WHERE sal = (SELECT MAX(sal) FROM emp WHERE deptno=e.deptno)
31-jan-22
=> EXISTS & NOT EXISTS are used to check whether record exists in the table or not
SELECT *
FROM tabname
WHERE EXISTS (SELECT STATEMENT)
SELECT *
FROM tabname
WHERE NOT EXISTS (SELECT STATEMENT)
scenario :-
------------
CUSTS CUSTT
CID NAME ADDR CID NAME ADDR
10 A HYD 10 A HYD
11 B MUM 11 B MUM
12 C DEL
=> display records from custs table which are there in custt table ?
METHOD 1 :-
SELECT *
FROM custs s
WHERE EXISTS (SELECT * FROM custt WHERE cid=s.cid)
10 A HYD
11 B MUM
METHOD 2 :-
SELECT *
FROM CUSTS
WHERE CID IN (SELECT CID FROM CUSTT)
10 A HYD
11 B MUM
=> SQL SERVER recommends EXISTS operator than IN operator because EXISTS gives
good performance than IN operator.
=> display records from custs table which are not there in custt table ?
method 1 :-
SELECT *
FROM custs s
WHERE NOT EXISTS (SELECT * FROM custt WHERE cid=s.cid)
12 C DEL
method 2 :-
SELECT *
FROM custs
WHERE cid NOT IN (SELECT cid FROM custt)
12 C DEL
=> sql server recommends NOT EXISTS operator than NOT IN because NOT EXISTS
gives good performance than NOT IN operator.
Derived tables :-
-----------------
SELECT columns
FROM (SELECT statement) <alias>
WHERE condition
=> by default sql server executes the clauses in the following order
FROM
WHERE
GROUP BY
HAVING
SELECT
ORDER BY
Example 1 :-
=> display ranks of all 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 displays 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 *
FROM (SELECT empno,ename,sal,
DENSE_RANK() OVER (ORDER BY sal DESC) as rnk
FROM emp) E
WHERE rnk<=5
Example 2 :-
01-FEB-22
Example 3 :-
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 BETWEEN 5 AND 10
SELECT *
FROM ( SELECT empno,ename,sal,
ROW_NUMBER() OVER (ORDER BY empno ASC) as rno
FROM emp ) E
WHERE rno%2=0
=> delete first 5 rows from emp table ?
DELETE
FROM ( SELECT empno,ename,sal,
ROW_NUMBER() OVER (ORDER BY empno ASC) as rno
FROM emp ) E
WHERE rno<=5 => ERROR
CTE :-
--------
=> in derived tables outer query must be SELECT but in CTEs outer query
can be SELECT/INSERT/UPDATE/DELETE.
syntax :-
Example 1 :-
WITH E
AS
(SELECT empno,ename,sal,
ROW_NUMBER() OVER (ORDER BY empno ASC) as rno
FROM emp)
DELETE FROM E WHERE rno<=5
Example 2 :-
EMP44
ENO ENAME SAL
1 A 5000
2 B 6000
1 A 5000 => duplicate record
2 B 6000 => duplicate record
3 C 7000
step 1 :-
SELECT eno,ename,sal,
ROW_NUMBER() over (partition by eno,ename,sal ORDER BY eno ASC) as rno
FROM emp44
eno ename sal rno
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)
DELETE FROM E WHERE RNO>1
scalar subqueries :-
---------------------
SELECT (subquery1),(subquery2),----------
FROM tabname
WHERE cond
=> use scalar subquery to show the query output in seperate column
Example 1 :-
SELECT (SELECT COUNT(*) FROM emp) as emp,(SELECT COUNT(*) FROM dept) as dept
emp dept
14 4
using where
order by
functions
group by
joins
set operators
subqueries
Database Transactions :-
------------------------
ex :- money transfer
acct1----------1000----------------->acct2
update1 update2
(bal=bal-1000) (bal=bal+1000)
=> in sql server a txn begins implicitly with DML/DDL command and ends
implicitly with COMMIT.
=> user can also start transaction explicitly with "BEGIN TRANSACTION"
command and ends explicitly with COMMIT/ROLLBACK command.
Example 1 :-
=> if txn ends with commit then it is called successful transaction and
operations are saved.
Example 2 :-
Example 3 :-
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
example 1 :-
select * from a
10
20
example 2 :-
select * from a
10
20
30
40
03-feb-22
Database Security :-
--------------------
SERVER (login)
DATABASE (users)
TABLES (privileges)
ROWS & COLS (views)
04-feb-22
Database Objects :-
--------------------
TABLES
VIEWS
SYNONYMS
SEQUENCES
INDEXES
PROCEDURES
FUNCTIONS
TRIGGERS
VIEWS :-
---------
1 to provide security
2 to reduce complexity
=> view provides another level of security called row & column level i.e.
with the help of views we can grant specific rows and columns to users
1 simple views
2 complex views
simple views :-
----------------
Ex :-
CREATE VIEW V1
AS
SELECT empno,ename,job,deptno FROM emp
=> sql server creates view v1 and stores query but not query output
SELECT * FROM V1
=> when above query submitted to sql server then sql server executes
the query as follows
VIJAY :-
--------
CREATE VIEW V2
AS
SELECT empno,ename,job,deptno
FROM emp
WHERE deptno=20
VIJAY :-
=> if view created with "WITH CHECK OPTION" then any DML command
through 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 :-
INSERT INTO V3 VALUES(777,'KLM','CLERK',30) => ERROR
05-feb-22
complex views :-
------------------
=> 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 then write the
simple query as follows
simple complex
Droping view :-
--------------
DROP VIEW V1
WITH SCHEMABINDING :-
---------------------
=> if view created with schemabinding then sql server will not allow
the user to drop table if any view exists on the table. To drop table
first we need to drop view.
Rules :-
Synonyms :-
----------
=> if tablename is lengthy then developer can give a simple and short name
to the table called synonym and where you want to use tablename instead of
using tablename we can use synonym name
=> after creating synonym instead of using tablename we can use synonym
name in SELECT/INSERT/UPDATE/DELETE queries
1 SELECT * FROM E
07-feb-22
SEQUENCES :-
------------
Ex :- CREATE SEQUENCE S1
START WITH 1
INCREMENT BY 1
MAXVALUE 5
using sequence :-
-----------------
CREATE SEQUENCE S2
START WITH 100
INCREMENT BY 1
MAXVALUE 999
CREAT SEQUENCE S3
START WITH 1
INCREMENT BY 1
MAXVALUE 9999
INVOICE
INVNO INVDT
KLM/0222/1 ?
KLM/0222/2 ?
KLM/0222/3 ?
CREATE SEQUENCE S4
START WITH 100
INCREMENT BY 1
MAXVALUE 999
CYCLE/NOCYCLE option :-
----------------------
=> if sequence created with NOCYCLE then it starts from start with and
generates upto MAX and after reaching MAX then it stops.
=> if sequence created with CYCLE then it starts from start with and
generates upto MAX and after reaching MAX then it will be reset to MIN.
CREATE SEQUENCE S5
START WITH 1
INCREMENT BY 1
MAXVALUE 5
MINVALUE 1
CYCLE
5 We can reseed an Identity property but we cannot change the step size
whereas we can alter the Seed as well as the Step size of a Sequence object
at any time.
INDEXES :-
-----------
=> indexes are created on columns and that column is called index key
=> whenever user submits a query to sql server then it uses following
methods to locate the record
1 table scan
2 index scan
=> in index scan sql server scans only half the table so index scan
is much faster than table scan.
Types of Indexes :-
-------------------
1 Non Clustered Indexes
simplex index
composite index
unique index
2 Clustered Indexes
09-feb-22
composite index :-
------------------
=> if index created on multiple columns then index is called composite index
EMP
deptno job
10 CLERK
20 MANAGER
30 SALESMAN
20 CLERK
30 CLERK
10 MANAGER
20 CLERK
30 SALESMAN
20
10 40
note :- SQL SERVER uses above index when where condition based on
leading column of the index.
UNIQUE index :-
--------------
=> UNIQUE index doesn't allow duplicate values into the column on which
index is created
G Q
CLUSTERED INDEX :-
------------------
=> a non clustered index stores pointers to actual records but whereas
clustered index stores actual records.
=> in non clustered indexes order of the records in table and order of
the records in index will not be same but in clustered index this order
will be same.
Example :-
30 80
10 A 40 C 70 B 90 D
30 E
10 A
30 E
40 C
70 B
90 D
10-feb-22
=> by default sql server creates clustered index on primary key column.
Droping Index :-
----------------
DB6PM
TABLES
ROWS & COLS
CONSTRAINTS
INDEXES
TRIGGERS
VIEWS
SYNONYMS
SEQUENCES
PIVOT operator :-
-----------------
syntax :-
SELECT *
FROM (SELECT statement) AS <ALIAS>
PIVOT
(
AGGR-EXPR FOR COLNAME IN (V1,V2,V3,--)
) AS <PIVOT-TABNAME>
ORDER BY <COLNAME> ASC/DESC
10 20 30
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
job 10 20 30
ANALYST NULL 6000.00 NULL
CLERK 1300.00 1900.00 950.00
MANAGER 2450.00 2975.00 2850.00
PRESIDENT 5000.00 NULL NULL
SALESMAN NULL NULL 5600.00
Example 2 :-
-----------
1 2 3 4
2018 ? ? ? ?
2019 ? ? ? ?
2020 ? ? ? ?
2021 ? ? ? ?
SELECT *
FROM (SELECT DATEPART(yy,hiredate) AS year,
DATEPART(qq,hiredate) AS qrt,
empno
FROM emp) E
PIVOT
(
COUNT(empno) FOR qrt IN ([1],[2],[3],[4])
) AS PIVOT_TABLE
ORDER BY year ASC
YEAR 1 2 3 4
2018 1 0 0 0
2019 1 0 0 1
2020 0 0 0 4
2021 2 3 2 0
11-feb-22
STUDENT
SID SNAME SUBJECT MARKS
1 A MAT 80
1 A PHY 90
1 A CHE 70
2 B MAT 60
2 B PHY 70
2 B CHE 50
OUTPUT :-
SELECT *
FROM student
PIVOT
(
SUM(marks) FOR subject IN ([MAT],[PHY],[CHE])
) AS PIVOT_TABLE
ORDER BY SID ASC
MERGE command :-
----------------
scenario :-
------------
10/2/22
CUSTS
CID NAME ADDR
10 A HYD
11 B MUM
12 C DEL
CUSTT
CID NAME ADDR
10 A HYD
11 B MUM
12 C DEL
11/2/22
CUSTS
CID NAME ADDR
10 A BLR => UPDATED
11 B MUM
12 C DEL
13 D KOL => INSERTED
Syn :-
Example :-
10 A BLR
11 B MUM
12 C DEL
13 D KOL
Example 2 :-
10 A BLR
11 B MUM
12 C DEL
13 D KOL
-----------------------------------------------------------------------------
12-feb-22
Features :-
-----------
1 improves performance :-
-------------------------
=> in TSQL , sql commands can be grouped into one block and we submit that
block to sql server. so TSQL programming no of requests and response
between user and sql server are reduced and performance is improved.
3 supports loops :-
-------------------
=> in TSQL programming if any statement causes error then we can handle
that error and we can display our own simple and user friendly message.
5 supports resuability :-
-------------------------
=> TSQL programs can be stored in db and applications which are connected
to db can reuse these programs.
6 supports security :-
-----------------------
=> TSQL programs are secured because 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 @x int
DECLARE @s varchar(10)
DECLARE @d date
SET statement :-
------------------
ex :- SET @x = 100
SET @s = 'abc'
SET @d = GETDATE()
PRINT statement :-
-------------------
PRINT 'HELLO'
PRINT @x
=> write a prog to input date and print day of the week ?
DECLARE @d DATE
SET @d = '1947-08-15'
PRINT DATENAME(DW,@d)
15-feb-22
=> to perform operations over db execute SQL commands from tsql program
=> the following commands are executed from tsql program
1 DML (insert,update,delete,merge)
2 DRL (select)
3 TCL (commit,rollback,save transaction)
SELECT @var1=col1,
@var2=col2,
---------
FROM tabname
WHERE condition
example :-
SELECT @x=sal
FROM emp
WHERE empno=110
SELECT @a=ename,@b=sal
FROM emp
WHERE empno=110
=> write a prog to input empno and print name & salary ?
DECLARE @eno int,@name varchar(10),@sal money
SET @eno=112
SELECT @name=ename,@sal=sal FROM emp WHERE empno=@eno
PRINT @name + ' ' + CAST(@sal AS VARCHAR)
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 ?
16-feb-22
=> write a prog to input empno and increment employee sal as follows
ACCOUNTS
ACCNO ACTYPE BAL
100 S 10000
101 C 20000
17-feb-22
WHILE loop :-
-------------
WHILE(condition)
begin
statements
end
DECLARE @a int = 1
WHILE(@a<=20)
BEGIN
PRINT @a
SET @a = @a+1
END
2022-01-01 ?
2022-01-02 ?
2022-12-31 ?
input :- NARESH
output :-
N
A
R
E
S
H
input :- NARESH
output :-
N
NA
NAR
NARE
NARES
NARESH
*
**
***
****
*****
DECLARE @x int=1
WHILE(@x<=5)
BEGIN
PRINT REPLICATE('*',@x)
SET @x = @x + 1
END
18-feb-22
CURSOR :-
---------
=> cursors are used to access row-by-row into tsql program.
1 declare cursor
2 open cursor
3 fetch records from cursor
4 close cursor
5 deallocate cursor
Declaring cursor :-
--------------------
Opening cursor :-
-------------------
=> 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
Closing cursor :-
--------------------
CLOSE <cursor-name>
CLOSE c1
Deallocating cursor :-
----------------------
DEALLOCATE <cursor-name>
DEALLOCATE c1
@@FETCH_STATUS :-
-------------------
=> it is a system variable the returns status of fetch.
=> using this we can find whether fetch stmt is successful or failed
=> @@FETCH_STATUS returns
raise_salary
empno pct
100 15
101 20
102 12
103 15
21-feb-22
STUDENT
sno sname s1 s2 s3
1 A 80 90 70
2 B 30 60 50
RESULT
sno stot savg sres
SCROLLABLE CURSOR :-
--------------------
=> by default cursor is called forward only cursor and it supports forward
navigation but doesn't support backward navigation.
=> forward only cursor supports only FETCH NEXT statement but scrollable
cursor supports the following fetch statements
Assignment :-
--------------
22-feb-22
=> in TSQL program if any statement causes runtime then sql server displays
error message , to replace system generated message with our own
simple and user friendly message then we need to handle that runtime
error.
=> to handle runtime error we need to include a block called TRY---CATCH block
BEGIN TRY
statement 1
statement 2
statement 3 => causes exception
statement 4
----------
END TRY
BEGIN CATCH
statements => handles exception
END CATCH
=> in try block if statement causes runtime error then control is transferred
to catch block and executes the statements in catch block
Example 1 :-
Example 2 :-
Example 3 :-
=> write a prog to input empno and increment sal by specific amount but
sunday updates are not allowed ?
message 0 to 10
errors 11 to 20
fatal errors 21 to 25
------------------------------------------------------------------------------
23-feb-22
1 stored procedures
2 stored functions
3 triggers
SUB-PROGRAMS :-
-----------------
1 stored procedures
2 stored functions
Advantages :-
-------------
1 modular programming :-
-------------------------
=> with the the help of procedures & functions a big tsql program can be
divided into small modules
2 reusability :-
----------------
=> procedures & functions can be stored in db and applications which are
connected to db can reuse these programs.
3 security :-
-------------
=> because these programs are stored in db so only authorized users can
execute these programs.
=> procedures & functions can be called from front-end applications like
java,.net .
5 improves performance :-
-------------------------
STORED PROCEDURES :-
---------------------
=> a stored procedure is a named tsql block that accepts some input
performs some action on db and may or may not returns a value.
=> these programs are called stored procedure because they are stored in db
parameters :-
--------------
1 INPUT
2 OUTPUT
INPUT :-
--------
OUTPUT :-
-----------
example 1 :-
-------------
execution :-
------------
1 ssms
2 tsql program
3 front-end applications
execution :-
DECLARE @s MONEY
EXECUTE raise_salary 100,1000,@s OUTPUT
PRINT @s
24-feb-22
ACCOUNTS
ACCNO ACTYPE BAL
100 S 10000
101 S 20000
execution :-
DECLARE @b money
EXECUTE debit 100,1000,@b output
print @b
Assignment :-
create a procedure for money deposit ?
25-feb-22
=> when predefine functions not meeting our requirements then we create
our own functions called user define functions.
=> a function is also a named TSQL block that accepts some input performs
some calculation and must return a value.
1 for calculations
2 to fetch value from db
syn :-
CREATE OR ALTER
FUNCTION <NAME>(parameters if any) RETURNS <type>
AS
BEGIN
statements
RETURN <expr>
END
example 1 :-
EXECUTION :-
--------------
1 sql commands
2 another tsql program
3 front-end applications
Example 2 :-
PRODUCTS
prodid pname price
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
26-feb-22
Example 1 :-
=> create a function that accepts deptno and returns list of employees
working for the dept ?
execution :-
--------------
example 2 :-
execution :-
------------
SELECT * FROM DBO.getTopNEmpList(5)
Assignment :-
--------------
CUSTOMERS
CUSTID NAME ADDR PHONE AADHARNO PANNO
ACCOUNTS
ACCNO ACTYPE BAL CUSTID
TRANSACTIONS
TRID TTYPE TDATE TAMT ACCNO
=> create following procedures & functions to implement various bank transactions
scalar table
procedures functions
5 cannot be called from select stmt can be called from select stmt
Droping :-
-----------
28-feb-22
TRIGGERS :-
-----------
=> a trigger is also a named TSQL block like procedure but executed implicitly
by sql server whenever user submits DML/DDL commands.
1 to control dmls/ddls
2 to enforce complex rules & validations
3 to audit tables
4 to generate values for primary key columns
5 to manage replicas
syntax :-
AFTER trigger :-
----------------
=> 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.
02-mar-22
Magic Tables :-
-----------------
1 INSERTED
2 DELETED
=> by using these two tables we can access the data in triggers affected
by dmls.
=> record user is trying to update is copied to both INSERTED & DELETED tables
DELETED
EMPNO ENAME SAL
100 A 5000
EMP_RESIGN
EMPNO ENAME HIREDATE DOR
Testing :-
INSTEAD OF trigger :-
---------------------
EMP99
ENO ENAME SAL BONUS
=> create trigger to generate eno and bonus for new employee ?