0% found this document useful (0 votes)
110 views86 pages

Sequellll

The document discusses databases and SQL Server. It provides information on the different types of databases (OLTP, OLAP), database administration roles, database architectures (client/server), and SQL Server versions and features. It also covers topics like data types, DDL/DML/DQL languages, and connecting to SQL Server.

Uploaded by

Developer 4
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
110 views86 pages

Sequellll

The document discusses databases and SQL Server. It provides information on the different types of databases (OLTP, OLAP), database administration roles, database architectures (client/server), and SQL Server versions and features. It also covers topics like data types, DDL/DML/DQL languages, and connecting to SQL Server.

Uploaded by

Developer 4
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 86

Every Organization maintains database. The primary purpose is for storing data.

We can store data in varibales, files and database

Language prcocess the data

Varaibles Files Database


-------- ---------- ----------
Not permanent Permanent Permanent
Not secured Not Secured Secured

If any company wants to provide permanent storage and to provide security to the
customer data compulsory they will go for databases

In Olden days, company used to maintain only 1 database.


Now a days companies are maintaing two types of databases

1) OLTP DB(Online Transaction Processing Database)


--------------------
Used for day to day transactions(Running the business)

2) OLAP DB(Online Analytical Processing Database)


-------------------------
Analysing the data, maintain historical data..(Analysing the business)

In olden days running the business is important, Now a days running the business
and analyisng the business is also important.

Hadoop and datascience are frameworks used to data analysis.

SQL server can be used for day to day transactions and also for analysis...If sql
server is used analysis then hadaoop came into picture??

Sql server is best for analysing structured data


Datascience and hadoop is good for analysing unstructured data

Structured data---If data is there in tabular form rows and columns

Unstructred data---My data is there in pdf whatsapp images, audio, video.

We will do data operations on the database like create, read, update and
delete...But we cant directly coummnicate with data we use SQL server as an
mediator

Sql server is a software used to manage the database.Sql Server is a back end
tool..

Back end tools available in market


-------------------
Sql Server----Microsoft
Oracle-----Oracle Corp
DB2-----IBM
MySql----Oracle Corp
Postresql---postgresql forum devlopment
Rds

These database softwares use sql language


These databases are good for storing and processing structured data

NoSQL
---------
MongoDB
Cassandra

These database softwares will not use SQL..they will use JSON..
These databases are good for storing and processing unstructured data

For every project we need a database.

DBA--Database Administartor, Actually what he will do??

He will take one system(High configuration) and he will install SQL Server in that
system.

High Configuration means latest processor, high speed ram etc.

Once you installing Sql server software on that machine it will become server.

In Server DBA will install Sql Server, In Sql Server he will create database of
project like bankdatabase, salesdatabse etc.

Assume there are 3 developers and there are assigned to work with this
bankdatabase.

Every day what this these developers has to do? Everyday they has to connect to the
server & database and work with database

Developers cannot directly work with servers because servers are located some where

In client machine SSMS should be installed.


SSMS-Sql Server Managment Studio.

So developer needs to client machine and ssms installed in it.

SSMS- Client tool


Sql Server - Server tool

For example nee laptop is acting as both server and client. because SSMS and SQL
Server installed on the same laptop.

Client / Server Architecture


---------------
Server: Server is a system where sql server is installed and running.
Inside the server sql server manages two memories.

1)DB
2)INSTANCE

DB is created in hardisk and instance is created in RAM.


DB acts as permanent storage and INSTANCE acts as temporary storage

Client
------------
A Client is a system from where users can
1) Connects to server
2) Submit requests to server
3) recevies response from server.

Client Tool---SSMS

SQL SERVER
---------
Sql Server is a RDBMS product from microsoft used to create and to manage
databases.

Sql Server can be used for both development and administration

Developing the database - Development


Maintaining the databse - Administration.

DBMS - is a software used to create and to manage database


DBMS is an interface between user and database

DBMS--Database Management Systems---used to miantain database above all also


HDBMS--Hierarchy----outdated---Data organized in hierarchy model tree structure
NDBMS---Network----outdated
RDBMS---Relation----Data oraganized in rows and columns--Will Store the data in the
form of tables
ORDBMS---Object Relation

The main difference between these DBMS are how the data is organized

Oracle is also RDBMS

Example:

DBMS VECHILE
HDBMS
NDBMS-------------------------2 WHeeler
RDBMS--------------------------4 Wheeler
SQL SERVER------------------------Honda City
ORACLE----------------------------Swift

Roles/Responsibilities of developer
-----------------------
Creating tables
Creating views
Creating synonyms
Creating sequences
Creating indexes
Creating procedures
Creating functions
Creating triggers
Writing Queries

Roles/Responsibilities of DBA
----------------
Installation of SQL Server
Creating database
Creating Logins
DB Backup and restore
DB Export and import
DB Upgradation and migration
Performance Tuning

Moving the database from one server to other server


Upgration- Moving from old version to the latest version
Migration - Moving from one database to other database MYSQL to SQL SERVER.

Versions of Sql Server


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

Sql Server 1.1 ---1991


Sql Server 4.2----1993
Sql Server 6.0----1995
Sql Server 6.5----1996
Sql Server 7.0-----1998
Sql Server 2000-----2000
Sql Server 2005-----2005
Sql Server 2008----2008
Sql Server 2012----2012
Sql Server 2014---2014
Sql Server 2016------2016
Sql Server 2017-----2017
Sql Server 2019------2019

SQL Server 2016


----------
1) Polybase--Using polybase SQl server can access the data stored in external
sources
2) Earlier Excel,txt,xml files supported from 2016 JSON files also supported.
3) Temporal table to save data changes
4) Dynamic data masking and row level security

SQL Server 2017


------------------
1) Identity cache
2) New String functions
3) Automatic Tuning

Sql Server 2019


---------------
1) Read, write and process big data from Transact-SQL
2) Easily combine and analyse high-value relational data with high volume big data
3) Query external data sources
4) Store big data in HDFS managed by SQL server
5) Query data from multiple external data sources through the cluster
How to connect to Sql server
---------------------
TO connect to sql server open ssms and enter following details

SERVER TYPE: DB ENGINE


SERVER NAME: Name of the computer where sql server is installed
AUTHENTICATION: 2 Aunthentication modes Windows/Sql server(While installing you
have to select mixed mode then only you will get sql server authentication)
LOGIN:sa(System Admin)
PASSWORD:

Creating Database
-----------------
Open object explorer----select databases---roght click and create new
Once database is created, Database is created with two files
1)Data file(.MDF)--Master Data file
Data/MDF File stores data
2)Log file(.LDF)--Log Data file
Log files stores operations. What ever operations performed on database all that
operations are recorded in log file

If these two files are deleted, database will also be deleted

NAME TYPE INTIALSIZE AUTOGROWTH PATH


DB123 DATA 8 64 Path, where the data file is
created

DBA persons will take back up right..taking the back up means nothing but taking
the back up of these two files only.

T-SQL Stands for Transact SQL

SQL Stands for Structured Query Language

In Sql server we will have TSQL COmmands and TSQL Programming


In Oracle we will have sql and pl/sql

SQL is the language used to communicate with SQL SERVER

User communicates with sql server by sending commands called queries

A query is a command/instruction/question submitted sql server to perform some


operation over database.

Sql is originally introduced by IBM and initial name of this language was "SEQUEL"
and later it is renamed to SQL

User---SSMS---SQL---SQL Server---Database
tool---language---software---storage

User---Sqlplus---sql---oracle---database

Based operations over database SQL is categorized into following sublanguages


DDL--Data Defination Language----create, alter, drop, truncate
DML--Data Manipulation Language---insert, update, delete, merge
DQL--Data Query Language/Data Retrieval Language---Select
TCL--Transaction Control Language----commit, rollback,save point
DCL---Data Control Language----grant, revoke

In oracle with these commands 4 extra commands will be there

In DDL---rename,flashback,purge
In DML insert all

Merge is a combination of update and delete

DDL COmmands acts on Data Defination


DML Commands acts on Data

EMPID ENAME SAL----Data Defination/Metdata


100 A 5000----Data

DataTypes in SQl Server


-------------------
A Datatype specifies

1) Type of the data allowed


2) Amount of memory allocated

DataTypes
-----
Character Data Type
-----------
ASCII UNICODE
---- ---------
char nchar
varchar nvarchar
varchar(max) nvarchar(max)

INTEGER FLOAT MONEY


----- ----- -------
tinyint numeric(p,s) smallmoney
smallint money
int
bigint
numeric(p)

DATE BINARY
-------- -----------
Date Binary
Time Varbinary
DateTime varbinary(max)

CHAR(size)
---------
Allows character data upto 8000 chars
Recommended for fixed length char fields
Ex: NAME CHAR(10)
NARESH--- Remaining wasted

Note: In CHAR datatype extra bytes are wasted so CHAR is not recommended for
varibale length fields and it is recommended for fixed length fields

STATE_CODE CHAR(2)
--------
AP
TS
MH

COUNTRY_CODE CHAR(3)
------------
IND
AUS
USA

VARCHAR(SIZE)
--------
Allows character data upto 8000 characters
Recommended for variable length fields

Ex: NAME VARCHAR(10)

SACHIN--------Released

Note: In Varchar extra bytes are not wasted and they are released

VARCHAR(MAX)
---------
Allows character data upto 2 gb

Ex: FEEDBACK VARCHAR(MAX)

Note: char/varchar/varchar(max) allows ascii characters that includes a-z,A-Z,0-


9,Special characters

Ex: PanNUm CHAR(10)


VechNum CHAR(10)
EMAILID VARCHAR(30)

Operators in SQL SERVER


---------------------
1) Arthimetic Operators == Used for calculations == +,-,*,/,%
10+2 => 12
10-2 =>8
10*2 => 20
10/2 => 5 (Quotient)
10%2 => 0 (Remainder)

2) Relational Operators == Used for comparision == >, >=, <, <=, =, <> or !=
10>2 => TRUE
10<2 => FALSE
10=2 => FALSE
10<>2 => TRUE

3)Logical Operators == used to combine two relational expressions == AND OR NOT

CONDITION1 AND CONDITION2 OUTPUT


T T T
T F F
F T F
F F F

CONDITION1 OR CONDITION2 OUTPUT


T T T
T F T
F T T
F F F

AND & OR are used in between two conditions

NOT CONDITION OUPUT


T F
F T

4) Special Operators ==> BETWEEN, IN, LIKE, IS, ANY, ALL, EXISTS, PIVOT

5) Set Operators ===> UNION, UNION ALL, INTERSECT, EXCEPT.

Displaying Data
--------------
"SELECT" command is used to display/retrieve the data from table
--> By using select command We can display all columns and specific columns
--> By using select We can display all rows and specific rows.

Syntax: SELECT columns / * from <tablename>// Here the whole thing is called
query...Individual parts are called clauses.

Here Select and From are clauses

SQL = ENGLISH
QUERIES = SENTENCES(will coummnicate)
CLAUSES = WORDS

Queries are madeup of clauses.

==>Display all the data from emp table


-----------------
SELECT * FROM emp
* => all columns

Select sal, ename from emp


in which ever the order you select in the same order data will display.

WHERE Clause
----------
Used to get specific row/rows from table based on a condition.

