BATCH2728
BATCH2728
----------------
Database :-
---------------
bank db univ db
cust students
accounts courses
trans faculty
loans colleges
employees
Types of Databases :-
-----------------------------
=> OLTP is for running business and OLAP is for to analyze business
C create
R read
U update
D delete
DBMS :-
-----------
user-------------------dbms----------------db
Evolution of DBMS :-
----------------------------
Information rule :-
----------------------
cust
cid name addr => columns / fields / attributes
10 sachin hyd
11 rahul del
12 vijay mum => row / record / tuple
=> every table must contain primary key to uniquely identify records.
ex :- accno,empid,aadharno,panno,voterid
RDBMS features :-
--------------------------
emp
empid ename job sal projid name duration cost client
1 A SE 40K 100 ABC 5 600 TATA MOTORS
2 100 ABC 5 600 TATA
MOTORS
projects
projid pname duration cost client
100 ABC 5 600 TATA MOTORS
101 KLM 4 300 KLM airlines
emp
empid ename job sal projid
1 A SE 40K 100
2 B SSE 60K 100
10 100
RDBMS softwares :-
----------------------------
SQL Databases :-
-------------------------
sql server from microsoft
oracle from oracle corp
mysql from oracle corp
postgresql from postgresql forum
rds from amazon
NoSQL Databases :-
---------------------------
1 mongoDB
2 cassandra
ORDBMS :-
---------------
ordbms softwares :-
--------------------------
sql server
oracle
postgresql
summary :-
what is db ?
what is dbms ?
what is rdbms ?
what is ordbms ?
===================================================================
SQL SERVER
===========
=> sql server is basically a rdbms product from microsoft and also supports
ordbms features and used to create and to manage database.
version year
1 server
2 client
server :-
-----------
1 DB
2 INSTANCE
client :-
----------
1 connects to server
2 submit requests to server
3 receive response from server
client tool :-
----------------
user------sqlplus---------------------------------oracle------------------db
user------mysqlworkbench--------------------mysql-----------------db
20-NOV-24
SQL :-
----------
user-----------------------ssms-------------sql--------------------sql
server-------------db
user----------------------sqlplus--------------sql---------------------
oracle-----------------db
user------------------mysqlworkbench--------sql-----------------
mysql-------------------db
SQL
SERVER
DATABASE
TABLE
DATA
Creating Database :-
-----------------------------
=> click ok
Databases
system databases
master => New Query
=> the following databases are created with installation of sql server are called
system databases
1 MASTER
2 MODEL
3 MSDB
4 TEMPDB
download :-
----------------
21-nov-24
Datatypes
Character types :-
------------------------
ASCII UNICODE
char nchar
varchar nvarchar
varchar(max) nvarchar(max)
char(size) :-
-----------------
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 :- gender char(1)
m
f
state_code char(2)
AP
TG
country_code char(3)
ind
usa
varchar(size) :-
---------------------
ex :- NAME VARCHAR(10)
SACHIN - - - -
released
=> char /varchar allows ascii chars (256 chars) that includes a-z,A-Z,0-9,special
chars
i.e. char / varchar allows alphanumeric data.
ex :- panno char(10)
vehno char(10)
emailid varchar(20)
varchar(max) :-
----------------------
=> allows character data upto 2GB.
ex :- TEXT VARCHAR(MAX)
=> allows unicode chars (65536) that includes all ascii chars and chars of
different
languages.
Integer types :-
---------------------
TINYINT 1 0 TO 255
SMALLINT 2 -32768 TO 32767
INT 4 -2^31 TO 2^31-1
BIGINT 8 -2^63 TO 2^63-1
ex :- AGE TINYINT
EMPID SMALLINT
NUMERIC(p) :-
--------------------
ex :- empid NUMERIC(4)
10
100
1000
10000 => not allowed
aadharno NUMERIC(12)
phone NUMERIC(10)
accno NUMERIC(11)
NUMERIC(P,S) / DECIMAL(P,S) :-
-----------------------------------------------
ex :- SALARY NUMERIC(7,2)
5000
5000.55
50000.55
500000.55 => not allowed
5000.5678 => allowed => 5000.57
5000.5648 => allowed => 5000.56
SAVG NUMERIC(5,2)
Currency Types :-
------------------------
922337203685477.5807
ex :- sal SMALLMONEY
bal MONEY
ex :- DOB DATE
2003-10-5
LOGIN TIME
9:30:00
TXNDT DATETIME
2024-11-21 10:00:00
22-nov-24
Rules :-
-------------
ex :- 123emp invalid
emp 123 invalid
emp*123 invalid
emp_123 valid
ex :-
EMP
EMPID ENAME JOB SAL HIREDATE DNO
SP_HELP <tabname>
Ex :-
SP_HELP emp
empid tinyint 1
ename varchar 10
job varchar 10
sal smallmoney 4
hiredate date 3
dno tinyint 1
1 single row
2 multiple rows
inserting single row :-
-----------------------------
ex :-
inserting nulls :-
----------------------
method 1 :-
-----------------
method 2 :-
-----------------
SELECT columns / *
FROM <tabname>
[WHERE cond]
SQL = ENGLISH
QUERIES = SENTNECES
CLAUSES = WORDS
23-nov-24
WHERE clause :-
-------------------------
=> where clause is used to get specific row/rows from table based on a condition
=> OP must be any relational operator like > >= < <= = <>
=> where cond is applied on each and every row
=> if cond = true row is selected otherwise row is not selected
Ex :-
SELECT *
FROM emp
WHERE empid = 103
SELECT *
FROM emp
WHERE ename = 'vijay'
SELECT *
FROM emp
WHERE hiredate > 2020 => ERROR
SELECT *
FROM emp
WHERE hiredate > '2020-12-31'
SELECT *
FROM emp
WHERE hiredate < '2020-01-01'
compound condition :-
------------------------------
SELECT *
FROM emp
WHERE empid = 103 OR empid = 105
SELECT *
FROM emp
WHERE job='clerk' OR job='manager'
SELECT *
FROM emp
WHERE job='clerk' AND sal>5000
=> employees earning more than 5000 and less than 10000 ?
SELECT *
FROM emp
WHERE sal > 5000 AND sal < 10000
SELECT *
FROM emp
WHERE hiredate >= '2020-01-01' AND hiredate <= '2020-12-31'
SELECT *
FROM emp
WHERE job='clerk' OR job='manager' AND sal > 5000
-------------
----------------------------------------------
above query returns clerk records earning less than 5000 because operator
AND has got more priority than operator OR , so sal>5000 is applied only
to managers but not to clerks. To overcome this problem use ( )
SELECT *
FROM emp
WHERE ( job='clerk' OR job='manager' ) AND sal > 5000
=>
STUDENT
SID SNAME S1 S2 S3
1 A 80 90 70
2 B 30 60 50
SELECT *
FROM student
WHERE s1>=35 AND s2>=35 AND s3>=35
SELECT *
FROM student
WHERE s1<35 OR s2<35 OR s3<35
IN operator :-
------------------
25-nov-24
BETWEEN operator :-
------------------------------
WHERE COLNAME BETWEEN V1 AND V2 ( col >= v1 AND col <= v2)
ex :-
SELECT *
FROM emp
WHERE sal BETWEEN 5000 AND 10000
SELECT *
FROM emp
WHERE hiredate NOT BETWEEN '2020-01-01' AND '2020-12-31'
=> employees working as clerk,manager and earning between 5000 and 10000
and working for dept 10,20 and not joined in 2020 ?
SELECT *
FROM emp
WHERE job IN ('clerk','manager')
AND
sal BETWEEN 5000 AND 10000
AND
dno IN (10,20)
AND
hiredate NOT BETWEEN '2020-01-01' AND '2020-12-31'
=> list of samsung,redmi,realme mobile phones price between 10000 and 20000 ?
products
prodid pname price category brand
SELECT *
FROM products
WHERE brand IN ('samsung','redmi','realme')
AND
price BETWEEN 10000 AND 20000
AND
category='mobiles'
COL = V1
OR
COL = V2 =========================> COL IN (V1,V2,V3)
OR
COL = V3
COL >= V1
AND ===========================> COL BETWEEN V1 AND V2
COL <= V2
LIKE operator :-
----------------------
wildcard chars :-
----------------------
SELECT *
FROM emp
WHERE ename LIKE 's%'
SELECT *
FROM emp
WHERE ename LIKE '%n%'
SELECT *
FROM emp
WHERE ename LIKE '___a%'
SELECT *
FROM emp
WHERE ename LIKE '%a___'
SELECT *
FROM emp
WHERE ename LIKE 'a%'
OR
ename LIKE 'e%'
SELECT *
FROM emp
WHERE ename LIKE '[aeiou]%'
SELECT *
FROM emp
WHERE ename NOT LIKE '[aeiou]%'
SELECT *
FROM emp
WHERE ename LIKE '[a-p]%'
SELECT *
FROM emp
WHERE hiredate LIKE '_____10___'
SELECT *
FROM emp
WHERE hiredate LIKE '2020%'
=>
SELECT *
FROM emp
WHERE job IN ('clerk','man%')
A ERROR
B returns clerk & manager
C only clerk
D none
ans :- C
ans :- B
IS operator :-
-------------------
SELECT *
FROM emp
WHERE sal IS NULL
SELECT *
FROM emp
WHERE sal IS NOT NULL
summary :-
ALIAS :-
-----------
Ex :-
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
STUDENT
SNO SNAME S1 S2 S3
1 A 80 90 70
2 B 30 60 50
SELECT SNO,
S1+S2+S3 AS TOTAL,
(S1+S2+S3)/3.0 AS AVG
FROM STUDENT
1 240 80
2 140 46.
26-nov-24
ORDER BY clause :-
----------------------------
SELECT columns
FROM tabname
[WHERE cond]
ORDER BY colname ASC / DESC , ------
SELECT *
FROM emp
ORDER BY ename ASC
SELECT *
FROM emp
ORDER BY sal DESC
NOTE :-
ex :-
SELECT empno,ename,hiredate,sal
FROM emp
ORDER BY 4 DESC
=> above query sorts data based on 4th column in the select list i.e. sal
=> arrange employee list dept wise asc and with in dept sal wise desc ?
SELECT empno,ename,sal,deptno
FROM emp
ORDER BY 4 ASC , 3 DESC
1 A 3000 20 6 F 7000 10
2 B 1000 30 3 C 4000 10
3 C 4000 10 ===========> 4 D 6000 20
4 D 6000 20 1 A 3000 20
5 E 5000 30 5 E 5000 30
6 F 7000 10 2 B 1000 30
SELECT empno,ename,hiredate,deptno
FROM emp
ORDER BY 4 ASC , 3 ASC
STUDENT
SNO SNAME M P C
1 A 80 90 70
2 B 60 70 50
3 C 90 70 80
4 D 90 80 70
SELECT sno,sname,m,p,c,(m+p+c)/3
FROM student
ORDER BY (m+p+c)/3 DESC ,m DESC, p DESC
4 D 90 80 70 80
3 C 90 70 80 80
1 A 80 90 70 80
2 B 60 70 50 60
=> employees working as clerk,manager and arrange output sal wise desc ?
SELECT *
FROM emp
WHERE job IN ('clerk','manager')
ORDER BY sal DESC
DISTINCT clause :-
---------------------------
Ex :-
10
20
30
ANALYST
CLERK
MANAGER
PRESIDENT
SALESMAN
TOP clause :-
--------------------
Ex :-
SELECT TOP 5 *
FROM emp
ORDER BY sal DESC
SELECT TOP 5 *
FROM emp
ORDER BY hiredate ASC
summary :-
27-nov-24
INSERT
UPDATE
DELETE
MERGE
SET IMPLICIT_TRANSACTIONS ON
=> to save the operation execute COMMIT
=> to cancel the operation execute ROLLBACK
UPDATE command :-
-----------------------------
UPDATE <tabname>
SET colname = value , colname = value , ------
[WHERE cond]
ex :-
NULL assignment =
NULL comparision IS
=> update sal with 1000 and comm with 500 whose empno = 7369 ?
UPDATE emp
SET sal = 1000 , comm = 500
WHERE empno = 7369
=> increment sal by 20% and comm by 10% those working as salesman and joined in
1981 year ?
UPDATE emp
SET sal = sal + (sal*0.2) , comm = comm + (comm*0.1)
WHERE job='SALESMAN' AND hiredate LIKE '1981%'
products
prodid name price category brand
UPDATE products
SET price = price + (price*0.1)
WHERE category='mobiles'
AND
brand IN ('samsung','relame')
DELETE command :-
-----------------------------
=> command used to delete row/rows from table
=> we can delete all rows or specific rows
ex :-
CREATE
ALTER
DROP
TRUNCATE
=> all DDL commands acts on table structure (columns,datatype and size)
ALTER command :-
---------------------------
1 add columns
2 drop columns
3 modify column
changing datatype
changing size
Adding column :-
------------------------
Ex :-
after adding by default the new column is filled with nulls , to insert data
into the
new column use update command.
Droping columns :-
-------------------------
ALTER TABLE <tabname>
DROP COLUMN col1,col2,---------
Ex :-
Modifying column :-
---------------------------
1 changing datatype
2 changing size
DROP command :-
--------------------------
Ex :-
TRUNCATE command :-
----------------------------------
=> when truncate command is executed sql server goer to memory and releases
all the pages allocate for table and when pages are released data stored in
pages are also deleted.
Ex :-
DELETE VS TRUNCATE :-
--------------------------------------
DELETE TRUNCATE
1 DML DDL
5 slower faster
IDENTITY :-
----------------
IDENTITY(SEED,INCR)
Ex :-
100 A
101 B
102 C
DELETE FROM cust TRUNCATE TABLE cust
103 K 100 P
=> a stored procedure used to change tablename and also column name
Ex :-
SP_RENAME 'emp','employees'
SP_RENAME 'employees.comm','bonus'
==========================================================================
Built-in Functions :-
----------------------------
=> a function accepts some input performs some calculation and returns one value
Types of functions :-
----------------------------
1 date
2 character
3 numeric
4 conversion
5 special
6 analytical
7 aggregate
DATE functions :-
-----------------------
GETDATE() :-
-----------------
DATEPART() :-
----------------------
Ex :-
SELECT *
FROM emp
WHERE DATEPART(YY,HIREDATE) IN (1980,1983,1985)
SELECT *
FROM emp
WHERE DATEPART(YY,HIREDATE)%4 = 0
SELECT *
FROM emp
WHERE DATEPART(MM,HIREDATE) IN (1,4,12)
SELECT *
FROM emp
WHERE DATEPART(DW,HIREDATE) = 1
DATENAME() :-
----------------------
MM DW
DATEPART 11 5
FORMAT() :-
-----------------
FORMAT(DATE,'format')
MM => 11
MMM => Nov
MMMM => November
scenario :-
---------------
SELECT *
FROM emp
WHERE hiredate = getdate() => no rows
"=" comparision with getdate() always fails , to overcome this problem use
FORMAT function.
SELECT *
FROM emp
WHERE hiredate = FORMAT(getdate() ,'yyyy-MM-dd')
DATEADD() :-
-------------------
=> used to add / subtract days / months / years to a date / from a date
scenario :-
GOLD_RATES
DATEID RATE
2020-01-01 ?
2020-01-02 ?
2024-11-29 ?
SELECT *
FROM gold_rates
WHERE dateid = FORMAT(getdate(),'yyyy-MM-dd')
SELECT *
FROM gold_rates
WHERE dateid = FORMAT(DATEADD(dd,-1,getdate()),'yyyy-MM-dd')
SELECT *
FROM gold_rates
WHERE dateid = FORMAT(DATEADD(mm,-1,getdate()),'yyyy-MM-dd')
4
SELECT *
FROM gold_rates
WHERE dateid = FORMAT(DATEADD(yy,-1,getdate()),'yyyy-MM-dd')
5 SELECT *
FROM gold_rates
WHERE
dateid BETWEEN FORMAT(DATEADD(mm,-1,getdate()),'yyyy-MM-dd')
AND
FORMAT(getdate(),'yyyy-MM-dd')
DATEDIFF() :-
---------------------
SELECT ENAME,
DATEDIFF(YY,HIREDATE,GETDATE()) AS EXPR
FROM EMP
SELECT ENAME,
DATEDIFF(MM,HIREDATE,GETDATE())/12 AS YEARS,
DATEDIFF(MM,HIREDATE,GETDATE())%12 AS MONTHS
FROM EMP
EOMONTH() :-
---------------------
EOMONTH(DATE,INT)
Ex :-
Queries :-
---------------
character functions :-
-----------------------------
UPPER() :-
----------------
UPPER(string)
Ex :-
LOWER() :-
----------------
LOWER(string)
Ex :-
30-nov-24
LEN() :-
----------
LEN(string)
Ex :-
SELECT *
FROM emp
WHERE LEN(ename) = 4
LEFT() :-
----------
LEFT(string,no of chars)
Ex :-
RIGHT() :-
--------------
SELECT *
FROM emp
WHERE LEFT(ename,1) = 's'
SELECT *
FROM emp
WHERE RIGHT(ename,1) = 's'
SELECT *
FROM emp
WHERE ename LIKE 'a%a'
OR
ename LIKE 'b%b'
SELECT *
FROM emp
WHERE LEFT(ename,1) = RIGHT(ename,1)
SELECT empno,ename,
LEFT(ename,3) + LEFT(empno,3) + '@tcs.com' as emailid
FROM emp
UPDATE emp
SET emailid = LEFT(ename,3) + LEFT(empno,3) + '@tcs.com'
SUBSTRING() :-
----------------------
SUBSTRING(string,start,no of chars)
ex :-
CHARINDEX() :-
-----------------------
CHARINDEX(char,string,[start])
Ex ;-
CUST
CID CNAME
10 sachin tendulkar
11 virat kohli
SELECT cid,
SUBSTRING(cname,1,CHARINDEX(' ',cname)-1) AS FNAME ,
SUBSTRING(cname,CHARINDEX(' ',cname)+1 , LEN(cname)) AS LNAME
FROM cust
CUST
CID CNAME
10 sachin ramesh tendulkar
11 mahendra singh dhoni
REPLICATE() :-
----------------------
REPLICATE(char , length)
Ex :-
=>
ACCOUNTS
ACCNO BAL
123456789523 10000
REPLICATE('X',4) + RIGHT(accno,4)
12xxx456
REPLACE() :-
-------------------
REPLACE(str1,str2,str3)
Ex :-
TRANSLATE() :-
-----------------------
TRANSLATE(str1,str2,str3)
Ex :-
e => a
l => b
o => c
=> translate function can be used to encrypt data i.e. converting plain text to
cipher text.
ex :-
SELECT ename,
TRANSLATE(sal,'0123456789.' , '$bT@g*#^&!%') as sal
FROM emp
output :- hello
SELECT
REPLACE(TRANSLATE( '@#he$%ll^&o*!' , '@#$%^&*!','********'),'*','')
----------------------------------------------------------------------
**he**ll**o**
02-dec-24
Numeric Functions :-
----------------------------
rounding numbers :-
-------------------------
ROUND
FLOOR
CEILING
ROUND:-
------------
ROUND(number,decimal places)
Ex :-
38-----------------------------------
38.5------------------------------------39
300 ----------------------------350-------------------------------400
380-----------------------------385---------------------------------390
0---------------------------------500----------------------------------1000
FLOOR() :-
---------------
FLOOR(number)
Ex :-
CEILING() :-
---------------
CEILING(number)
Ex :-
Conversion functions :-
--------------------------------
CAST
CONVERT
CAST :-
--------------
CAST(source-value as target-type)
Ex :-
SELECT ename + ' joined as ' + job + ' on ' + CAST(hiredate as varchar)
FROM emp
CONVERT() :-
-------------------
CONVERT(TARGET-TYPE , SOURCE-VALUE)
Ex :-
SELECT CONVERT(INT,10.5) => 10
1 using convert we can display dates in different styles but not possible
using cast
2 using convert we can display money in different styles but not possible
using cast
Date Styles :-
------------------
=> to display dates in different styles first convert date to char type
CONVERT(VARCHAR,DATE,style-number)
Ex :-
104 =>
02.12.2024
114
=> 12:11:58:420
SELECT ename,
CONVERT(VARCHAR,hiredate,101) as hiredate
FROM emp
Money styles :-
--------------------
CONVERT(VARCHAR,MONEY,STYLE-NUMBER)
0
1 => displays number with thousand seperator
2
SELECT ename,
CONVERT(VARCHAR,sal,1) as sal
FROM emp
Special functions :-
-------------------------
ISNULL() :-
----------------
ISNULL(arg1,arg2)
Ex :-
3-dec-24
Ex :-
=> find the ranks of the employees based on sal and highest paid
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 gap
PARTITION BY clause :-
--------------------------------
=> used to find ranks with in group , for ex to find ranks with in dept
first divide the table dept wise using partition by clause and
apply rank/dense_rank functions on each partition (dept) .
SELECT empno,ename,sal,deptno,
dense_rank() over (partition by deptno order by sal desc) as
rnk
FROM emp
ex :-
SELECT empno,ename,sal,
LAG(sal,1) OVER (order by empno asc) as prev_sal
FROM emp
SELECT ename,hiredate,
DATEDIFF(dd,lag(hiredate,1) over (order by hiredate asc),hiredate) as days
FROM emp
population :-
-------------------
year population
2000
2001
2023
2024
Aggregate functions :-
-----------------------------
=> these functions process multiple rows and returns one value
MAX
MIN
SUM
AVG
COUNT
COUNT(*)
MAX() :-
------------
MAX(arg)
Ex :-
MIN() :-
-----------
MIN(arg)
Ex :-
SUM() :-
------------
SUM(arg)
Ex :-
o/p :- 30,000.00
AVG() :-
------------
AVG(arg)
Ex :-
2107--------------------------------------2108
NOTE :-
COUNT() :-
-----------------
COUNT(arg)
Ex :-
SELECT COUNT(BONUS) FROM EMP => 1 => nulls are not counted
COUNT(*) :-
------------------
T1
F1
10
NULL
20
NULL
30
COUNT(F1) => 3
COUNT(*) => 5
SELECT COUNT(*)
FROM EMP
WHERE DATEPART(QQ,HIREDATE) = 2
AND
DATEPART(YY,HIREDATE) = 1981
SUMMARY :-
===========================================================================
CASE statement :-
-------------------------
1 simple case
2 searched case
simple case :-
--------------------
CASE colname
WHEN value1 THEN return expr1
WHEN value2 THEN return expr2
----------------
ELSE return expr
END
Ex :-
if deptno=10 display HR
20 IT
30 SALES
others UNKNOWN
SELECT ENAME,
CASE DEPTNO
WHEN 10 THEN 'HR'
WHEN 20 THEN 'IT'
WHEN 30 THEN 'SALES'
ELSE 'UNKNOWN'
END AS DNAME
FROM EMP
UPDATE EMP
SET SAL = CASE JOB
WHEN 'CLERK' THEN SAL+(SAL*0.1)
WHEN 'SALESMAN' THEN SAL+(SAL*0.15)
WHEN 'MANAGER' THEN SAL+(SAL*0.2)
ELSE SAL + (SAL*0.05)
END
searched case :-
-----------------------
=> use searched case when conditions not based on "=" operator.
CASE
WHEN COND1 THEN RETURN EXPR1
WHEN COND2 THEN RETURN EXPR2
-----------------
ELSE RETURN EXPR
END
Ex :-
SELECT ENAME,SAL,
CASE
WHEN SAL>3000 THEN 'HISAL'
WHEN SAL<3000 THEN 'LOSAL'
ELSE 'AVGSAL'
END AS SALRANGE
FROM EMP
STUDENT
SNO SNAME S1 S2 S3
1 A 80 90 70
2 B 30 60 50
SELECT SNO,
(S1+S2+S3) AS TOTAL,
(S1+S2+S3)/3 AS AVG,
CASE
WHEN S1>=35 AND S2>=35 AND S3>=35 THEN 'PASS'
ELSE 'FAIL'
END AS RESULT
FROM STUDENT
===================================================================================
=====
05-dec-24
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. For ex to calculate
dept wise no of employees first group the rows based on dept and
apply count function on each dept
emp
empno ename deptno
1 A 20
2 B 10 group by 10
2
3 C 30 ================> 20 2
4 D 20 30 1
5 E 10
=> group by clause converts detailed data to summarized data which is useful for
analysis.
SELECT columns
FROM tabname
[WHERE cond]
GROUP BY colname
[HAVING cond]
[ORDER BY col ASC/DESC]
Execution :-
FROM
WHERE
GROUP BY
HAVING
SELECT
ORDER BY
ex :-
FROM emp :-
------------------
emp
empno ename deptno
1 A 20
2 B 10
3 C 30
4 D 20
5 E 10
GROUP BY deptno :-
----------------------------
10 2 B
5 E
20 1 A
4 D
30 3 C
10 2
20 2
30 1
1980 1
1981 10
1982 2
1983 1
sql server cannot calculate dept wise count before group by and it can calculate
only
after group by , so apply the condition COUNT(*) > 3 after group by using HAVING
clause
20 5
30 6
WHERE VS HAVING :-
-------------------------------
WHERE HAVING
PERSONS
ADHAARNO NAME GENDER CITY STATE
=> display job wise no of employees for the jobs clerk,manager and display only
the
jobs where no of emps > 3 ?
=> display dept wise and with in dept job wise no of employees ?
SELECT deptno,job,count(*)
FROM emp
GROUP BY deptno,job
ORDER BY deptno ASC
10 CLERK 1
MANAGER 1
PRESIDENT 1
20 ANALYST 2
CLERK 2
MANAGER 1
30 CLERK 1
MANAGER 1
SALESMAN 4
=> display year wise and with in year quarter wise no of employees joined ?
note :-
=> column alias cannot be used in group by clause because group by clause is
executed
before select
=> column alias can be used in order by clause because order by clause is executed
after select
==========================================================================
INTEGRITY CONSTRAINTS
========================
=> integrity constraints are rules to maintain data integrity i.e data quality
or data consistency
=> used to prevent users from entering invalid data .
=> used to enforce rules like min bal must be 1000.
Types of constraints :-
-------------------------------
1 NOT NULL
2 UNIQUE
3 PRIMARY KEY
4 CHECK
5 FOREIGN KEY
6 DEFAULT
1 column level
2 table level
column level :-
----------------------
NOT NULL :-
-------------------
ex :-
UNIQUE :-
----------------
PRIMARY KEY :-
-----------------------
=> In tables one column must be there to uniquely identify the records and
into that column duplicates and nulls are not allowed , so declare that
column with primary key.
ex :-
NOTE :-
----------
=> only one primary key is allowed per table , if we want multiple primary keys
then declare one column with primary key and others columns with UNIQUE
NOT NULL.
2 a table can have multiple unique constraints a table can have only one
primary key
07-DEC-24
CHECK constraint :-
---------------------------
CHECK(condition)
FOREIGN KEY :-
-------------------------
ex :-
projects
projid pname duration cost client
1000 ABC 5 300 TATA MOTORS
1001 KLM 4 200 KLM Airlines
emp
empno ename job sal projid REFERENCES projects(projid)
1 A SE 30 1000
2 B SSE 40 1001
3 9999 => not accepted
4 1000
5 null
=> values entered in fk column should match with values entered in pk column
ex :-
=> while inserting if we skip hiredate then sql server inserts default value
ex :-
Question :-
ACCOUNTS
ACCNO ACTYPE BAL OPEN_DT
Rules :-
-------------
TRANSACTIONS
TRID TTYPE TDATE TAMT ACCNO
Rules :-
-------------
10-dec-24
Relationship types :-
-----------------------------
1 one to one (1:1)
2 one to many (1:m) DEFAULT
3 many to one (m:1)
4 many to many (m:n)
=> by default sql server creates one to many relationship between two tables
=> to establish one to one (1:1) relationship between two tables declare foreign
key with
unique constraint.
ex :-
projects
projid pname duration cost
1000
1001
manager
mgrno mname start_date end_date projid REFERENCES
projects(projid) UNIQUE
100 A / / 1000
101 B / / 1001
=> to establish many to many relationship then create 3rd table and
add primary keys of both tables as foreign keys
ex :-
course student
cid cname sid sname
10 .NET 1 A
11 SQL SERVER 2 B
registrations
sid cid dor fee
1 10 ?? ??
1 11 ? ?
2 10 ? ?
=> if combination of columns uniquely identifies the records then that combination
is declared as primary key.
Ex 2 :-
CUST PRODUCTS
CID CNAME PRODID PNAME PRICE
10 A 100 A 80
11 B 101 B 120
SALES
DATEID PRODID CID QTY
2024-12-09 100 10 3
2024-12-09 101 10 2
2024-12-09 100 11 2
2024-12-10 100 10 2
11-dec-24
A UNIQUE
B CHECK
C NOT NULL
D FOREIGN KEY
E PRIMARY KEY
ANS :- C
products
prodid pname price mfd_dt exp_dt
100 AAA 80 2024-12-01 2024-11-01 INVALID
DELETE rules :-
------------------------
=> delete rule specifies how child rows are affected if parent row is deleted.
=> these rules are declared with foreign key.
ON DELETE NO ACTION :-
-------------------------------------
scenario :-
ACCOUNTS
ACCNO ACTYPE BAL
100 S 10000
101 S 20000
LOANS
ID TYPE AMT ACCNO REFERENCES ACCOUNTS(ACCNO)
1 H 30 100
2 C 10 100
ON DELETE CASCADE :-
------------------------------------
scenario :-
ACCOUNTS
ACCNO ACTYPE BAL
100 S 10000
101 S 20000
TRANSACTIONS
TRID TTYPE TDATE TAMT ACCNO REFERENCES ACCOUNTS(ACCNO)
ON
DELETE CASCADE
Rule :-
=> if parent row is deleted then it is deleted but child rows are not deleted
but fk will be set to null.
scenario :-
projects
projid pname client
1000 A TATA
1001 B DBS
emp
empno ename projid REFERENCES projects (projid)
1 1000 ON DELETE SET NULL
2 1001
RULE :- if project is completed (deleted) then set the employee projid to null
=> if parent row is deleted then it is deleted but child rows are not deleted but
fk will be set to default value
1 A 20
2 B 20
summary :-
importance of constraints
declaring constraints
column level
table level
relationship types
delete rules
===========================================================================
12-dec-24
JOINS
=====
=> join is an operation performed to display data from two or more table.
=> In DB related data stored in multiple tables , to gather or to combine data
stored
in multiple tables we need to join those tables.
ex :-
orders cust
ordid orddt deldt cid cid cname addr
1000 05 15 100 100 A HYD
1001 08 20 101 101 B HYD
1002 10 21 102 102 C HYD
SELECT o.*,c.*
FROM orders as o INNER JOIN cust as c
ON o.cid = c.cid
OUTPUT :-
Types of joins :-
----------------------
1 inner join
equi join
non equi join
self join
2 outer join
left join
right join
full join
3 cross join / cartesian join
equi join :-
--------------
=> 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.
SELECT columns
FROM tab1 INNER JOIN tab2
ON join condition
join condition :-
---------------------
=> join condition specifies which record of tab1 joined with which record of
tab2.
=> based on the given join condition sql server joins records of two tables
table1.commonfield = table2.commonfield
ex :-
emp dept
empno ename sal deptno deptno dname loc
1 A 3000 10 10 ACCOUNTS NEW YORK
2 B 4000 20 20 RESEARCH
3 C 5000 30 30 SALES
4 D 4000 20 40 OPERATIONS
5 E 3000 NULL
SELECT empno,ename,sal,dname,loc
FROM emp INNER JOIN dept
ON emp.deptno = dept.deptno
NOTE :-
=> In join queries , declare table alias and prefix column names with
table alias for two reasons
1 to avoid ambiguity
2 for faster execution
ex :-
SELECT e.empno,e.ename,e.sal,d.deptno,d.dname,d.loc
FROM emp as e INNER JOIN dept as d
ON e.deptno = d.deptno
=> display employee details with dept details working at NEW YORK loc ?
SELECT e.ename,d.dname,d.loc
FROM emp as e INNER JOIN dept as d
ON e.deptno = d.deptno /* join cond */
WHERE d.loc = 'NEW YORK' /* filter cond */
SELECT o.*,c.*
FROM orders as o INNER JOIN cust as c
ON o.cid = c.cid
WHERE o.deldt = FORMAT(getdate(),'yyyy-MM-dd')
13-dec-24
SELECT columns
FROM tab1 INNER JOIN tab2
ON join cond
INNER JOIN tab3
ON join cond
INNER JOIN tab4
ON join cond
ex :-
SELECT e.ename,
d.dname,
l.city , l.state,
c.country_name as country
FROM emp as e INNER JOIN dept as d
ON e.deptno = d.deptno
INNER JOIN locations as l
ON d.locid = l.locid
INNER JOIN countries as c
ON l.country_id = c.country_id
Outer join :-
--------------------
=> Inner join returns only matching records but will not return unmatched records
to display unmatched records perform outer join.
ex :-
emp dept
empno ename sal deptno deptno dname loc
1 A 3000 10 10 ACCOUNTS NEW YORK
2 B 4000 20 20 RESEARCH
3 C 5000 30 30 SALES
4 D 4000 20 40 OPERATIONS => unmatched record
5 E 3000 NULL => unmatched record
1 LEFT JOIN
2 RIGHT JOIN
3 FULL JOIN
LEFT JOIN :-
------------------
=> left join returns all rows (matched + unmatched) from left side table and
matching rows from
right side table.
SELECT e.ename,d.dname
FROM emp as e LEFT JOIN dept as d
ON e.deptno = d.deptno
=> above query displays all rows from emp and matching rows from dept
A ACCOUNTS
B RESEARCH
C SALES
D RESEARCH
E NULL => unmatched from emp
RIGHT JOIN :-
-------------------
=> returns all rows from right side table and matching rows from left side table
SELECT e.ename,d.dname
FROM emp as e RIGHT JOIN dept as d
ON e.deptno = d.deptno
=> above query returns all rows from dept table and matching rows from emp table
A ACCOUNTS
B RESEARCH
C SALES
D RESEARCH
NULL OPERATIONS => unmatched from dept
FULL JOIN :-
------------------
SELECT e.ename,d.dname
FROM emp as e FULL JOIN dept as d
ON e.deptno = d.deptno
A ACCOUNTS
B RESEARCH
C SALES
D RESEARCH
E NULL => unmatched from emp
NULL OPERATIONS => unmatched from dept
SELECT e.ename,d.dname
FROM emp as e LEFT JOIN dept as d
ON e.deptno = d.deptno
WHERE d.dname IS NULL
E NULL
SELECT e.ename,d.dname
FROM emp as e RIGHT JOIN dept as d
ON e.deptno = d.deptno
WHERE e.ename IS NULL
NULL OPERTIONS
both tables :-
------------------
SELECT e.ename,d.dname
FROM emp as e FULL JOIN dept as d
ON e.deptno = d.deptno
WHERE d.dname IS NULL
OR
e.ename IS NULL
E NULL
NULL OPERATIONS
Question :-
emp projects
empno ename sal projid projid pname duration
1 100 100
2 101 101
3 null 102
SELECT e.*,p.*
FROM emp as e RIGHT JOIN projects as p
ON e.projid = p.projid
WHERE e.empno IS NULL
14-dec-24
Non-Equi join :-
-----------------------
=> Non equi join is performed between the tables not sharing a common field
ex :-
emp salgrade
empno ename sal grade losal hisal
1 A 3000 1 700 1000
2 B 1000 2 1001 2000
3 C 5000 3 2001 3000
4 D 1500 4 3001 4000
5 E 2000 5 4001 9999
SELECT e.ename,e.sal,s.grade
FROM emp as e INNER JOIN salgrade as s
ON e.sal BETWEEN s.losal and s.hisal
A 3000 3
B 1000 1
C 5000 5
D 1500 2
E 2000 2
SELECT e.ename,d.dname,s.grade
FROM emp as e INNER JOIN dept as d
ON e.deptno = d.deptno
INNER JOIN salgrade as s
ON e.sal BETWEEN s.losal and s.hisal
ON e.deptno = d.deptno :-
------------------------------------
emp dept
empno ename sal deptno deptno dname loc
1 A 3000 10 10 ACCOUNTS NEW YORK
2 B 4000 20 20 RESEARCH
3 C 5000 30 30 SALES
4 D 4000 20 40 OPERATIONS => unmatched record
5 E 3000 10
output :-
1 A 3000 ACCOUNTS
2 B 4000 RESEARCH
3 C 5000 SALES
4 D 4000 RESEARCH
5 E 3000 ACCOUNTS
output :-
1 A 3000 ACCOUNTS 3
2 B 4000 RESEARCH 4
3 C 5000 SALES 5
4 D 4000 RESEARCH 4
5 E 3000 ACCOUNTS 3
SELECT e.ename,d.dname,s.grade :-
--------------------------------------------------
A ACCOUNTS 3
B RESEARCH 4
C SALES 5
D RESEARCH 4
E ACCOUNTS 3
SELF JOIN :-
-------------------
emp x emp y
empno ename mgr empno ename mgr
7369 smith 7902 7369 smith 7902
7499 allen 7698 7499 allen 7698
7566 jones 7839 7566 jones 7839
7698 blake 7839 7698 blake 7839
7839 king null 7839 king null
7902 ford 7566 7902 ford 7566
SELECT x.ename,y.ename
FROM emp as x INNER JOIN emp as y
ON x.mgr = y.empno
smith ford
allen blake
jones king
blake king
ford jones
SELECT x.ename,x,sal,
y.ename as manager , y.sal as mgrsal
FROM emp as x INNER JOIN emp as y
ON x.mgr = y.empno
WHERE x.sal > y.sal
Questions :-
----------------
TEAMS
ID COUNTRY
1 IND
2 AUS
3 ENG
output :-
IND VS AUS
IND VS ENG
AUS VS ENG
TEAMS A TEAMS B
ID COUNTRY ID COUNTRY
1 IND 1 IND
2 AUS 2 AUS
3 ENG 3 ENG
=> 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 all records of 1st table
joined with
all the records of 2nd table.
=> to perform cross join submit the join query without join condition.
SELECT columns
FROM tab1 CROSS JOIN tab2
ex :-
SELECT e.ename,d.dname
FROM emp as e CROSS JOIN dept as d
==========================================================================
16-dec-24
SET OPERATORS :-
=================
1 UNION
2 UNION ALL
3 INTERSECT
4 EXCEPT
A = 1,2,3,4
B = 1,2,5,6
=> In sql these operations performed between the result of two queries i.e.
between the
records return by two queries.
SELECT statement 1
UNION / UNION ALL / INTERSECT / EXCEPT
SELECT statement 2
Rules :-
Query 1 :-
CLERK
MANAGER
ANALYST
CLERK
ANALYST
Query 2 :-
SALESMAN
SALESMAN
SALESMAN
MANAGER
SALESMAN
CLERK
UNION :-
-------------
Ex 1 :-
ANALYST
CLERK
MANAGER
SALESMAN
Ex 2 :-
ANALYST 3000.00
CLERK 800.00
CLERK 950.00
CLERK 1100.00
MANAGER 2850.00
MANAGER 2975.00
SALESMAN 1250.00
SALESMAN 1500.00
SALESMAN 1600.00
UNION JOIN
scenario :-
--------------
EMP_US
eno ename sal dno
100 A 3000 10
101 B 4000 20
DEPT
dno dname loc
EMP_IND 10 HR
eno ename sal dno 20 IT
200 K 3000 10 30 SALES
201 X 4000 30
100 A
101 B
200 K
201 X
100 A 3000 10 10 HR
101 B 4000 20 20 IT
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 stmts
CLERK
MANAGER
EXCEPT :-
---------------
=> returns values present in 1st query output and not present in 2nd query
output
ANALYST
SALESMAN
Question 1 :-
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
T1 T2
F1 C1
1 1
2 2
1 1
2 2
NULL NULL
NULL NULL
==========================================================================
17-dec-24
Types of sub-queries :-
-------------------------------
SELECT columns
FROM tabname
WHERE colname OP (SELECT statement)
=> OP must be any relational opertors like = > >= < <= <>
Ex :-
SELECT *
FROM emp
WHERE sal > ( SELECT sal FROM emp WHERE ename='BLAKE')
-----------------------------------------------------------------------
2850
SELECT *
FROM emp
WHERE hiredate < ( SELECT hiredate FROM emp WHERE ename='KING' )
-----------------------------------------------------------------------------
1981-11-17
SELECT ename
FROM emp
WHERE sal = MAX(sal) => ERROR
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)
-------------------------------------------
5000
=> name of the employee having max experience ?
SELECT ename
FROM emp
WHERE hiredate = (SELECT MIN(hiredate) FROM emp )
SELECT MAX(sal)
FROM emp
WHERE sal < (SELECT MAX(sal) FROM emp)
SELECT ename
FROM emp
WHERE sal = (SELECT MAX(sal)
FROM emp
WHERE sal < (SELECT MAX(sal) FROM emp))
UPDATE emp
SET sal = sal + (sal*0.1)
WHERE hiredate = (SELECT MIN(hiredate) FROM emp)
UPDATE emp
SET sal = CASE empno
WHEN 7369 THEN (SELECT sal FROM emp WHERE empno=7499)
WHEN 7499 THEN (SELECT sal FROM emp WHERE empno = 7369)
END
WHERE empno IN (7369,7499)
sub-query :-
------------------
SELECT *
FROM emp
WHERE deptno = (SELECT deptno FROM dept WHERE loc='NEW YORK')
join :-
-----------
SELECT e.*
FROM emp as e INNER JOIN dept as d
ON e.deptno = d.deptno
WHERE d.loc = 'NEW YORK'
=> display employee details with dept details working at NEW YORK loc ?
join :-
------
SELECT e.*,d.*
FROM emp as e INNER JOIN dept as d
ON e.deptno = d.deptno
WHERE d.loc = 'NEW YORK'
sub-query :-
----------------
not possible
SUB-QUERY VS JOIN :-
------------------------------------
=> to display data from one table and condition based on another table then we
can use
sub-query or join.
SELECT *
FROM emp
WHERE deptno IN (SELECT deptno FROM dept WHERE loc IN ('NEW
YORK','CHICAGO'))
-----------------------------------------------------------------------------------
------------
10
30
co-related sub-queries :-
---------------------------------
=> if inner query references values of outer query then it is called co-related
sub-query.
=> execution starts from outer query and inner query is executed no of times
depends
on no of rows return by outer query.
=> use co-related sub-query to execute sub-query for each row return by outer
query
ex :-
emp
empno ename sal deptno
1 A 5000 10
2 B 3000 20
3 C 4000 30
4 D 6000 20
5 E 3000 10
SELECT *
FROM emp
WHERE sal > ( SELECT AVG(sal) FROM emp)
--------------------------------------------
4200
SELECT *
FROM emp as x
WHERE sal > (SELECT AVG(sal) FROM emp WHERE deptno = x.deptno)
emp
empno ename sal deptno
1 A 5000 10 5000 > (4000) TRUE
2 B 3000 20 3000 > (4500) FALSE
3 C 4000 30 4000 > (4000) FALSE
4 D 6000 20 6000 > (4500) TRUE
5 E 3000 10 3000 > (4000) FALSE
SELECT *
FROM emp as x
WHERE sal = (SELECT MAX(sal) FROM emp WHERE deptno = x.deptno)
emp
empno ename sal deptno
1 A 5000 10 5000 = (5000) TRUE
2 B 3000 20 3000 = (6000) FALSE
3 C 4000 30 4000 = (4000) TRUE
4 D 6000 20 6000 = (6000) TRUE
5 E 3000 10 3000 = (5000) FALSE
18-dec-24
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
=> display 3rd max salary ?
Derived tables :-
-------------------------
SELECT columns
FROM (SELECT statement) as <alias>
[WHERE cond]
FROM
WHERE
GROUP BY
HAVING
SELECT
ORDER BY
WHERE
Ex 1 :-
SELECT empno,ename,sal,
DENSE_RANK() OVER (ORDER BY SAL DESC) as rnk
FROM emp
=> above query returns ranks of all the employees but to display top 5 employees
SELECT empno,ename,sal,
DENSE_RANK() OVER (ORDER BY SAL DESC) as rnk
FROM emp
WHERE rnk <= 5 => ERROR
column alias cannot be used in where clause because where clause is executed
before select
to overcome this use derived table
SELECT *
FROM (SELECT empno,ename,sal,
DENSE_RANK() OVER (ORDER BY sal DESC) as rnk
FROM emp) as e
WHERE rnk <= 5
ROW_NUMBER() :-
--------------------------
Ex :-
=> above query displays row numbers for all the records but to display first 5
rows
SELECT *
FROM ( SELECT ROW_NUMBER() OVER (ORDER BY empno ASC) as rno,
empno,ename,sal
FROM emp ) as e
WHERE rno <= 5
WHERE rno%2 = 0
SELECT *
FROM ( SELECT ROW_NUMBER() OVER (ORDER BY empno ASC) as rno,
empno,ename,sal
FROM emp ) as e
WHERE rno >= (SELECT COUNT(*)-2 FROM emp)
simple select
where
order by
distinct
top
group by & having
functions
joins
set operators
sub-queries
19-dec-24
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)
failed
successful INVALID
=> the following commands provided by sql server to handle transactions called
TCL commands
=> In sql server a txn begins implicitly with dml and ends implicitly with commit.
=> a user can also start transaction by executing "begin transaction" command and
end transaction by executing commit / rollback command.
ex 1 :-
ex 2 :-
ex 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
ex :-
10
20
30
40
DATABASE SECURITY :-
----------------------------------
SERVER (LOGIN)
DATABASE (USER)
TABLE (PRIVILEGE)
ROWS & COLS (VIEW)
security
logins => New Login
=> click OK
NOTE :-
=> a new login is created but cannot access databases , so to access database
login
must be associated with a user in database.
creating user in db :-
---------------------------
=> click OK
=> open the database in which you want to create user for ex BATCH2728 and
execute the
following command
SERVER
LOGIN
SA
NARESH
BATCH2728
DBO (SA)
EMP
DEPT
CUST
STUDENT
KUMAR (NARESH)
NOTE :-
PRIVILEGES :-
--------------------
DBO :-
----------
KUMAR :-
-------------
DBO :-
-----------
KUMAR :-
------------
REVOKE command :-
-----------------------------
Ex :-
DBO :-
-------------
21-dec-24
DB objects :-
==========
1 TABLES
2 VIEWS
3 SYNONYMS
4 SEQUENCES
5 INDEXES
VIEWS :-
-----------
=> a view is a virtual table because it doesn't store data and doesn't occupy
memory
and it always derives data from base table.
1 to provide security
2 to reduce complexity
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 i.e. data
SELECT * FROM V1
DBO :-
-----------
KUMAR :-
--------------
1 SELECT * FROM V1
NOTE :-
1 if we make any changes (DMLs) to view that changes are applied to table
2 if we make any changes to table we can see the changes in view
CREATE VIEW V2
AS
SELECT empno,ename,job,deptno
FROM emp
WHERE deptno = 20
DBO :-
--------
KUMAR :-
-------------
=> user kumar can access only the employees belongs to 20th dept
1 SELECT * FROM V2
=> if view created with " WITH CHECK OPTION " then any dml command through view
violates where cond that dml is not accepted
CREATE VIEW V3
AS
SELECT empno,ename,job,deptno
FROM emp
WHERE deptno = 20
WITH CHECK OPTION
KUMAR :-
-------------
Complex views :-
------------------------
=> with the help of views complex queries can be converted into simple queries
Ex 1 :-
Ex 2 :-
after creating view whenever we want dept wise summary execute the following
query
simple complex
SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE='BASE TABLE'
Droping :-
-------------
DROP VIEW V1
23-dec-24
synonyms :-
----------------
Ex :-
=> after creating synonym instead of using tablename EMP we can use
synonym name E as follows
1 SELECT * FROM E
Question :-
synonym alias
E EMP
Droping :-
--------------
DROP SYNONYM E
Ex :-
SEQUENCES :-
----------------------
Ex 1 :-
CREATE SEQUENCE S1
START WITH 1
INCREMENT BY 1
MAXVALUE 5
Ex 2 :-
CREATE SEQUENCE S2
START WITH 100
INCREMENT BY 1
MAXVALUE 999
Ex 3 :-
BILL
BILLNO BDATE AMT
NIT/1224/1 ? ?
NIT/1224/2
CREATE SEQUENCE S3
START WITH 1
INCREMENT BY 1
MAXVALUE 9999
Droping sequence :-
------------------------------
DROP SEQUENCE S1
IDENTITY SEQUENCE
1 bind to specific table and specific column not bind to any column
INDEXES :-
----------------
=> indexes are created on columns and that column is called index key.
Types of Indexes :-
----------------------------
1 Non clustered
2 Clustered
Ex :-
EMP
sal
3000
1000
2000
5000
3000
4000
1500
2500
=> SQL SERVER uses following methods to fetch data from table
1 TABLE SCAN
2 INDEX SCAN
=> In table scan sql server scans comple table i.e. each and every row but in
index scan
on avg sql server scans only half of the table , so index scan is much
faster than
table scan.
UNIQUE index :-
------------------------
=> unique index doesn't allow duplicate values into the column on which index is
created.
G Q
=> primary key / unique columns are automatically indexed by sql server and
a unique index is created on primary key / unique column and unique
index doesn't allow duplicates so primary key / unique also doesn't allow
duplicates.
26-dec-24
Clustered Index :-
--------------------------
=> a non clustered index stores pointers actual records where as clustered
index stores acutal records.
50
30 70
10 A 40 C 60 D 80 B
1 select * from cust => sql server goes to index and access all the
leaf nodes from left to right
2 select *from cust where cid = 60 => sql server goes to index and
finds cid=60 and returns the
row from index
SP_HELPINDEX emp
Droping index :-
--------------------
DROP INDEX EMP.I1
SERVER
DATABASE
TABLE
ROWS & COLS
CONSTRAINTS
INDEXES
TRIGGERS
VIEWS
SYNONYMS
SEQUENCES
Question :-
-----------------
SQL
================================================================
T-SQL (Transact-SQL)
-----------------------------
Basic programming
conditional statements
loops
cursors
error handling
stored procedures
functions
triggers
SQL SERVER
SQL T-SQL
(commands) (blocks)
Features :-
----------------
1 improves performance :-
--------------------------------
=> In T-SQL , sql commands can be grouped into one block and we submit
that block to sql server. so in T-SQL no of requests and response between
user and sql server are reduced and performance is improved.
3 supports loops :-
---------------------------
=> T-SQL supports loops like while ,so in t-sql we can execute sql commands
repeatedly multiple times.
=> In t-sql if any statement causes error then we can handle that error
and we can replace system generated message with our own simple
and user friendly message.
5 supports reusability :-
----------------------------
=> T-SQL programs can be stored in db and applications which are connected
to sql server can reuse t-sql programs.
1 Anonymous Blocks
2 Named
stored procedures
functions
triggers
Anonymous Blocks :-
-----------------------------
1 DECLARE
2 SET
3 PRINT
DECLARE :-
------------------
=> statement used to declare variables
Ex :-
DECLARE @x INT
DECLARE @s VARCHAR(20)
DECLARE @d DATE
SET :-
---------
Ex :-
SET @x = 100
SET @s = 'ABC'
SET @d = getdate()
PRINT :-
---------------
PRINT @x
PRINT @s
PRINT @d
PRINT 'hello'
declare @d date
set @d = '2025-01-01'
print DATENAME(dw,@d)
1 DML (insert,update,delete)
2 DQL (select)
3 TCL (commit,rollback,save transaction)
SELECT stmt syntax :-
-----------------------------
ex :-
27-dec-24
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
=> wap to input empno and increment sal by specific amount and
after increment if sal exceeds 5000 then cancel that increment ?
ACCOUNTS
ACCNO ACTYPE BAL
100 S 10000
101 S 20000
TRANSACTIONS
TRID TTYPE TDATE TAMT ACCNO
30-dec-24
=> wap to input sno and calculate total,avg,result and insert into result table ?
STUDENT
sno sname s1 s2 s3
1 A 80 90 70
2 B 30 40 60
RESULT
sno stotal savg sresult
WHILE loop :-
--------------------
WHILE(cond)
BEGIN
statements
END
DECLARE @x tinyint = 1
WHILE(@x<=20)
BEGIN
PRINT @x
SET @x = @x + 1
END
2025-01-01 ?
2025-01-02 ?
2025-12-31 ?
DECLARE @d1 DATE,@d2 DATE
SET @d1 = '2025-01-01'
SET @d2 = '2025-12-31'
WHILE(@d1 <= @d2)
BEGIN
PRINT CAST(@d1 AS VARCHAR) + ' ' + DATENAME(dw,@d1)
SET @d1 = DATEADD(dd,1,@d1)
END
CURSORS :-
------------------
1 DECLARE CURSOR
2 OPEN CURSOR
3 FETCH RECORDS FROM CURSOR
4 CLOSE CURSOR
5 DEALLOCATE CURSOR
Declaring cursor :-
---------------------------
Opening cursor :-
----------------------
OPEN <cursor-name>
ex :- OPEN C1
=> a fetch stmt fetches one row at a time but to process multiple rows
fetch stmt should be executed multiple times , so fetch should be in a loop.
Closing cursor :-
-----------------------
CLOSE <cursor-name>
Ex :- CLOSE c1
Deallocating cursor :-
-------------------------------
DEALLOCATE <cursor>
Ex :- DEALLOCATE c1
@@FETCH_STATUS :-
--------------------------------
31-dec-24
DECLARE C1 CURSOR FOR SELECT sal FROM emp ORDER BY sal DESC
DECLARE @sal MONEY
OPEN C1
FETCH NEXT FROM C1 INTO @sal
PRINT @sal
CLOSE C1
DEALLOCATE C1
=> wap 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 40 60
RESULT
sno stotal savg sresult
SCROLLABLE CURSOR :-
-----------------------------------
=> by default cursor is forward only cursor and it supports only forward
navigation but
doesn't support backward navigation
=> if cursor declared scroll then it is called scrollable cursor and it supports
both forward and
backward navigation.
=> a forward only cursor supports only FETCH NEXT statement but scrollable cursor
1-jan-25
smith,allen,ward,jones,martin,------------
STRING_AGG() :-
---------------------------
STRING_AGG(colname , seperator)
10 MILLER,CLARK,KING
20 SCOTT,SMITH,JONES,FORD,ADAMS
30 JAMES,MARTIN,BLAKE,ALLEN,WARD,TURNER
========================================================================
02-jan-25
ERROR HANDLING / EXCEPTION HANDLING :-
=====================================
1 syntax errors
2 logical errors
3 runtime errors
=> errors raised during program execution are called runtime errors
ex :- declare @x tinyint
set @x = 500 => runtime error
=> if any statement causes runtime error then sql server displays error
message but messages generated by sql server are not user friendly ,
so to replace system generated message with our own simple and
user friendly message then we need to handle that runtime error.
BEGIN TRY
statement1
statement2 => stmts causes runtime error
statement3
statement4
END TRY
BEGIN CATCH
statements => stmts handles runtime error
END CATCH
=> if any statement in try block causes exception then control is transferred to
catch block
and execute the statements in catch block.
Ex 1 :-
ex 2 :-
0-9 messages
10-18 errors
19-25 fatal error
Ex 1 :-
=> wap to input empno and increment sal by specific amount
but sunday updates are not allowed ?
Ex 2 :-
ACCOUNTS
ACCNO ACTYPE BAL
100 S 10000
101 S 20000
TRANSACTIONS
TRID TTYPE TDATE TAMT ACCNO
ex 3 :-
========================================================================
1 STORED PROCEDURES
2 FUNCTIONS
3 TRIGGERS
SUB-PROGRAMS :-
---------------------------
1 STORED PROCEDURES
2 FUNCTIONS
Advantages :-
-------------------
1 modular programming :-
--------------------------------
=> with the help of procedures and functions we can divide a big T-SQL program
into
small modules and small modules are easy to code ,compile,execute and
debug.
2 reusability :-
-----------------
=> procedures & functions can be stored in db and applications which are
connected
to db can reuse these procedures & functions.
=> procedures and functions can be invoked from front-end applications like
java/.net/python
4 improves performance :-
---------------------------------
=> proc/func improves performance because of one time compilation i.e. when we
create a procedure program is compiled and stored in db and whenever we
call procedure only execution is repeated but not compilation , so this
improves
performance.
STORED PROCEDURES :-
--------------------------------------
=> a procedure is a named T-SQL Block that accepts some input
performs some actions on db and may or may not returns a value.
parameters :-
--------------------
=> parameters are used to receive values from calling program and sends value to
calling program
=> parameters are 2 types
1 INPUT (DEFAULT)
2 OUTPUT
C#.NET PROCEDURE
A ----------------------------------------------------------> X
(INPUT)
B <----------------------------------------------------------- Y
(OUTPUT)
Executing :-
-----------------
EXECUTE raise_salary
Execution :-
1 EXECUTE raise_salary 104,1000 positional association
Execution :-
-----------------
declare @s money
execute raise_salary 104,1000,@s output
print @s
declare @s money
execute raise_salary @eno=104,@amt=1000,@newsal=@s output
print @s
4-jan-24
=> while calling procedure if we don't pass value to @amt sql server assigns
default value i.e. 500
ex 4 :-
execution :-
declare @s money
execute raise_salary 100,default,@s output
print @s
declare @s money
execute raise_salary @eno=100,@newsal=@s output
print @s
ex 5 :-
ACCOUNTS
ACCNO ACTYPE BAL
100 S 10000
101 S 20000
TRANSACTIONS
TRID TTYPE TDATE TAMT ACCNO
=> when predefine functions not meeting our requirements then we create
our own functions called user define functions.
=> a function is also a named T-SQL block that accepts some input
performs some calculation and must return a value.
Ex 1 :-
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 :-
Ex 2 :-
orders products
ordid prodid qty prodid pname price
1000 100 2 100 A 1000
1000 101 3 101 B 2000
1000 102 2 102 C 1500
1001 100 2
CREATE OR ALTER
FUNCTION getOrdAmt(@d INT) RETURNS MONEY
AS
BEGIN
DECLARE C1 CURSOR FOR SELECT o.prodid,o.qty,p.price
FROM orders as o INNER JOIN
products as p
ON o.prodid = p.prodid
WHERE o.ordid = @d
DECLARE @pid INT,@qty INT,@price MONEY
DECLARE @amt MONEY = 0
OPEN C1
FETCH NEXT FROM C1 INTO @pid,@qty,@price
WHILE(@@FETCH_STATUS=0)
BEGIN
SET @amt = @amt + (@qty*@price)
FETCH NEXT FROM C1 INTO @pid,@qty,@price
END
CLOSE C1
DEALLOCATE C1
RETURN @amt
END
C1
100 2 1000
101 3 2000
102 2 1500
Execution :-
5-jan-25
CREATE OR ALTER
FUNCTION <name>(parameters) RETURNS TABLE
AS
RETURN (SELECT statement)
Ex 1 :-
=> create a function to accept deptno and returns employees working for that dept
?
create or alter
function getEmpList(@dno INT) RETURNS TABLE
AS
RETURN (SELECT * FROM emp WHERE deptno=@dno)
Execution :-
Ex 2 :-
CREATE OR ALTER
FUNCTION getTopN(@n INT) RETURNS TABLE
AS
RETURN ( SELECT *
FROM (SELECT empno,ename,sal,
dense_rank() over (order by sal desc) as
rnk
FROM emp) AS E
WHERE rnk<= @n )
Execution :-
Ex 3 :-
Assignment :-
------------------
ACCOUNTS
ACCNO ACTYPE BAL
100 S 10000
101 S 20000
TRANSACTIONS
TRID TTYPE TDATE TAMT ACCNO
scalar table
procedures functions
3 returns values using output parameter returns value using return stmt
SELECT ROUTINE_NAME,ROUTINE_TYPE,ROUTINE_DEFINITION
FROM INFORMATION_SCHEMA.ROUTINES
Droping :-
--------------
6-jan-24
TRIGGERS :-
-----------------
=> a trigger is also a named T-SQL block like procedure but executed implicitly
by sql server
whenever user submits DML commands
1 to control dmls
2 to enforce complex rules and validations
3 to audit day-to-day operations on tables
AFTER triggers :-
------------------------
=> if trigger is after then sql server executes the trigger after executing dml
INSTEAD OF triggers :-
--------------------------------
=> if trigger is instead of then sql server executes the trigger instead of
executing dml
Ex 1 :-
Testing :-
--------------
Ex 2 :-
Testing :-
--------------
Ex 3 :-
Magic Tables :-
---------------------
1 INSERTED
2 DELETED
=> these tables exists only during trigger execution , once trigger execution is
completed then these tables are deleted.
=> with the help of magic tables we can access data affected by dmls
=> record user is trying to update is copied to both INSERTED & DELETED tables
ex :-
DELETED
empno sal
100 2500
7-jan-25
Testing :-
/*
1 row is copied to inserted,deleted tables
2 executes update command
3 executes trigger
*/
=> create trigger to insert details into emp_resign table when employee resigns ?
EMP_RESIGN
EMPNO ENAME JOB SAL HIREDATE DOR
Testing :-
/*
1 row is copied to deleted table
2 executes delete command
3 executes trigger
*/
EMP_AUDIT
uname operation odate new_eno new_ename new_sal old_eno old_ename
old_sal
Testing :-
-------------
AFTER INSERT
sys.triggers
sys.tables
name object_id parent_id name object_id
SELECT tr.name,tb.name
FROM sys.triggers as tr INNER JOIN sys.tables as tb
ON tr.parent_id = tb.object_id
Droping triggers ;-
--------------------------
DROP TRIGGER T1
================================================================
8-jan-25
Dynamic SQL :-
-----------------------
=> SQL commands generated at runtime are called dyhnamic SQL commands
=> dynamic sql is useful when we don't know table names and column names
until runtime.
=> dynamic sql command that you want to execute should be passed as a
string to EXEC procedure.
Ex 1 :-
Execution :-
Ex 2 :-
Execution :-
EXECUTE DROP_ALL_TABLES
========================================================================
9-jan-25
RESTORING DATABASE :-
-------------------------------------
Ex :-