Syntax: Select Columns/* from TableName WHERE condition.

How to write condition


--------
ColName Operator Value

Here Operator should be any relational operator

If condition is true row is selected


If condition is false row is not selected

Note: Greater than and less than operators can be used with dates also

In programming languages will write conditions by using IF


In SQL will write conditions by using WHERE Clause.

Compound Condition
-----------
Multiple conditions combined with AND / OR operators is called compound condition

WHERE COndtion1 AND Condition2


WHERE COndtion1 AND Condition2

Display employee details whose id=100,103?


-------------------------
SELECT * FROM emp WHERE empid=100,103 ===>ERROR
SELECT * FROM emp WHERE empid=100 OR empid=103

Display employee details working as clerk,manager?


-------------------------------
SELECT * FROM emp WHERE job='clerk' OR job='manager'

IN Operator
--------------
Use "IN" operator for list comparision.
List means empid=100,103 ..........
Use "IN" operator for "=" comparision with multiple values

WHERE COLNAME=V1,V2,V3====>INVALID
WHERE COLNAME IN (V!,V2,V3,----) ===> VALID

Display employee list whose id=100,103,105


------------------
Select * FROM emp WHERE empid IN (100,103,105)....
Internally it is converted like this (empid=100 or empid=103 or empid=105)

Display employees working as clerk, manager, analyst?


-------------------
Select * from emp where job in ('clerk','manager','analyst')

Employees not working for dept 10,20?


---------------
Select * from emp WHERE deptno NOT IN (10,20)
Employees working as clerk and earning more than 3000?
-----------------
Select * from='clerk' AND sal>3000

Employees earning more than 5000 and less than 10000


----------------------
Select * from emp WHERE sal>5000 AND sal<10000

Employees joined in 2021 year


---------------
Select * from emp WHERE hiredate >= '2021-01-01' AND hiredate <= '2021-12-31'

BETWEEN Operator
------------
Use BETWEEN Operator for range comaparision
Ex: 5000 to 10000
2020 to 2022

Syntax: WHERE COLNAME BETWEEN V1 AND V2

Employees earning between 5000 and 10000


---------------
Select * from WHERE sal BETWEEN 5000 AND 10000

Employees not joined in 2022 year


-------------
SELECT * FROM emp WHERE hiredate NOT BETWEEN '2022-01-01' AND '2022-12-31'

Like Operator
-----------
Use Like operator for pattern comparision.

Ex: name starts with 's'


name ends with 'n'
email id ends with '.in'

Syantax: WHERE COLNAME LIKE 'PATTERN'

So what pattern contains?


-----------
Pattern contains alphabets, digits,specials chars and wildcard chars.

Wild Card Characters


----------
There are two wild card characters
1) % ---> 0 or many characters
When we dont know how many characters are there use this
2) _(underscore) ----> exactly 1 character
When we know the number of charcters use this.

Employees name starts with 's'?


---------------
SELECT * from emp WHERE ename LIKE 'S%'

Employees name ends with 'r'?


----------------
SELECT * from emp WHERE ename LIKE '%R'
Employees name contains 'a'?
------------
Select * from emp WHERE ename LIKE '%A%'

Where 'A' is the 4th in char in their name?


-----------
Select * from emp WHERE ename LIKE '___A%'

Where 'A' is the 3rd character from last?


------------------------
SELECT * FROM emp WHERE ename LIKE '%A__'

Name ends with 'r' or 'n'?


---------
SELECT * from emp WHERE ename LIKE '%R' or ename LIKE '%N'

Name starts with 'a','c','j','s'?


-----------
Select * from emp WHERE ename LIKE '[ACJS]%'

Name starts between 'A' to 'P'?


------------------
SELECT * from emp WHERE ename LIKE '[A-P]%'

List of employees join ined in oct month


---------------
yyyy-mm-dd

SELECT * from emp WHERE hiredate LIKE '_____10___'

IS Operator
----------
use IS operator for NULL comparision

WHERE COLNAME IS NULL


WHERE COLNAME IS NOT NULL

EMployees not earning salary?


------------
Select * from emp WHERE sal IS NULL

Employees earning salary?


----------
Select * from emp where sal IS NOT NULL

ORDER BY Clause
-----------
Order by clause is used to sort data based on one or more columns either in
ascending or in desending order

SELECT columns FROM emp [WHERE COND] ORDER BY COLNAME ASC/DSC

Default order is ascending

Examples
---------
Arrange employee list name wise ascending order?
--------------
SELECT * from emp ORDER BY ename ASC

Arrange employee list sal wise desc order?


--------------------
SELECT * from emp ORDER BY sal DESC

Note 1: In ORDER BY we can use column names and column numbers

SELECT * FROM emp ORDER BY 6 DESC

Above query sorts data based on 6th column in emp table

Note 2: ORDER BY Number is not based on table and it is based on select list.

SELECT empno,ename,sal,deptno FROM emp ORDER BY 6 DESC (Error)

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

Display employee list working as clerk,manager and arrange list salary wise desc?
----------------------------
SELECT * from emp WHERE job IN ('CLERK','MANAGER') ORDER BY sal DESC

Execution order for the above query


--------
FROM
WHERE
SELECT
ORDER BY

DISTINCT Clause
-------------
Distinct clause eliminates duplicates from select statement output not from actual
table
We can apply distinct on single column, mulitple columns or all columns

Example: SELECT DISTINCT job FROM emp

Distinct applied on combination


-----------
SELECT DUSTINCT deptno,job FROM emp.

TOP Clause
----------
Used to display top N rows
used to limit no of rows return by query

Syntax: SELECT TOP <n> columns FROM tabname [WHERE] [ORDER BY <col>]

Display first 5 rows from emp table


-----------------------
SELECT TOP 5 * FROM emp
SELECT TOP 5 ename FROM emp//Display first 5 employee names.

Display top 5 highest paid employees?


-----------------------------
SELECT TOP 5 empno,ename,sal FROM emp ORDER BY sal DESC

Display top 5 max salaries?


-------------
SELECT DISTINCT TOP 5 sal FROM emp ORDER BY sal DESC.

Display top 5 employees based on experience


----------------
SELECT TOP 5 empno,ename,hiredate FROM emp ORDER BY hiredate ASC

DML Commands (Data Manipulation Language)


----------------
INSERT UPDATE DELETE MERGE

All DML commands acts on table data

Table = Structure(COLS) +Data(Rows)

All DML commands acts on table data


By default all DML operations are auto comitted(saved)
to stop auto commit execute the following command

SET IMPLICIT_TRANSACTIONS ON

Once you execute this command autocommit is off


Usually operations are implicitly saved but once you execute this command.then
operations should be explicitly committed.

to save the operation execute COMMIT.


to cancel the operation execute ROLLBACK.

UPDATE Command
----------
Command used to modify the data in a table
we can update all rows or specific rows
we can update single column or multiple coulmns

Syntax: UPDATE<tabname> set colname=value,colname=value,-------[WHERE Condition]

Set operator is used with update command

If where condition is not there update is applied for all the rows

Examples
----
Update all the employees comm with 500?
UPDATE emp SET comm=500

update employees comm with 500 whose comm=null?


UPDATE emp set comm=500 WHERE comm IS NULL

Update employee comm with null whose comm <> null?


UPDATE emp SET comm IS NULL WHERE comm IS NOT NULL = > Error
UPDATE emp SET comm=NULL WHERE comm IS NOT NULL

Null Assignment =
NUll Comaprision IS
Alter
-----------
Command used to modify the table structure
Using Alter command we can add columns, drop column, modify a
columns(Increase/Decrease Field size, CHanging Data type)

Adding Column
-----------
ALTER TABLE <tabname> ADD colname DATATYPE(size)

Add column gender to emp table?


------------
ALTER TABLE emp ADD gender CHAR(1)

After adding the column by default the new column is filled with nulls, to insert
data into the new column use update command

UPDATE emp SET gender='M' WHERE empno=7499

Adding Multiple Columns


----------
ATLER TABLE emp ADD DOB DATE, AADHARNO NUMERIC(12)

Dropping COlumn
------------
ALTER TABLE <tabname> DROP COLUMN colname

Ex: drop column aadharno from emp

ALTER TABLE emp DROP COLUMN aadharno

We change the dataype also using Alter command

Syntax: ALTER COLUMN colname DATAYPE(size)

Modify the size of ename column to 20?


-------------------
ALTER TABLE emp ALTER COLUMN ename VARCHAR(20)

Change the datatype of empno to small int


------------------------
ALTER TABLE EMP ALTER COLUMN EMPNO SMALLINT

Drop columns gender, dob?


---------
ALTER TABLE emp DROP COLUMN DOB, GENDER

Modifying a column
----------
Alter Table <tabname> ALTER COLUMN colname DATATYPE(Size)

Modify the size of ename column to 20?


------------
ALTER TABLE emp ALTER COLUMN ename VARCHAR(20)

Change the dataype of empno to smallint?


----------------
ALTER TABLE EMP ALTER COLUMN EMPNO SMALLINT
CHange the datatype of hiredate to date?
--------------------------
ALTER TABLE EMP ALTER COLUMN HIREDATE DATE

Drop Command
---------
Command used to drop table from database.
Drops table structure along with data.

Syntax: DROP TABLE <tabname>


Ex: DROP TABLE emp

Truncate Command
-----------
Deletes all the data from table
Will empty the table
Releases memory allocated for table

Synatx: TRUNCATE TABLE <tabname>


Ex: TRUNCATE TABLE dept

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

DROP VS DELETE VS TRUNCATE


-------------------
DROP
---
DDL Command
Drops struncture along with data

DELETE
------
DML COmmand
Deletes only data but not structure

TRUNCATE
--------
DDL COmmand
Deletes only data but not structure

DELETE VS TRUNCATE
-----------
DELETE
-----
DML
Can delete specific row/rows
where condition can be used with delete
Deletes row by row
slower
will not release memory
will not reset identity

TRUNCATE
---------
DDL
Can delete only allrows but cannot delete specific rows
where condition cannot be used with truncate
delete all rows at a time
faster
releases memory
will reset identity

SP_RENAME
-----------
Used to change tablename and column name

SP_RENAME 'oldname','newname'

Rename table emp to employees


------------------
SP_RENAME 'EMP','EMPLOYEES'

Rename column comm to bonus?


-----------------
SP_RENAME 'Employees.comm','Bonus'

Identity
----------
USed to generate sequence numbers
Used to auto increment column values
We can declare identity for integer columns

Synatx: IDENTITY(SEED,INCR).....Default(1,1)

SEED===>START, OPTIONAL, DEFUALT 1


INCR====>INCREMENT, OPTIONAL, DEFAULT 1

Example
-----------
CREATE TABLE Cust(cid INT IDENTITY(100,1),cname VARCHAR(10))
INSERT INTO cust(cname) VALUES ('A')
INSERT INTO cust(cname) VALUES ('B')
INSERT INTO cust(cname) VALUES ('C')

SELECT * FROM cust

Output
--------
CID cname
100
101
102

DELETE FROM CUST

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

SELECT * FROM CUST

CID NAME
103
TRUNCATE TABLE cust
INSERT INTO CUST(CNAME) VALUES('k')

SELECT * FROM CUST

CID NAME
100 K

How to reset identity manually?


-----------------
DBCC CHECKIDENT(tablename,reseed,value)
DBCC CHECKIDENT('CUST',RESEED,99)

How to explicitly give the value to identity?


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

Note: By default sql server will not allow explicit value to identity column

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

To provide explicit value into identity column execute the following command

SET IDENTITY_INSERT CUST ON

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

SQL is widely used for data process and data analysis

Built In Fuctions in SQL Server


------------------------
A function accepts some input perform some calculation and must return a value

Types of functions
-------------
1) Date
2) String
3) Mathematical
4) Conversion
5) Special
6) Analytical
7) Aggregate

Date functions
-----------
1) GETDATE()---Returns Current date and time

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

2) DATEPART()---Used to extract part of the date

DATEPART(INTERVAL,DATE)

SELECT DATEPART(YY,GETDATE())==>2022
MM====10
DD====01
DW====7 (Day of the week)
1--Sunday
7--Saturday

SELECT DATEPART(DAYOFYEAR,GETDATE())

DAYOFTHEYEAR=>274
HH=>8
MI=>21
SS=>10
QQ=>4(QUARTER) 1 JAN-MAR, 2 APR-JUN, 3 JUL-SEP, 4 OCT-DEC

Display employees joined in jan,apr,dec months?


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

Display employees joined in leap year


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

Display employees joined on sunday?


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

Employees joined in the 2nd Quarter of 1981 year?


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

FORMAT
--------
FUnction used to get date in different formats
FORMAT(date,format)
SELECT FORMAT(GETDATE(),'yyyy-MM-dd')
SELECT FORMAT(GETDATE(),'dd-MM-yyyy')
SELECT FORMAT(GETDATE().'MM/dd/yyyy')

List of employees joined today??


---------------
SELECT * FROM emp WHERE hiredate = GETDATE() => No ROws(Becoz it will print time as
well)

SELECT * FROM emp WHERE hiredate=FORMAT(GETDATE(),'yyyy-MM-dd')

DATENAME()
------------
USed to extract part of the date

Difference between Datepart and Datename are only in 2 intervals

MM DW
DATEPART 10 2
DATENAME OCTOBER MONDAY

Display on which day india got independence??


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

DIsplay smith joined on wednesday, allen joined on friday??


----------------
SELECT ename + ' Joined on ' +DATENAME(dw,hiredate) FROM emp

DATEDIFF()
---------
Used to find difference between two dates
DATEDIFF(interval,date1,date2)

SELECT DATEDIFF(yy,'2021-10-10',GETDATE())=>1
SELECT DATEDIFF(mm,'2021-10-10',GETDATE())=>12
SELECT DATEDIFF(dd,'2021-10-10',GETDATE())=>365

Real time example , Display EName and Experience


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

Display Ename Experience M Years and N Months


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

Experience = 40 months = 3 years 4 months


Years = Months/12 = 40/12 =3
MONTHS = MOnths%12 = 40%12=4

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

Display employees having more than 40 years of experience?


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

DATEADD()
------
Used to add/subtract days,years,months to/from a date

DATEADD(interval, int,date)

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

Scenario
---------
GOLD_RATES
DATEID RATE
2015-01-01 ??
2015-01-02 ??
2022-10-09 ??

Display todays gold rate


-------------
SELECT * FROM GOLD_RATES WHERE DATEID=FORMAT(GETDATE(),'yyyy-MM-dd')

Display Yesterdays's gold rate


----------
SELECT * FROM GOLD_RATES WHERE DATEID=FORMAT(DATEADD(DD,-1,GETDATE()),'yyyy-MM-dd')

Display last month same day gold rate


---------------
SELECT * FROM GOLD_RATES WHERE DATEID=FORMAT(DATEADD(MM,-1,GETDATE()),'yyyy-MM-dd')

Display last year same day gold rate


------------
SELECT * FROM GOLD_RATES WHERE DATEID=FORMAT(DATEADD(YY,-1,GETDATE()),'yyyy-MM-dd')

Display last 1 month gold rates


---------
SELECT * FROM GOLD_RATES WHERE DATEID BETWEEN DATEADD(MM,-1,GETDATE()) AND
GETDATE()

EOMONTH()
--------
Returns end of the month i.e last day of the month

EOMONTH(DATE,INT)

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


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

String Functions
-----------
UPPER()---Converts string to uppercase

UPPER(arg)

Select UPPER('hello')===>HELLO

LOWER()---COnverts string to lowercase

LOWER(arg)

SELECT LOWER('HELLO')===>hello

SELECT LOWER(ename) FROM emp//only displays the names

COnvert all the employees names to lowercase


-------------
UPDATE emp SET ename=LOWER(ename)//updates

LEN()---Returns string length i.e no of characters

LEN(arg)

SELECT LEN('hello welcome')==>13


space is also treated as 1 character

Display employee list name contains 5 characters


--------------------
SELECT * FROM emp WHERE ename like '_____'
WHERE LEN(ename)=5
Writing queries using operators is difficult and with functions is easy

Select ename, len(ename) from emp//This query shows names along with length

SUBSTRING()
------------
Used to extract part of the string
THis functions takes 3 arguments

SUBSTRING(string,start,length)

SELECT SUBSTRING('hello welcome',10,3)//com


Starting from 10th charcters how many charcters 3 charcters.
SELECT SUBSTRING('helo welcome',7,4)//welc

LEFT & RIGHT


-------------
LEFT(string len)==>Returns chars from left side
RIGHT(string len)==>Returns chars from right side

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


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

Employees name starts with 'S'


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

Employees name ends with 's'


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

Employees name starts and ends with same char?


---------------------------
WHERE ename LIKE 'A%A' or ename LIKE 'B%B'
By using like cannot extract all records at once.

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

Generate Emailids as follows?


------------
EMPNO ENAME EMAILID
7369 smith [email protected]
7499 allen [email protected]

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


Here we are only diplaying the data but what if we want to store.

store emailids in db?


---------------
Step 1: add email id column to emp table
ALTER TABLE emp ADD emailid VARCHAR(20)

Step 2: update the column with emailids


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

REPLICATE()
------------
Repeats character for given number of times
REPLICATE(char,len)
SELECT REPLICATE('*',5)===>*****

DISPLAY ENAME and SAL ***


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

SCENARIO
------
your a/c no XXXX1234 debited

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

REPLACE()
------------
Used to replace one string with another string
REPLACE(str1,str2,str3)

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

TRANSLATE()
------------
Used to translate one character to another character

TRANSLATE(str1,str2,str3)

SELECT TRANSLATE('hello','elo','abc')//habbc

e==>a
1==>b
o==>c

SELECT TRANSLATE('hello','elo','ab')//Error

TRANSLATE function used to encrypt data i.e converting plain text to cipher text

cipher text--The text which you cant understand

usually passwords are encryted

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

Jones 2975.00 P%@&^$$

CHARINDEX()
------------
Returns position of a character in a string
CHARINDEX(char,string,[start])

SELECT CHARINDEX('o','hello welcome') =>5


SELECT CHARINDEX('x','hello welcome') =>0
SELECT CHARINDEX('o','hello welcome',6) =>11//Starts from 6th element

Display employee list name contains 'a' ?


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

Mathematical functions
------------
1) POWER:- Calculate power
POWER(3,2)=>9

2) SQRT:-Returns square root


SQRT(16)=>4

3)SQUARE:-Returns square
SQUARE(5)=>25

4)ABS:- Returns absolute value


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

5) SIGN():-Resturns whether given number is positive


or negative

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

6) Rounding Numbers:-
ROUND => rounds numbers based on avg
CEILING => rounds number always to highest
FLOOR=> rounds number always to lowest

38.4747383 =>38
38.47
38.4747

ROUND
------------
ROUND(number,decimal places)
ROUND(38.5678,0)===>39

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

number >= avg => Rounded to highest


number < avg => Rounde to lowest

ROUND(38.5678,2) => 38.57


ROUND(38.5678,3) => 38.568
ROUND(386,-2) => 400

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

ROUND(386,-1) => 390

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

ROUND(386,-3) => 0
0-------------------500-----------------------1000

SELECT ROUND(4567,-1),ROUND(4567,-2),ROUND(4567,-3)
4570 4600 5000

CEILING()
--------------------
Rounds number always to highest

CEILING(number)

SELECT CEILING(3.1) => 4

FLOOR()
-------------
Rounds number always to lowest

FLOOR(number)

SELECT FLOOR(3.9) => 3

Conversion Functions
-------------------
Used to convert one datatype to another datatype
1.CAST
2.CONVERT

CAST
----------
CAST(source-expr as target-type)

SELECT CAST(10.5 AS INT) =>10

Display smith earns 800


allen earns 1600

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


SELECT ename + ' earna ' + CAST(sal as varchar) FROM emp

Display smith joined on 1980-12-17 as clerk?


----------------------------
SELECT ename + ' joined on ' + CAST(hiredate AS VARCHAR) + ' as ' +job FROM emp

CONVERT()
----------------
CONVERT(TARGET-TYPE,SOURCE-EXPR)

SELECT CONVERT(INT,10.5) =>10

Difference between CAST & CONVERT?


----------------------------
1) Using convert we can display dates in different formats which is not possible
using cast function.

2) Using convert we cna display numbers in different formats which is not possible
using cast function

Displaying dates in different formats


-------------------------------
CONVERT(VARCHAR,DATE,STYLE-NUMBER)
First you need to convert into character type once you convert into character type
we cna display the date in different formats

We can write style numbers from 101-114

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

102 => 2022.10.12

DIsplay Ename and hire date and hiredate in mm/dd/yyyy format?


------------------
SELECT ENAME,CONVERT(VARCHAR,HIREDATE,101) AS HIREDATE FROM EMP

mm---minutes
MM---Months

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

SELECT FORMAT(GETDATE(),'dd/MM/yyyy hh:mm:ss')

Money and smallmoney styles


------------------------
CONVERT(VARCHAR,MONEY/SMALLMONEY,STYLE-NUMBER)
First convert money/small money into character format.Once you converted it into
different formats you can display it in different styles.

SELECT ENAME,CONVERT(VARCHAR,SAL,0) FROM EMP

0----Salary displayed with 2 decimal places


1---- Salary displayed with 1000 separator
2----Salary displayed with 4 decimal places

Display ENAME SAL ?


Display salaries with thousand separator ?

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

Special Functions
--------------
ISNULL()-----Used to convert null values

ISNULL(arg1,arg2)---takes two arguments

if arg1=null returns arg2


if arg1<> null returns arg1 only

SELECT ISNULL(100,200) ==>100


SELECT ISNULL(NULL,200)==>200

Display ENAME SAL COMM TOTSAL?

TOTSAL= SAL+COMM

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

SMITH 800 NULL NULL


ALLEN 1690 300 1900

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

Display ENAME SAL COMM ?


if COMM=NULL display NO COMM ?

SELECT ENAME,SAL, ISNULL(CAST(COMM AS VARCHAR),'NO COMM') AS COMM FROM EMP

Analytical Functions/ Window functions


---------------
rank & dense_rank
------------------
1) Both functions are used to find ranks
2) Ranking is based on some column
3) For rank functions input data must be sorted

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

Display ranks of the employees based on sal and highest paid employee should get
1st rank?
-------------------------
SELECT EMPNO,ENAME,SAL,RANK() OVER(ORDER BY SAL DESC) AS RNK FROM EMP

SELECT EMPNO,ENAME,SAL,DENSE_RANK() OVER(ORDER BY SAL DESC) AS RNK FROM EMP

Difference between rank and dense_rank


----------------------------------
1) Rank function generate gaps but dense_rank will not generate gaps
2) In rank function ranks may not be in sequence but in dense_rank ranks will be
always in sequence.

SAL RANK DENSE_RANK

5000 1 1
4000 2 2
3000 3 3
3000 3 3
3000 3 3
2000 6 4
2000 6 4
1000 8 5

DIsplay ranks of the employees based on sal desc, if salaries are same then ranking
should be based on hiredate asc?
------------------------
SELECT ename,hiredate,sal, DENSE_RANK() OVER (ORDER BY sal DESC, hiredate ASC) as
rnk FROM emp

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 and apply rank functions on each dept instead of
applying it on whole table.

SELECT ename,sal,deptno,dense_rank() over (partition by deptno order by sal desc)


as rnk FROM emp

ROW_NUMBER()
-------------------
Returns record numbers
row_number is also based on some column
data must be sorted

Syntax: ROW_NUMBER() OVER (ORDER BY COLNAME ASC/DESC,------)

SELECT EMPNO,ENAME,SAL ROW_NUMBER() OVER (ORDER BY SAL DESC) AS RNO FROM EMP

Aggregate Functions
------------------
From a group of value if we get a single value that is called aggregate
These functions process group of rows and returns one value

MAX()---> Returns maximum value


MAX(arg)

SELECT MAX(sal) FROM emp


SELECT MAX(hiredate) FROM emp
SELECT MAX(ename) FROM emp

MAX() function can be applied on numeric, date,charcter columns

MIN()---->Returns minimum value


MIN(arg)

SELECT MIN(sal) FROM emp

MIN() function can be applied on numeric, date,charcter columns

SUM()
-----
Returns total
SUM(args)

SELECT SUM(SAL) FROM EMP ==>29025

Round the total sal to hundreds?


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

After rounding display total sal with thousand separator?


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

Display total sal paid to managers


---------------------------
Select sum(sal) from EMP WHERE Job='Manager'

Calculate total sal including comm


---------------------
Select sum(sal+comm) from emp
AVG()
-----
Returns average value
AVG(arg)

SELECT AVG(sal) FROM EMP

==>round avg(sal) to lowest integer?


----------------
Select floor(avg(sal)) From emp

Note: sum,avg functions cannot be applied on date and char columns can be applied
only on numeric columns

COUNT(*)
-----------
Returns no of rows in a table.
SELECT COUNT(*) FROM EMP

Display no of employees joined in 1981 year


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

Display no of employees joined on sunday


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

Select count(empno) from emp

Select count(comm) from emp// If nulls are there in the column they are not
countable

Note: aggregate, window functions are not allowed in where clause

Select ename from emp where sal=max(sal) =>Error


Select ename from emp where count(*)=3==>Error

Note: Window functions can only appear in the SELECT or ORDER BY caluses

Select * from emp where dense_rank() over(order by sal desc) =3 ===>Error

SELECT col1,col2 From tabname


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

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


14 1
2) SELECT ename,ROUND(sal,0) FROM emp ==>valid
14 14

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


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

CASE Statement
--------------
Used to implement IF-THEN-ELSE
Useful to return expressions based on conditions
Case statements are 2 types
1) Simple case 2) Searched case

Simple case
------------
Use simple case when conditions based on "=" operator

CASE COLNAME
WHEN VALUE1 THEN RETURN EXPR1
WHEN VALUE2 THEN RETURN EXPR2
---------------------
ELSE RETURN EXPR
END

===>Display ENAME DNAME ?


if deptno=10 display ACCOUNTS
20 RESEARCH
30 SALES
OTHERS UNKNOWN

SELECT ENAME,
CASEDEPTNO
WHEN10 THEN 'ACCOUNTS'
WHEN20 THEN 'RESEARCH'
WHEN30 THEN 'SALES'
ELSE 'UNKNOWN'
END AS DNAME
FROM EMP

Display ename job ?


if job=CLERK display WORKER
MANAGER BOSS
PRESIDENT BIG BOSS
ELSE EMPLOYEE

===>Increment employee salaries as follows?


if job=CLERK incr sal by 10%
SALESMAN 15%
MANAGER 20%
OTHERS 5%

Update emp
set sal=CASE job
WHEN 'clerk' THEN sal+(sal*0.1)
WHEN 'salesman' THEN sal+(sal*0.15)
WHEN 'manager' THEN sal+(sal*0.2)
ELSE sal+(sal*0.05)
END

Searched Case
--------------
Use searched case when conditions not based on "=" operator.

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

==>Display ENAME SAL SALRANGE?


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

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

===>Display SNO SNAME TOTAL AVG RESULT?


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

SELECT SNO,SNAME
S1+S2+S3 As Total
(S1+S2+S3)/3 As Avg
CASE
WHEN S1>=35 AND S2>=35 AND S3>=35 THEN 'PASS'
ELSE 'FAIL'
END AS RESULT
FROM EMP

GROUP BY Clause
-----------------
Used to group rows based on one or more columns to calculate min,max,sum,avg,count
for each group.

empno ename sal deptno


1 A 5000 10
2 B 6000 20 GROUP BY 10 10000
3 C 7000 30==========================> 20 12000
4 D 6000 20 30 7000
5 E 5000 10

Detailed Data Summarized Data

GROUP BY clause converts detailed data into summarized data which is useful for
data analysis.

Syntax:
-------
Select columns from tablename [where condition]
group by <colname>,---------------
[having condition]
[order by <colname> asc/desc-------]

Here in this syntax group by clause is mandatory and other clauses are optional.

Execution order of clauses


------------------
from, where, group by, having, select, order by

Display dept wise total salary?


-----------------------
SELECT deptno,SUM(sal) as totsal FROM emp GROUP BY deptno

Display job wise no of employees?


-------------------
SELECT job, COUNT(*) as cnt from emp group by job

Display year wise no of employees joined


--------------------
Select DATEPART(yy,hiredate) as year, COUNT(*) as cnt from emp group by
DATEPART(yy,hiredate)

Display no of employees joined in each month in the year 1981?


---------------------------------
Select DATENAME(mm,hiredate) as month, COUNT(*) as cnt FROM emp WHERE
DATEPART(yy,hiredate)=1981 GROUP BY DATENAME(mm,hiredate)

Display depts having more than 3 employees working ?


--------------------
SELECT deptno, count(*) FROM emp WHERE COUNT(*) >3 GROUP BY deptno====>Error

SQL SERVER cannot calculate dept wise count before group by and it can calculate
only after group by , so apply the condition COUNT(*)> after group by using HAVING
clause.

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


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

Scenario
----
PERSONS
AADHARNO NAME GENDER AGE ADDR CITY STATE

FInd the southern states having more than 5cr population


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

Difference between where clause and having clause


-------------------------------
WHERE Clause
----------
Selects specific rows
conditions applied before group by
use where clause if condition not based on aggregate function
HAVING Clause
------------
Selects specific groups
conditions applied after group by
use having clause if condition based on aggregate function

Display dept wise and job wise total salary?


-------------------------
SELECT deptno,job,SUM(sal) as totsal,COUNT(*) as cnt
FROM emp
GROUP BY deptno,job
ORDER BY deptno ASC

ROLLUP & CUBE


---------------
Both functions are used to display subtotals and grand total
rollup and cubes are applied on group by columns
GROUP BY ROLLUP(COL1,COL2,----------------)
GROUP BY CUBE()COL1,COL2,-----------------)

ROLLUP
-----------
rollup displays subtotals for each group and also displays grand total

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


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

CUBE
---------
displays subtotals for each group by column (deptno,job) and also displays grand
total

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


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

Display state wise and with in state gender wise population and display state wise
and gender wise subtotals
----------------------------------
SELECT state,gender,count(*) FROM persons
GROUP BY CUBE(state,gender)
ORDER BY state ASC,gender ASC

GROUPING_ID
-------------------
This function accepts group by columns and returns sub total belong to which group
by column

GROUPING_ID(deptno,job)

1==>subtotal belongs to 1st group by column i.e dept no


2==>subtotal belongs to 2nd group by column i.e job
3==>grand total

SELECT deptno,job,SUM(sal) as totsal,


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

For clear understanding for user write the above query like this

SELECT deptno,job,SUM(sal) as totsal,


CASE GROUPING_ID(deptno,job)
WHEN 1 THEN 'Dept Subtotal'
WHEN 2 THEN 'Job Subtotal'
WHEN 3 THEN 'Grand Total'
END as subtotal
FROM emp
GROUP BY CUBE(deptno,job)
ORDER BY deptno ASC,job ASC

Integrity Constraints
-------------------------
Integrity constraints are the rules to maintain Data Integrity i.e Data Quality
Used to prevent users from entering invalid data
Used to enforce rules like min bal must be 1000

Different integrity constraints in sql server

1) NOT NULL
2) UNIQUE
3) PRIMARY KEY
4) CHECK
5) FOREIGN KEY
6) DEFAULT

Constraints can be decalred in two ways

1) column level
2) table level

column level
-----------------
If constraints are decalred immediately after declaring column then it is called
column level

CREATE TABLE <tabname>


(
colname datatype(size) constraint,
)

NOT NULL
-------
NOT NULL constraint doesnt accept null values
A column decalred with NOT NULL is called mandatory column

Example:
---------
CREATE TABLE emp22(
empno INT,
ename VARCHAR(10) NOT NULL)
INSERT INTO emp22 VALUES(100,NULL)==>Error
INSERT INTO emp22 VALUES(101,'A')

Unique
-----------
Unique constriant doesnt acccept duplicates

Example
----------
CREATE TABLE cust(
cid int,
cname varchar(10),
emailid varchar(20) UNIQUE)

INSERT INTO cust VALUES(100,'A','[email protected]')


INSERT INTO cust VALUES(101,'B','[email protected]')====> Error
INSERT INTO cust VALUES(102,'C',NULL)
INSERT INTO cust VALUES(103,'D',NULL)=======>Error

PRIMARY KEY
----------------
Primary key doesnt accept duplicates and nulls
Primary key is the combination of unique and not null

Primary key=Unique+Not Null

In DB tables one column must be there to uniquley identify the records and that
column must be declared with primary key.

Example
-----------
CREATE TABLE emp33(
empid INT PRIMARY KEY,
ename VARCHAR(10) NOT NULL,
sal MONEY)

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


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

Beacuse empid doesnt allow duplicates and nulls so using empid we can uniquely
identify the records.

only one primary key is allowed per table

Create table cust(


custid int primary key,
name varchar(10) not null,
aadharno numeric(12) unique not null
panno char(10) unique not null)

Difference between unique and primary key


---------------------------
Unique
-------
1) Allows one null
2) Multiple columns can be declared with unique

Primary Key
---------
1) Doesnt allow nulls
2) Only one column can be declared with primary key

Candidate key
-------------
A field eligible for primary key is called candidate key

VECHILE
VECHNO VNAME MODEL PRICE CHASSISNO

Candidate Keys: vechno, chassisno


primary key: vechno
secondary key: chassisno
or
alternate key

While creating table secondary keys are declared with UNIQUE & NOT NULL

CHECK
---------
Use check constraint when rule based on condition
CHECK(condition)

ex: sal must be min 3000

CREATE TABLE emp44(


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

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


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

Ex 2: Gender must be 'm','f'

GENDER CHAR(1) CHECK(GENDER IN ('M','F'))

Ex 3: Amount must be multiple of 100

AMOUNT MONEY CHECK(AMT%100=0)

Ex 4: Password must be minimum 6 characters

password VARCHAR(10) CHECK(LEN(PWD)>=6)

Ex 5: emailid must contain '@'


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

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

Foreign Key
------------
1) foreign key is used to establish relationship between two tables.
2) To establish relationship take primary key of one table nad add it to another
table as foreign key and declare with references constraint.
3) Foreign key allows duplicates and nulls
4) After declaring foreign key a relationship is established between two tables
calles parent/child relation ship.
5) PK table is parent and FK table is child

CREATE TABLE projects


(
projid INT PRIMARY KEY,
pname VARCHAR(10),
sal MONEY CHECK(sal>=3000)
projid INT REFRENCES projects(projid)
)

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


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

Assignment
-----------
ACCOUNTS
ACCNO ACTYPE BAL

Rules
------------
1) Accno should not be duplicate and null
2) Actype must be 's' or 'c'
3) Bal must be min 1000

TRANSACTIONS
TRID TTYPE TAMT TDATE ACCNO

Rules
--------
1) trid must be auto incremented
2) ttype must be 'w' or 'd'
3) tamt must be multiple of 100
4) tdate must be system date
5) accno should match with accounts table accno

Write create table scripts?

Types of relationships
----------------------
one to one (1:1)
one to many(1:m)
many to one(m:1)
many to many(m:m)

In sql server by default one to many relationship is created between two tables

To establish one to one (1:1) realtion ship between two tables decalre forign key
with unique constraint.

Example :- (1:1)
DEPT
DNO DNAME
10 HR
20 IT

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

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

Many to Many:---(M:N)
--------------------------
By default sql server doesnt support many to many relationship

Here many to many relationship is divided into 2 one to many realtionships.

Example
----------
PRODUCTS CUSTOMERS
prodid pname price cid name addr
100 A 1000 10 x HYD
101 B 2000 11 k HYD

Relationship between products and customer is many to many because one product can
be purchased by many customers and one customer can purchase many products.

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

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

ER Diagram- graphical representation of database


Flow chart - graphical representation of program

ER MODEL RELATIONAL MODEL


------------ ----------------------
To deign database to develop database
entities tables
attributes fields
relationship foreign key

DEFAULT
-----------
==> While inserting if we skip hiredate then sql server inserts default value
CREATE TABLE emp66
(
empno INT,
hiredate DATE DEFAULT GETDATE()
)

INSERT INTO emp66(empno) values(100)


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

SELECT * FROM emp66

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

TABLE LEVEL
-------------
If constraints are decalred after declaring all columns then it is called table
level

CREATE TABLE <tabname>


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

Use table level to declare constraint for multiple or combination of columns.

Decalring check constraint at table level


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

RULE: exp_dt > mfd_dt

CREATE TABLE products


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

Composite Primary key


----------------
---> If combination of columns declared as primary key then it is called composite
primary key
--->I n composite primary key combination should not be duplicate
---> In some tables we may not be able to uniquely identify by using single column
and we need combination of columns to uinquley identify and that combination should
be declared primary key at table level

Example:
STUDENT COURSE
SID NAME CID NAME
1 A 10 SQL
2 B 11 .NET
REGISTRATIONS
SID CID DOR FEE
1 10 ? ?
1 11 ? ?
2 10 ? ?

In the above example sid,cid combination uniquely identifies records so declare


this combination as primary key at table level.

CREATE TABLE student


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

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

CREATE TABLE course


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

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

CREATE TABLE registrations


(
sid INT REFRENCES STUDENT(SID),
cid INT REFRENCES COURSE(CID),
dor DATE,
fee MONEY,
PRIMARY KEY(sid,cid)
)

INSERT INTO registrations VALUES(1,10,GETDATE(),1000)


INSERT INTO registrations VALUES(1,11,GETDATE(),1000)
INSERT INTO registrations VALUES(2,10,GETDATE(),1000)
INSERT INTO registrations VALUES(1,10,GETDATE(),1000)====>Error

composite foreign key


--------------------------
If combination of columns declared foreign key then it is called composite forign
key

A composite forign key references composite primary key

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

CERTIFICATES
CERTNO DOI SID CID
1000 ? 1 10
1001 ? 1 11
1002 ? 2 11====>Invalid
In the above example SID,CID combination should match with registrations table
primary key i.e SID,CID combination so declare this combination as foreign key at
table level.

CREATE TABLE certificates


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

Adding constraints to existing table


---------------------------
ALTER command is used to add constraints to existing table

CREATE TABLE emp88(


empno INT,
ename VARCHAR(10)
sal MONEY,
dno INT)

Adding check constraint


----------------------------
Add check constraint with condition sal>=3000

ALTER TABLE EMP88 ADD CHECK(SAL>=3000)

ALTER TABLE EMP ADD CHECK(SAL>=3000) ===>Error

Because some of the employee salaries are less than 3000 while adding constraint
sql server also validates existing data

WITH NOCHECK
------------------
If check constraint added with "NO CHECK" then sql server will not validate
existing data and it validates new data.

ALTER TABLE EMP


WITH NOCHECK ADD CHECK(SAL>=3000)

Adding primary key


------------------
primary key can be added only to not null column but cannot be added nullable
column

to add primary key

1) change the column to not null


2) add primary key

==> add primary key to empno?


ALTER TABLE emp88
ALTER COLUMN empno INT NOT NULL

ALTER TABLE emp88


ADD PRIMARY KEY(empno)
Adding foreign key
---------------------
Add foreign key to dno that references dept table primary key i.e deptno?

ALTER TABLE emp88


ADD FOREIGN KEY(DNO) REFERENCES DEPT(DEPTNO)

Changing column from NULL to NOT NULL


--------------------------
ALTER TABLE EMP88
ALTER COLUMN ENAME VARCHAR(10) NOT NULL

Dropping Constraints
-------------------
ALTER TABLE <tabname>
DROP CONSTRAINT <name>

Ex: drop check constraint in emp88 table


------------------------
ALTER TABLE EMP88
DROP CONSTRAINT CK__emp88__sal__6477ECF3

Drop primary key in dept table?


------------------------
ALTER TABLE DEPT DROP CONSTRAINT PK__DEPT_E0E808D7B829E841====>Error

DROP TABLE DEPT ===>Error

TRUNCATE TABLE DEPT ====>Error

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

DELETE Rules
-----------------
ON DELETE NO ACTION
ON DELETE CASCADE
ON DELETE SET NULL
ON DELETE SET DEFAULT

==> These rules are decalred with foreign key


==> These rules specifies how child rows are affected if parent row is deleted.

ON DELETE NO ACTION
----------------------------
Parent row cannot be deleted if associated with child rows

CREATE TABLE dept99


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

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

CREATE TABLE emp99


(
empno INT PRIMARY KEY,
dno INT REFERENCES dept99(dno)
)

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

DELETE FROM DEPT99 WHERE DNO=10==========>Error

Scenario
----------------
ACCOUNTS
ACCNO ACTYPE BAL
100 S 10000

LOANS
ID TYPE AMT ACCNO
1 H 30 100
2 C 10 100

RULE: Account closing is not possible if associated with loans.

ON DELETE CASCADE
--------------------------
If parent row is deleted then it is deleted along with child rows.

CREATE TABLE dept99


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

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

CREATE TABLE emp99


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

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

DELETE FROM DEPT99 WHERE DNO=10 =>1 row affected

SELECT * FROM EMP99 ===>NO rows

Scenario
------------
ACCOUNTS
ACCNO ACTYPE BAL
100 S 10000

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

RULE: When account is closed then along with account delete transactions.
ON DELETE SET NULL
----------------------
If parent row is deleted then it is deleted without deleting child rows but foreign
key will be set to null.

CREATE TABLE dept99


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

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

CREATE TABLE emp99


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

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

DELETE FROM DEPT99 WHERE DNO=10===>1 Row Affected

SELECT * FROM EMP99

EMPNO DNO
1 NULL
2 NULL

Scenario
----------------
PROJECTS
projid pname duration
100
101

EMP
empid name projid
1 100
2 100

Rule: If project is deleted then set the employee projid to null.

ON DELETE SET DEFAULT


----------------------------
If parent row deleted then it is deleted with deleting child rows but foreign key
will be set to default value

CREATE TABLE dept99


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

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

CREATE TABLE emp99


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

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

DELETE FROM DEPT99 WHERE DNO=10 =>1 Row Affected.

Update Rules
------------------
ON UPDATE NO ACTION
ON UPDATE CASCADE
ON UPDATE SET NULL
ON UPDATE SET DEFAULT

Update rules specifies how foreign key value is affected if we update primary key
value

JOINS
---------

Repeatation of data, duplication of data is called redundancy

Join is an operation performed to fetch data from two or more tables

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


tables we need to join those tables.

Types of joins
----------------------
1) Inner join/ Equi Join
2) Outer Join
Left
Right
Full
3) Non Equi Join
4) Self Join
5) Cross Join/ Cartesian Join

Inner Join/Equi Join


---------------------
Inner Join returns only matching records.

To perform Inner join between the two tables there must be a common field and name
of the common field need not to be same and pk-fk relation shipis not compulsory

Inner join is performed on common field with same datatype

SELECT columns FROM tab1 INNER JOIN tab2 ON join condition

join condition
-----------------
based on the given join condition sql server joins the records of two tables.
table1.commonfield = table2.commonfield

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

==> display ENAME SAL DNAME LOC


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

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

A 3000 ACCTS ???


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

Note:
--------
In join queries declare table alias and prefix column names with table alias for
two reasons
1) to avoid ambiguity
2) for faster execution

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


FROM emp e INNER JOIN dept d
ON e.deptno = d.deptno//join condition

Where d.loc='NEW YORK'//filter condition

Joining more than 2 tables


--------------------------------
If number of tables increases number of join conditions also increases, to join N
Tables N-1 join conditions required.

EMP DEPT LOCATIONS COUNTRIES


empno deptno locid country_id
ename dname city country_name
sal locid state
deptno country_id

Display ENAME DNAME CITY STATE COUNTRY


---------- ----------- ----------- -------- ------------
EMP DEPT LOCATIONS COUNTRIES

SELECT e.ename, d.dname, l.city, l.state, c.country_name


FROM emp e INNER JOIN dept d
ON e.deptno=d.deptno
INNER JOIN locations l
ON d.locid=l.locid
INNER JOIN countries c
ON l.country_id=c.country_id

Outer Join
---------------
Inner join returns only matching records but wont return unmatched records but to
display unmatched records perform outer join.

outer join is 3 types


1 LEFT JOIN
2 RIGHT JOIN
3 FULL JOIN

LEFT JOIN
-------------
returns all rows(matched+unmatched) from left side table and matching rows from
right side table.

SELECT e.ename, d.dname


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

Above query returns all rows from emp and matching rows from dept

A ACCT
B RESEARCH
C SALES
D ACCT
E NULL ==> unmatched from emp

Right Join
----------------
Returns all rows from right side table and matching rows from left side table.

SELECT e.ename, d.dname


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

A ACCT
B RESEARCH
C SALES
D ACCT
NULL OPERATIONS ==> unmatched from dept

Full Join
--------------
Returns all rows from both tables.
SELECT e.ename,d.dname
FROM emp e RIGHT JOIN dept d
ON e.deptno=d.deptno

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

Displaying unmatched records


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

E NULL

right side table


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

NULL OPERATIONS

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

E NULL
NULL OPERATIONS

SELF JOIN
--------------
Joining a table to itself is called self join
In Self join a record in one table joined with another record of same table
To perfrom self join the same table must be declared two times with different alias

FROM EMP X JOIN EMP Y


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

==> display ENAME MGRNAME ?


-------------------------
SELECT X.ENAME, Y.ENAME AS MGRNAME
FROM EMP X JOIN EMP Y
ON X.MGR=Y.EMPNO

Display employees reporting to blake


--------------------------------
SELECT X.ENAME, Y.ENAME AS MGRNAME
FROM EMP X JOIN EMP Y
ON X.MGR=Y.EMPNO
WHERE Y.ENAME='BLAKE'

Display blakes manager name


-----------------------
SELECT X.ENAME, Y.ENAME AS MGRNAME
FROM EMP X JOIN EMP Y
ON X.MGR=Y.EMPNO
WHERE x.ENAME='BLAKE'

Display employees earning more than their manager


---------------------------
SELECT X.ENAME, Y.ENAME AS MGRNAME
FROM EMP X JOIN EMP Y
ON X.MGR=Y.EMPNO
WHERE X.SAL>Y.SAL

Question
--------------
TEAMS
ID COUNTRY
1 IND
2 AUS
3 NZ

Write the query to display following output?


-----------------------
IND VS AUS
IND VS NZ
AUS VS NZ

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

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


B.ID

IND IND IND AUS AUS IND IND AUS


AUS AUS IND NZ NZ IND IND NZ
NZ NZ AUS IND NZ AUS AUS NZ
AUS NZ
NZ IND
NZ AUS

SELECT A.COUNTRY + ' VS ' + B.COUNTRY


FROM TEAMS A JOIN TEAMS B
ON A.ID < B.ID

CROSS JOIN / CARTESIAN JOIN


--------------------------------
cross join returns cross product or cartesian product of two tables

A=1,2
B=3,4

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

If cross join performed between teo tables then all the records of 1st table joined
with all the records of 2nd table
To perform cross join submit the join query without join condition.

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

GROUP & JOIN


--------------------
Display dept wise total sal? display dept names?
----------------------
SELECT d.dname,SUM(e.sal) as totsal
FROM emp e INNER JOIN dept d
ON e.deptno = d.deptno
GROUP BY d.dname

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

ON e.deptno = d.deptno
-------------------
1 A 3000 10 ACCTS
2 B 4000 20' RESEARCH
3 C 5000 30 SALES
4 D 3000 20 RESEARCH
5 E 2000 10 ACCTS

GROUP BY d.dname
-------------------
ACCTS
1 A 3000
5 E 2000

RESEARCH
2 B 4000
4 D 3000

SALES
3 C 5000

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


----------------------------
ACCTS 5000
RESEARCH 7000
SALES 5000

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

PRODUCTS
PRODID PNAME PRICE CATEGORY
100 AAA 1000 ELECTRONICS
CUSTOMERS
CUSTID NAME ADDR COUNTRY
10 KK HYD IND

Display quarter wise total amount in yearr 2022?


Display category wise total amount?
display country wise total amount?
display coutry wise,category wise,year wise total amount?

SET OPERATORS
--------------
UNION
UNION ALL
INTERSECT
EXCEPT

A = 1,2,3,4
B = 1,2,5,6

A UNION B = 1,2,3,4,5,6
A UINON 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
queries.

SELECT STATEMENT 1
UNION/UNION ALL/INTERSECT/EXCEPT
SELECT STATEMENT 2

Rules
--------
1) Both queries must return same no of columns
2) Corresponding columns data type must be same

UNION
-------------
==> combines rows return by two queries
==> eliminates duplicates
==> sorts result

SELECT job FROM emp WHERE deptno=20

CLERK
MANAGER
ANALYST
CLERK
ANALYST

SELECT job FROM emp WHERE deptno=30

SALESMAN
SALESMAN
SALESMAN
MANAGER
SALESMAN

SELECT job FROM emp WHERE deptno=20


UNION
SELECT job FROM emp WHERE deptno=30

ANALYST
CLERK
MANAGER
SALESMAN

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

1) Hoizontal merge Vertical merge


2) Combines rows combines columns
3) Performed between two similar structures can be performed between two
dissimilar
structures

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

==> total employees list?


-----------------
SELECT * FROM EMP_US
UNION
SELECT * FROM EMP_IND

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


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

==> total employee list with dept details


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

UNION ALL
------------------
==> combines rows return by two queries
==> duplicates are not eliminated
==> result is not sorted

SELECT job FROM emp WHERE deptno=20


UNION ALL
SELECT job FROM emp WHERE deptno=30

Difference between UNION and UNION ALL


-----------------------------
UNION UNION ALL
---------- ----------
1) Eliminates duplicates duplicates are not eliminated
2) result is sorted result is not sorted
3) slower faster

INTERSECT
--------------------
returns common values from the output of two select statements

SELECT job FROM emp WHERE deptno=20


INTERSECT
SELECT job FROM emp WHERE deptno=30

EXCEPT
--------
returns values from 1st query output and not present in 2nd query output

SELECT job FROM emp WHERE deptno=20


EXCEPT
SELECT job FROM emp WHERE deptno=30

Display first day of the year??


--------------------------
SELECT DATEADD(yy,datediff(yy,0,getdate()),0)
0 means 1900-01-01
DATEADD(interval,int,date)

SUBQUERIES/NESTED QUERIES
-------------------------------------
A query in another query is called sub query or nested query
One query is called inner/child/sub query
other query is called outer/parent/main query
First sql server executes inner query then it executes outer query and result of
inner query is input to outer query
Use subquery when where condition based on unknown value

Employees earning more than blake?


--------------------
where sal>(select sal from emp where ename='blake')

Types of subqueries
---------------------
1) Single row subqueries
2) multi row subqueries
3) co-related subqueries
4) derived tables
5) scalar subqueries

single row subqueries


--------------------------
If inner query returns one value then it is called single row subquery

SELECT columns FROM tabname


WHERE colname OP (SELECT STATEMENT)

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

Employees earning more than blake?


-------------------------------
SELECT * FROM emp WHERE sal > (SELECT sal FROM emp WHERE ename='blake')

Employees who are senior to king?


---------------------------
SELECT * FROM emp WHERE hiredate < (SELECT hiredate FROM emp WHERE ename='king')

Display name of the employee earning max sal?


---------------------
SELECT ename FROM emp WHERE sal= MAX(sal) => ERROR

SELECT ename FROM emo WHERE sal = (SELECT MAX(sal) FROM emp) => Correct

Name of the employee having max experience


-----------------------------
SELECT ename FROM emp WHERE hiredate = (SELECT MIN(hiredate) FROM emp)

Display 2nd max salary


-----------------
SELECT MAX(sal) FROM emp WHERE sal < (SELECT MAX(sal) FROM emp)

Name of the employee earning 2nd max sal?


---------------------------
SELECT ename FROM emp WHERE sal = (SELECT MAX(sal) FROM emp WHERE sal < (SELECT
MAX(sal) FROM emp))

Note:
----------
Outer query can be SELECT/INSERT/UPDATE/DELETE but inner query must be always
SELECT

Delete employee having max experience


---------------------------
DELETE FROM emp WHERE hiredate = (SELECT MIN(hiredate) FROM emp)

Incerement salaries by 10% those working at newyork location


-----------------------------
UPDATE emp SET sal=sal+(sal*0.1)
WHERE deptno = (SELECT deptno FROM dept WHERE loc='NEW YORK')

Multirow subqueries
--------------------------
If subquery returns more than one value then it is called multirow subquery

SELECT columns
FROM tabname
WHERE colname OP (SELECT STATEMENT)
==> OP must be IN, NOT IN, ANY, ALL

Display employees working at new york, chicago?


------------------------------
SELECT * FROM emp WHERE deptno = (SELECT deptno FROM dept WHERE loc IN('NEW
YORK','CHICAGO'))

ANY operator
-----------------
==> used for > < comaprision with multiple values

WHERE x > ANY(1000,2000,3000)


if x=800 false
x=1500 true
x=4500 true

WHERE x < ANY(1000,2000,3000)


x = 800 true
x = 1500 true
x = 4500 false

ALL
--------
used for > < comaprision with multiple values

WHERE

Employees earning more than all managers


--------------------
SELECT * from emp where sal > all(select sal from emp where job='manager')

Employees earning more than atleast one manager?


---------------------------
select * from emp where sal > any (select sal from emp where job='manager')

DERIVED TABLES
------------------
Subqueries in FROM clause are called derived tables

SELECT columns
FROM (SELECT statement) <alias>
WHERE cond

==> Sub query output acts like a table for outer query

==> Derived tables are used in following scenarios

1) to control order of execution of clauses


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

Controlling order of execution


-------------------------
By default sql server executes the clauses in the following order

FROM
WHERE
GROUP BY
HAVING
SELECT
ORDER BY

Use derived tables to control this order of execution

Display ENAME ANNUAL SALARY?


--------------------
SELECT ename, sal*12 as annsal FROM emp

Above query returns annual salaries of all employees but to display employees whose
annual salary > 20000 then

SELECT ename, sal*12 as annsal


FROM emp
WHERE annsal > 20000 ==> ERROR

column alias cannot be used in where clause because where clause is executed before
select, to overcome this ise derived table

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

Example 2
-------------
Display ranks of the employees based on sal and highest paid employee should get
1st rank?
-----------------------
SELECT ENAME,SAL,DENSE_RANK() OVER (ORDER BY SAL DESC) AS RNK From EMP

Above query returns ranks of all the employees but to display top 5 employees

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

SELECT * FROM(SELECT ENAME,SAL,DENSE_RANK() OVER (ORDER BY SAL DESC) AS RNK From


EMP
) AS E WHERE RNK <=5

Display top 5 max salaries


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

Methods to find top 5 max salaries


------------------------
Using top clause
co related sub queries
using derived tables with dense rank
Example 3
------------
Display first 5 rows from emp table
-----------------------
SELECT *
FROM(SELECT empno,ename,sal,ROW_NUMBER() OVER (order by empno asc) FROM emp
) AS E
WHERE rno<=5

WHERE rno=5

WHERE rno IN(5,7,11)

WHERE rno BETWEEN 5 AND 10

WHERE rno%2=0

Display last 3 rows


-----------------
SELECT * FROM (SELECT empni,ename,sal,ROW_NUMBER() over
(order by empno asc FROM emp) AS E
WHERE rno>=(SELECT COUNT(*)-2 FROM EMP)

DELETE
FROM(SELECT empno,ename,sal,ROW_NUMBER() over (order by empno asc)
FROM emp) AS E
WHERE rno<=3 ===> Error

Note: In dervived tables outer query cannot be DML and it must be always SELECT. To
overcome this use CTEs.

CTE
----------
CTE stands for common table expression, It is a named query that can be referenced
in another query like SELECT/INSERT/UPDATE/DELETE.

In Dervied tables outer query cannot be DML but in CTE'S outer query can be
SELECT/INSERT/UPDATE/DELETE

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

Example
----------
Delete first 5 rows from emp??
----------------
WITH E AS
(SELECT empno,ename,ROW_NUMBER() OVER (ORDER BY empno ASC) as rno
FROM emp)
DELETE FROM E WHERE rno<=5

Pivot Operator
---------------------
==> used to convert rows into columns
==> used for cross tabulation
==> used to display data in matrix form

Example
-------

10 20 30
ANALYSR ?? ?? ??
CLERK ?? ?? ??
MANAGER ?? ?? ??
SALESMAN ?? ?? ??

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

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

Example 2
-----------
1 2 3 4
1980 ? ? ? ?
1891 ? ? ? ?
1982 ? ? ? ?
1983 ? ? ? ?

SELECT * FROM(SELECT DATEPART(YY,HIREDATE) AS YEAR,


DATEPART(QQ,HIREDATE) AS QRT,
EMPNO
From emp ) AS E
PIVOT
(
COUNT(EMPNO) FOR QRT IN ([1],[2],[3],[4])
) AS PIVOT_EXPR
ORDER BY YEAR ASC

Example 3
--------------

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

Output
------------
SNO SNAME MAT PHY CHE
1 A 80 50 60
2 B 70 40 50

SELECT * FROM STUDENT


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

UNPIVOT Operator
----------------
1) reverse of PIVOT is called UNPIVOT operator
2) converts columns into rows

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

OUTPUT
-----------
SNO SNAME SUBJECT MARKS
1 A MAT 80
2 A PHY 90
3 A CHE 70
2 B MAT 60
2 B PHY 50
2 B CHE 70

SELECT SNO, SNAME, SUBJECT, MARKS


FROM STUDENT
UNPIVOT
(
MARKS FOR SUBJECT IN([MAT],[PHY],[CHE])
)

ORDER BY SNO ASC

Creating a new table from exisiting table :- (replica)


---------------------
SELECT columns/* INTO <new-tabname>
FROM <old-tabname>
WHERE cond

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

Example 1: (copying whole table)


--------
SELECT * INTO emp10
FROM emp
Example 2: (copying specific rows and columns)

SELECT empno,ename,job,sal INTO emp11


FROM emp
WHERE deptno IN(10,20)

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

SELECT * INTO emp12


FROM emp
WHERE 1=2

MERGE command
------------------
=> Command used to merge data into a table
=> It is the combination of insert, update and delete
=> Widely used in ETL applications
=> Used to manage replicas

E==> Extract
T==> Transform
L==> Load

Syntax:
------------
MERGE INTO <TARGET-TABLE> <ALIAS>
USING <SOURCE-TABLE> <ALIAS>
ON(CONDITION)
WHEN MATCHED THEN
UPDATE
WHEN NOT MATCHED THEN
INSERT
WHEN NOT MATCHED BY SOURCE THEN
DELETE

Example:-
-------
Step 1:- Create source table

CUSTS
CID NAME ADDR
1 A HYD
2 B MUM

Step 2: - create replica for custs

SELECT * INTO CUSTT FROM CUSTS

CUSTT
CID NAME ADDR
1 A HYD
2 B MUM

Step 3: - modify the source table

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

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


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

Step 4:- replicate changes to custt

MERGE INTO CUSTT AS T


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

DB SECURITY
------------
1 LOGINS => Provides security at server level
2 USERS => provides security at db level
3 PIVILEGES => provides security at table level
4 VIEWS => provides security at row and col level

GRANT SELECT, INSERT, UPDATE, DELETE ON EMP TO NARESH

VIEWS
------------
==> A view is a subset of a table
==> A view is a virtual table because it doesnt store data and doesnt occupy menory
and it always derives data from base table
==> A view is representation of a query
==> Views are created
1) For security
2) To reduce complexity

Views provides another level of security by granting specific rows and columns to
users

Views are 2 types

1) Simple Views
2) Complex Views

Simple Views
------------
If view created on single table then it is called simple view

CREATE VIEW <NAME>


AS
SELECT STATEMENT

example:
-----------
Create view v1
as
Select empno, ename, job, deptno from emp
==> When above command is executed sql server creates view v1 and stores query but
not query output.

Select * from v1

==> When above query submitted to sql server it executes the query as follows

Select * from (Select empno, ename, job, deptno from emp)

Granting permissions on view to user


----------------------------
GRANT SELECT, INSERT, UPDATE, DELETE ON V1 TO NARESH

NARESH
-------------
1) SELECT * FROM V1
2) UPDATE V1 SET JOB='SALESMAN' WHERE EMPNO=7698
3) UPDATE V1 SET SAL=4000 WHERE EMPNO=7698=====> Error

Row Level Security


------------------
CREATE VIEW V2
AS
SELECT EMPNO,ENAME,JOB,DEPTNO
FROM EMP
WHERE DEPTNO=20

GRANT SELECT,INSERT,UPDATE,DELETE ON V2 TO NARESH

==> user "NARESH" can access only the employees belongs to 20th department

Complex views
----------------
A view said to be complex view

1) If based on multiple tables (Joins)


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

With the help of view complex queries are converted into simple queries

CREATE VIEW CV1


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

After creating view whenever we want data from emp & dept tables instead of writing
join query write the simple query as follows

SELECT * FROM CV1

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

AFter creating view whenever we want dept wise summary

SELECT * FROM CV2

Display list of tables created by user?


---------------------------
SELECT * FROM INFORMATION_SCHEMA.TABLES

Display list of views created by user?


---------------------------
SELECT * FROM INFORMATION_SCHEMA.VIEWS

Droping View
-----------------
Drop VIEW V1

If we drop base table what about view created on base table ?


--------------------------
Views are not dropped but views cannot be queried

WITH SCHEMABINDING
------------------------
If view created with "SCHEMABINDING" then sql server will not allow users to drop
base table if any view exists on the base table

Rules
----------
1) '*' is not allowed in schema binding
2) tablename should be prefixed with schemaname

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

DROP TABLE DEPT ==> ERROR

SYNONYMS
---------------
1) A synonym is another name or alternative name for a table or view
2) If tablename/viewname is lengthy then we can give a simple and shortname to the
table/view called synonym and instead of using tablename we can use synonym name.

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

Ex: CREATE SYNONYM E FOR EMP

After creating synonym instead of using tablename we can use synonym name in
SELECT/INSERT/UPDATE/DELETE queries.
1) SELECT * FROM E
2) UPDATE E SET COMM=500 WHERE EMPNO=7369

Question
-----------------
CREATE SYNONYM E FOR EMP
SELECT * FROM EMP E'
SP_RENAME 'EMP','E'

Difference between synonym and alias


-------------------------
SNONYM ALIAS
1) Permanent Not permanent
2) Stored in db Not stored in db
3) Scope of the synonym Scope of the alias is upto the
query in which it is declared
is upto the schema

Display list of synonyms created by user?


----------------------------------
SELECT NAME, base_object_name FROM SYS.SYNONYMS

Droping Synonym
--------------
DROP SYNONYM E

SEQUENCES
--------
==> Sequence is also a db object created to generate sequence numbers
==> Sequence can use to auto increment column values.

Syntax
--------
CREATE SEQUENCE <NAME>
[START WITH <VALUE>]
[INCREMENT BY <VALUE>]
[MAXVALUE <VALUE>]
[MINVALUE <VALUE>]
[CYCLE/NOCYCLE]
[CACHE <SIZE>]

Example 1:
-------------
CREATE SEQUENCE S1
START WITH 1
INCREMENT BY 1
MAXVALUE 5

CREATE TABLE student


(
sid INT,
sname VARCHAR(10)
)

use above sequence s1 to generate values for sid?


----------------------------
INSERT INTO student VALUES(NEXT VALUE FOR S1,'A')
INSERT INTO student VALUES(NEXT VALUE FOR S1,'B')
INSERT INTO student VALUES(NEXT VALUE FOR S1,'C')
INSERT INTO student VALUES(NEXT VALUE FOR S1,'D')
INSERT INTO student VALUES(NEXT VALUE FOR S1,'E')
INSERT INTO student VALUES(NEXT VALUE FOR S1,'F')====> Error

Example 2: (calling sequence in update command)


---------------
CREATE SEQUENCE S2
START WITH 100
INCREMENT BY 1
MAXVALUE 999

Use above sequence to generate empno?


----------------------
UPDATE EMP SET EMPNO = NEXT VALUE FOR S2

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

CREATE TABLE INVOICE


(
INVNO VARCHAR(20)
INVDT DATETIME
)

CREATE SEQUENCE S3
START WITH 1
INCREMENT BY 1
MAXVALUE 9999

INSERT INTO INVOICE VALUES('NIT/' +


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

SELECT * FROM INVOICE

CYCLE/NOCYCLE
------------------
==> BY default sequence is created with NOCYCLE.
==> If sequence created with NOCYCLE then it starts from start with and generated
upto max and after reaching max then it stops.
==> If sequence create with CYCYLE then it starts from start with and generates
upto to max and after reaching max then it reset to min

CREATE SEQUENCE S5
START WITH 1
INCREMENT BY 1
MAXVALUE 5
MINVALUE 1
CYCLE
CACHE 4
Sql server preallocates 100 values in cache memory, so when we call 'next value for
seq' then sql server goes to cache memory and gets the value and return the value
from cache memory.
so no of requests going to db are reduced and performance is improved.

List of sequences created by user?


------------------------
SELECT * FROM INFORMATION_SCHEMA.SEQUENCES

How to change sequence parameters


---------------------------
ALTER SEQUENCE s3 MAX VALUE 100

How to reset sequence Manually


-------------------
ALTER SEQUENCE S1 RESTART WITH 1

Droping Sequence
----------------
DROP SEQUENCE S1

INDEXES
--------------
--> Index is also a db object created to improve the performance data accessing
--> Index improves performance of search operation
--> Index in db is similar to index in textbook. In textbook using index a
particular topic can be located fastly and in db using index a particular record
can be located fastly.
---> Indexes are created on columns and that column is called index key.

--> Indexes created on columns

1) that re frequently used in where clause


2) used in join operation

Types of Indexes
----------------
1) Non Clustered
simple
composite
unique

2) Clustered

Simple non clustered index


----------------------
If index created single cloumn then it is called simple index

Syntax: CREATE INDEX <NAME> ON <TABNAME> (COLNAME)

Ex: CREATE INDEX I1 ON EMP(SAL)

When we submit query to sql server it uses following 2 methods to locate the record

1) TABLE SCAN
2) INDEX SCAN

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

SELECT * FROM EMP (TABLE SCAN)


SELECT * FROM EMP WHERE ENAME='BLAKE' (TABLE SCAN)
SELECT * FROM EMP WHERE SAL=3000 (INDEX SCAN)
SELECT * FROM EMP WHERE SAL>=3000 (INDEX SCAN)
SELECT * FROM EMP WHERE SAL<=3000 (INDEX SCAN)

Composite Index
-----------------
If index created on multiple columns then it is called composite index

CREATE INDEX I2 on EMP(DEPTNO,JOB)

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

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

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


SELECT * FROM EMP WHERE DEPTNO=20 AND JOB ='CLERK' (INDEX SCAN)
SELECT * FROM EMP WHERE JOB='CLERK' (TABLE SCAN)

Note: Sql server uses above index when where condition based on leading column of
the index i.e deptno

UNIQUE INDEX
------------------
unique index doesnt allow duplicate values into the column on which index is
created

Ex: CREATE UNIQUE INDEX I3 ON EMP (ENAME)


K
G Q
ADAMS * JAMES * MARTIN * SCOTT *
ALLEN * JONES * MILLER * SMITH *
BLAKE *

SELECT * FROM EMP WHERE ENAME='BLAKE'


INSERT INTO EMP(EMPNO,ENAME,SAL)
VALUES(777,'BLAKE',4000)=====> Error

What are the different methods to enforce uniqueness?


-----------------------------------------
1) Decalre primary key/unique constraint
2) Create unique index
Note: primary key/unique columns are automatically indexed by sql server and it
created unique index on primary key / unique columns and unique index doesnt allow
duplicates so primary key/ uinque also doesnt allow duplicates.

Clustered Index
-----------------
A non cluster index stores pointers to actual records where as clustered index
stores actual records.

In non clustered index order of the records in table and order of the records in
index will not be same where as in clustered index order will be same

Example
----------
CREATE TABLE CUST
(
CID INT,
CNAME VARCHAR(10)
)

CREATE CLUSTERED INDEX I10 ON CUST(CID)

INSERT INTO CUST VALUES(10,'A')


INSERT INTO CUST VALUES(80,'B')
INSERT INTO CUST VALUES(40,'C')
INSERT INTO CUST VALUES(60,'D')

50
30 70
10 A 40 C 60 D 80 B

SELECT * FROM CUST ===> Sql server goes to clustered index and access records from
left to right

10 A
40 C
60 D
80 B

SELECT * FROM CUST WHERE CID=40

Note:
----------
--> only one clustered index allowed per table
--> by default sql server creates clustered index on primary key column

Difference between non clustered index & clustered indexes?


--------------------------------------------
Non Clustered Clustered
1) stores pointers to actual records stores actual records
2) order of the records in table and order order will be same
of the records in index may not be same
3) requires two lokkups to find desired record requires one look up to find
desired record
4) needs extra storage doesnt need extra storage
5) sql server allows 999 non clustred indexes only one clustered index
allowed per table
per table
6) created on non primary kry columns sql server implicitly creates
clustered index on primary key column

How to see list of indexes?


---------------------
SP_HELPINDEX <tabname>

Ex: SP_HELPINDEX EMP

Droping Index
----------------
DROP INDEX EMP.I1

If we drop table what about indexes created on table ?


Ans: indexes are also dropped

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

T SQL Programmming (Transact-sql)


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

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

2) supports conditional statements


-------------------------------
tsql supports conditional statements like if - then - else. So in tsql we can
execute sql commands based on conditions.

3) supports loops
--------------
tsql supports looping statements like while, using loops we can executes statements
repeatedly multiple times

4) supports error handling


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

5) supports reusability
---------
TSQL programs can be stored in db and applications which are connected to db can
reuse those programs

6) supports security
--------------
because these programs are stored in db so only authorized users can execute these
programs

TSQL blocks are 2 types

1) anonymous blocks
2) named blocks
strored procedures
stored functions
triggers

Anonymous blocks
-----------------
A TSQL block without name is called anonymous block

The following statements are used in tsql programming

1) DECLARE
2) SET
3) PRINT

DECLARE Statement
--------------------
Used to declare variables

DECLARE @varname datatype(size)

EX: DECLARE @x INT


DECLARE @s VARCHAR(10)
DECLARE @d DATE

DECLARE @x INT, DECLARE @s VARCHAR(10), DECLARE @d DATE

SET Statement
--------------
Used to assign value to variable

SET @varname=value

Ex: SET @x=100


SET @s='abc'
SET @d=GETDATE()

PRINT Statement
-------------
Used to print variable values or messages

PRINT 'hello'
PRINT @x

example 1:
-----------
DECALRE @a tinyint, @b tinyint, @c tinyint
SET @a=10
SET @b=20
SET @c=@a+@b
PRINT @c

example 2:
-------------
write a program to input and print day of the week?
----------------------
DECLARE @d DATE
SET @d='2023-01-01'
PRINT DATENAME(dw,@d)

output: sunday

DB Programming with TSQL


------------------------
To perform operations on db execute sql commands from tsql program and the
following commands can be executed from tsql program

1) DML(INSERT, UPDATE, DELETE, MERGE)


2) DRL(SELECT)
3) TCL(COMMIT, ROLLBACK, SAVETRANSACTION)

SELECT stmt syntax


------------
In TSQL, we get data from db table and copy that value into varibales declared in
tsql program

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

example
-------------
1) SELECT @s=ename FROM emp WHERE empno=7844
2) SELECT @n=ename, @s=sal FROM emp WHERE empno=7844

Write a program to input empno and print name & salary?


---------------------------
DECLARE @eno INT, @name VARCHAR(10), @sal MONEY
SET @eno=7844
SELECT @name=ename, @sal=sal FROM emp WHERE empno=@eno
PRINT @name + ' ' + CAST(@sal AS VARCHAR)

Write a program to input empno and print experience?


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

Write a program to input empno and print total salary


------------------------------------
total sal = sal+comm
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
--------

Write a program to input empno and increment sal by specific amount and after
increment if sal exceeds 5000 then cancel that increment?
--------------------------------
DECLARE @eno INT, @amt MONEY, @sal MONEY
SET @eno=107
SET @amt=2500
UPDATE EMP SET SAL=SAL+@amt WHERE EMPNO=@eno
SELECT @sal=SAL FROM EMP WHERE EMPNO=@eno
IF @sal>5000
ROLLBACK
ELSE
COMMIT

Write a program to input empno and increment salary as follows


--------------------------
if job=CLERK incr sal by 10%
SALESMAN 15%
MANAGER 20%
OTHERS 5%

DECLARE @eno INT, @job VARCHAR(10)


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

Write a program to process bank transaction(w/d)?


--------------------------
ACCOUNTS
ACCNO ACTTYPE BAL
100 S 10000
101 S 20000

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


SET @acno=100
SET @ttype='w'
SET @amt=1000
IF @ttype ='w'
BEGIN
SELECT @bal=bal FROM accounts WHERE accno=@acno
IF @amt > @bal
PRINT 'insufficient balance'
ELSE
UPDATE accounts SET bal=bal-@amt WHERE accno=@acno
END
ELSE IF @ttype='d'
UPDATE accounts SET bal=bal+@amt WHERE accno=@acno
ELSE
PRINT 'invalid transaction type'

Write a program to transfer amount from one account to another account


----------------------
DECLARE @sacno int, @tacno int, @amt money, @bal money
SET @sacno=100
SET @tacno=101
SET @amt=1000
SELECT @bal=bal FROM accounts WHERE accno=@sacno
IF @amt>@bal
PRINT 'insufficient balance'
ELSE
BEGIN
UPDATE accounts SET bal=bal-@amt WHERE accno=@sacno
UPDATE accounts SET bal=bal+@amt WHERE accno=@tacno
END

Using ROWCOUNT
-----------------------
DECLARE @sacno int, @tacno int, @amt money, @bal money
SET @sacno=100
SET @tacno=101
SET @amt=1000
SELECT @bal=bal FROM accounts WHERE accno=@sacno
IF @amt>@bal
PRINT 'insufficient balance'
ELSE
BEGIN
UPDATE accounts SET bal=bal-@amt WHERE accno=@sacno
SET @CNT1=@@ROWCOUNT
UPDATE accounts SET bal=bal+@amt WHERE accno=@tacno
SET @CNT2=@@ROWCOUNT
IF @CNT1=1 AND @CNT2=1
COMMIT
ELSE
ROLLBACK
END
Note:
--------
Every transaction must gurantee a peroperty called atomocity i.e all or none if
transaction contains multiple operations if all re successful then it must be
saved, if any of the operation fails then entire transaction must be cancelled

@@ROWCOUNT
----------------
It is a system variable that returns no of rows affected by dml
If DML is successful then it returns no of rows affected
If DML fails then returns 0

While Loop
--------------
Loops are used to execute statements repeatedly multiple times.

WHILE(COND)
BEGIN
Statements
END

if cond=true loop continues


if cond=false loop terminates

Write a program to print numbers from 1 to 20?


----------------------
DECLARE @x int=1
WHILE(@x<=20)
BEGIN
PRINT @X
SET @X=@X+1
END

Write a program to print 2023 calendar?


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

Write a program to print sundays between two given dates?


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

Same task other logic


------------------
DECALRE @d1 DATE , @d2 DATE
SET @d1='2023-01-01'
SET @d2='2023-12-31'
//to find first sunday
WHILE(DATENAME(dw,@d1)<>'sunday')
BEGIN
SET @d1=DATEADD(dd,1,@d1)
END
//to print sundays
WHILE(@d1<=@d2)
BEGIN
PRINT CAST(@d1 AS VARCHAR)+ ' '+ DATENAME(dw,@d1)
SET @d1=DATEADD(dd,1,@d1)
END

Cursors
-------------

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

Ex: CLOSE C1

Deallocating cursor
--------------------
DEALLOCATE <cursor-name>
Ex: DEALLOCATE C1

@@FETCH_STATUS
--------
It is a system variable that returns
0 ====> if fetch successful
-1====> if fetch unsuccessful

==> useful for loop condition


example
------------
write a program to print all the employees names and salaries?
-------------------
DECLARE C1 CURSOR FOR SELECT ename, sal FROM emp
DECLARE @name VARCHAR(10), @sal MONEY
OPEN C1
FETCH NEXT FROM C1 INTO @name, @sal
WHILE(@@FETCH_STATUS=0)
BEGIN
PRINT @name + ' ' +CAST(@sal AS VARCHAR)
FETCH NEXT FROM C1 INTO @name,@sal
END
CLOSE C1
DEALLOCATE C1

Write a program to calculate total sal without using sum?


------------------------------
DECLARE C1 CURSOR FOR SELECT sal FROM emp
DECLARE @sal MONEY, @total MONEY
OPEN C1
FETCH NEXT FROM C1 INTO @sal
WHILE(@@FETCH_STATUS=0)
BEGIN
SET @total=@total+@sal
FETCH NEXT FROM C1 INTO @sal
END
PRINT @total
CLOSE C1
DEALLOCATE C1
Write a program to print max salary without using max function
----------------------------
DECLARE C1 CURSOR FOR SELECT sal FROM emp
DECLARE @sal MONEY, @max MONEY=0
OPEN C1
FETCH NEXT FROM C1 INTO @sal
WHILE(@@FETCH_STATUS=0)
BEGIN
IF @sal>@max
SET @max=@sal
FETCH NEXT FROM C1 INTO @sal
END
PRINT @max
CLOSE C1
DEALLOCATE C1

Write a program to find minimum salary?

STUDENT
sno sname S1 S2 S3
1 A 80 90 70
2 B 70 60 30

RESULT
sno total avg result

Write a program to calculate all the students total, avg, result and insert into
result table
---------------------------
DECLARE C1 CURSOR FOR SELECT sno, s1,s2,s3 FROM student
DECLARE @sno int, @s1 int, @s2 int, @s3 int, @total int, @avg numeric(5,2)
DECLARE @res char(4)
OPEN C1
FETCH NEXT FROM C1 INTO @sno,@s1,@s2,@s3
WHILE(@@FETCH_STATUS=0)
BEGIN
SET @total=@s1+@s2+@s3
SET @avg=@total/3
IF @s1>=35 AND @s2>=35 AND @s3=35
SET @res='pass'
ELSE
SET @res='fail'
INSERT INTO RESULT VALUES(@sno,@total,@avg,@res)
FETCH NEXT FROM C1 INTO @sno,@s1,@s2,@s3
END
CLOSE C1
DEALLOCATE C1

SCROLLABLE CURSOR
-----------
==> By default cursor is forward only cursor and it supports forward navigation
but doesnt support backward navigation

==> If cursor declared with SCROLL then it is called scrollable cursor and it
supports both forward and backward navigation.

==> forward only cursor supports only FETCH NEXT statement

==> scrollable supports the following fetch statements

FETCH FIRST ===> fetches first record


FETCH NEXT ===> fetches next record
FETCH PRIOR ===> fetches previous record
FETCH LAST ===> fetches last record
FETCH ABSOLUTE N ===> fetches Nth record from first record
FETCH RELATIVE N ===> fetches Nth record from current record

Example
--------------
DECLARE C1 CURSOR SCROLL FOR SELECT ename FROM emp
DECLARE @ename VARCHAR(10)
OPEN C1
FETCH FIRST FROM C1 into @ename
PRINT @ename
FETCH ABSOLUTE 5 FROM C1 INTO @ename
PRINT @ename
FETCH RELATIVE 5 FROM C1 INTO @ename
PRINT @ename
FETCH LAST FROM C1 INTO @ename
PRINT @ename
FETCH PRIOR FROM C1 INTO @ename
PRINT @ename
CLOSE C1
DEALLOCATE C1
Write a program to print names from last to first?
--------------------------------
DECLARE C1 CURSOR SCROLL FOR SELECT ename FROM emp
DECLARE @ename VARCHAR(10)
OPEN C1
FETCH LAST FROM C1 INTO @ename
WHILE(@@FETCH_STATUS=0)
BEGIN
PRINT @ename
FETCH PRIOR FROM C1 INTO @ename
END
CLOSE C1
DEALLOCATE C1

Write a program to print every 5th record?


-----------------------
DECLARE C1 CURSOR SCROLL FOR SELECT ename FROM emp
DECLARE @ename VARCHAR(10)
OPEN C1
FETCH RELATIVE 5 FROM C1 INTO @ename
WHILE(@@FETCH_STATUS=0)
BEGIN
PRINT @ename
FETCH RELATIVE 5 FROM C1 INTO @ename
END
CLOSE C1
DEALLOCATE C1

Error Handling/Exception Handling


-------------------------------
1) Syntax Errors
2) Logical Errors
3) Runtime Errors

==> Erros that are raised during program execution are called runtime errors
Ex: DECLARE @x TINYINT
SET @x=1000 ==> runtime Error

==> If any statement causes runtime error then sql server displays error message
and contimues program execution

===> To replace system generated message with our own simple and user freindly
message then we need to handle that runtime error

BEGIN TRY
Statements ====> causes runtime error
END TRY
BEGIN CATCH
Statements ====> handles runtime error
END CATCH

Example
-------------------
DECLARE @a TINYINT, @b TINYINT, @c TINYINT
BEGIN TRY
SET @a=100
SET @b=2000
SET @c=@a/@b
PRINT @c
END TRY
BEGIN CATCH
PRINT 'runtime error'
END CATCH

output: runtime error

Error Handling Functions


-------------------
1) ERROR_NUMBER() ==> returns error number
2) ERROR_MESSAGE() ==> returns error message
3) ERROR_LINE() ==> returns error line number
4) ERROR_SEVERITY() ==> retunrs error severity level
5) ERROR_STATE() ==> returns error state

DECLARE @a TINYINT,@b TINYINT,@c TINYINT


BEGIN TRY
SET @a=100
SET @b=0
SET @c=@a/@b
PRINT @c
END TRY
BEGIN CATCH
IF ERROR_NUMBER()=8134
PRINT 'DIVISOR CANNOT BE ZERO'
ELSE IF ERROR_NUMBER()=220
PRINT 'VALUE EXCEEDING LIMIT'
END CATCH

=====>
CREATE TABLE emp88
(
empno int primary key,
ename varchar(10) not null,
sal money check(sal>-3000)
)

Write a program to insert data into emp88 table?


------------------------
DECLARE @eno int,@name varchar(10),@sal money
BEGIN TRY
SET @eno=101
SET @name='klm'
SET @sal=1000
INSERT INTO emp88 VALUES(@eno,@name,@sal)
END TRY
BEGIN CATCH
IF ERROR_NUMBER()=2627
PRINT 'empno should not be duplicate'
ELSE IF ERROR_NUMBER()=515
PRINT 'name should not be null'
ELSE IF ERROR_NUMBER()=547
PRINT 'sal>=3000'
END CATCH

user defined errors


------------------
==> errors raised by user are called user defined errors
==> when predefine errors not meeting your requirements then we define our own
errors called user defined errors
==> these errors raised by user by using RAISEERROR procedure
RAISEERROR(error mesg,severity level,state)

severity level ==> can be between 0 and 25


represents the seriousness of the error

0-10 informational messages


11-18 Errors
19-25 fatal errors

state ==> between 00 through 255. If you raise the same user defined error at
multiple locations, you can use a unique state number for each location to make it
easier to find which section of the code is causing the errors.

Write a program to increment specific employee sal by specific amount but sunday
updates are not allowed
------------------
DECLARE @eno int,@amt money
SET @eno=7369
SET @amt=1000
IF datename(dw,GETDATE())='sunday'
RAISEERROR('sunday not allowed',15,1)
ELSE
UPDATE emp SET sal=sal+@amt WHERE empno=@eno

Display list of errors?


-------------
SELECT * FROM SYS.MESSAGES

SUB-PROGRAMS(Named TSQL Blocks)


-------------------
1) STORED PROCEDURES
2) STORED FUNCTIONS

Advantages
------------------

1) Modular Programming
-----------------
with the help of procedures and function a big tsql program can be divided into
small modules

2) reusability
------------
beacuse these programs are 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

4) invoked from front end applications


--------------------------
these programs can be called front end applications like java/.net /python
5) improves performance
-------------------
procedures/functions improves performance because they are precompiled i.e compiled
already and ready for execution . If we create a procedure program is compiled and
stored in db and whenever we call procedure only execution is repeated

STORED PROCEDURES
--------------------------
A procedure is a named TSQL bloack that aceepts some input perfroms some action on
db and may or may not returns a value

procedures are created to perform one or more dml operations on db

Syntax
--------------
CREATE OR ALTER PROCEDURE <name>
parameters if any
AS
STATEMENTS

Parameters
----------
We can declare parameters and we can pass valyes to parameters
parameters are 2 types

1) INPUT
2) OUTPUT

INPUT parameters always receives value


OUPUT parameter always send value

Ex 1: (procedure without parameters)

create a procedure to increment all the employee salaries by 1000?


---------------------
CREATE OR ALTER PROCEDURE RAISE_SALARY
AS
UPDATE emp SET sal=sal+1000

procedure created (compiled + stored in db)

execution
-----------
execute raise_salary

create a procedure to increment specific employee sal by specific amount?


------------------------------------------
CREATE OR ALTER PROCEDURE RAISE_SALARY
(
@eno INT,
@amt MONEY
)
AS
UPDATE emp SET sal=sal+@amt WHERE empno=@eno

execution
---------------
1) EXECUTE raise_salary 100,1000 (positional association)
2) EXECUTE raise_salary @eno=100, @amt=1000 (named association)
3) EXECUTE raise_salary @amt=1000, @eno=100

example 3:
------------------
Procedure with output parameter

Create procedure to increment specific employee sal by specific amount after


increment send the updated sal to calling program?

CREATE OR ALTER PROCEDURE RAISE_SALARY


(
@eno INT,
@amt MONEY,
@newsal MONEY
)
AS
UPDATE emp SET sal=sal+@amt WHERE empno=@eno
SELECT @newsal=sal FROM emp WHERE empno=@eno

Execution
----------------
declare @sal money
execute raise_salary @eno=100, @amt=1000, @newsal=@sal ouput
print @sal

Example 4
-------------------
ACCOUNTS
ACCNO ACTYPE BAL
100 S 10000
101 S 20000

create a procedure for money withdrawl?


----------------------
CREATE OR ALTER PROCEDURE DEBIT
(
@acno INT,
@amt MONEY,
@newbal MONEY OUTPUT
)
AS
DECLARE @bal MONEY
SELECT @bal=bal FROM accounts WHERE accno=@acno
IF @amt>@bal
RAISEERROR('insufficient balance',15,1)
ELSE
BEGIN
UPDATE accounts SET bal=bal-@amt WHERE accno=@acno
SELECT @bal=bal FROM accounts WHERE accno=@acno
END

Execution
---------------
declare @b money
execute debit @acno=100, @amt=1000, @newbal=@b output
print @b
create procedure for money deposit
create procedure for money transfer

User Define Functions


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

Functions are 2 types

1) Scalar Valued
2) Table Valued

Scalar Valued Functions


-----------------------
These functions returns one value
Return type must be scalar type
Return expression must be scalar varaible.

Syntax
---------------------
CREATE OR ALTER
FUNCTION <NAME>(paramters if any) RETURNS <type>
AS
BEGIN
statements
RETURN <expression>
END

Example 1
-----------
CREATE OR ALTER
FUNCTION CALC(@a INT,@b INT,@op CHAR(1)) RETURNS INT
AS
BEGIN
DECLARE @c INT
IF @op='+'
SET @c=@a+@b
ELSEIF @op='-'
SET @c=@a-@b
ELSEIF @op='*'
SET @c=@a*@b
ELSEIF @op='/'
SET @c=@a/@b
RETURN @c

Execution
---------------
1) Sql commands
2) another program
3) front end applications

Executing form sql commands


-----------------------
SELECT DBO.CALC(10,20,'*') ===> 200

Example 2
----------------
create a function that accepts deptno and returns employee names working for that
dept sepearated by ','

input deptno:- 20
output:- smith, jones, scott, adams, ford

CREATE OR ALTER
FUNCTION getNames(@d INT) RETURNS VARCHAR(1000)
AS
BEGIN
DECLARE C1 CURSOR FOR SELECT ename FROM emp WHERE deptno=@d
DECLARE @name VARCHAR(10),@s VARCHAR(500)
OPEN C1
FETCH NEXT FROM C1 INTO @name
WHILE(@@FETCH_STATUS=0)
BEGIN
SET @s=@s+@name+','
FETCH NEXT FROM C1 INTO @name
END
CLOSE C1
DEALLOCATE C1
RETURN @s

STRING_AGG
-------------
It is a predefine function used to concatenate column values

STRING_AGG(colname,separator)

SELECT deptno,STRING_AGG(ename,',') as names


FROM emp
GROUP BY deptno

Table valued functions


------------------------
These functions returns records
Return type of these function must be table
return expression must be SELECT statement
table valued functions allows only one statment that must be return statement

CREATE OR ALTER
FUNCTION <NAME>(parameters) RETURNS TABLE
AS
RETURN (SELECT STATEMENT)

Example
-------------
Create a function that aceepts deptno and returns list of employees working for
that dept?
-------------------------------
CREATE OR ALTER
FUNCTION getEmpList(@d INT) RETURNS TABLE
AS
RETURN (SELECT * FROM EMP WHERE DEPTNO=@d)

Execution
----------------
Table valued functions are invoked in from clause
SELECT * FROM DBO.getEmpList(20)

Example 2
-----------
Create a function that returns top N employee list based on sal?
------------------
CREATE OR ALTER
FUNCTION getTopNEmpList(@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
----------------
Select * from dbo.getTopNEmpList(3)

Difference between procedures and functions?


--------------------------------
Procedures
----------------
May or may not returns a value
can return multiple values
returns values using OUTPUT parameter
procedure can contain dml statements
cannot be called from sql commands
procedures are created to perform one or more operations like insert, update,
delete

Functions
--------------
Must return a value
Always returns one value
Returns value using return statement
functions cannot contain dml statements
can be called from sql commands
created for calculation or fetch data from the table

sp_helptext
----------------
stored procedure used to see the procedure or function code

sp_helptext <proc-name>

ex:- sp_helptext debit

TRIGGERS
-------------
trigger is also a named TSQL block like procedure but executed implicitly by sql
server whenever user submits DML commands

triggers are created

1) to control dmls
2) to enforce complex rules and validations
3) to audit day to day operations on tables
4) to manage replicas(duplicate copy)
5) to generate values for primary key columns

Syntax
------------
CREATE OR ALTER TRIGGER <NAME>
ON <TABNAME>
AFTER/INSTEAD OF INSERT, UODATE, DELETE
AS
STATEMENTS

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

Example 1
--------------
Create a trigger to not allow dmls on sunday on emp table
------------------------
CREATE OR ALTER TRIGGER T1
ON EMP
AFTER INSERT, UPDATE, DELETE
AS
IF DATENAME(DW,GETDATE())='SUNDAY'
BEGIN
ROLLBACK
RAISERROR('sunday not allowed',15,1)

END

Testing
-----------
UPDATE EMP SET SAL=SAL+1000 WHERE EMPNO=110

You might also like