BSQL 7 PM
BSQL 7 PM
-----------
Data :
------
Data is nothing but a collection of facts & figures .
Ex:
---
list of customers,student marks.......
information :
-------------
an information is processed data.
or
(converting un-organized data into organized format is called information.)
Which is Collected Together and Stored in Separate Place for Future
Analysis/Reporting Purpose.
Ex :
invoice of customer,marks sheet...
Database:
---------
DataBase is a collection of related data.That related data is organised,so that it
can be easily Accessed,Managed and Updated.
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
In Older Days---> Record Books -------> It is not possible to store the data
for longer peiod
In Later Days ---> Flat File like (Excel,csv,Google Sheet)--->It is not possible
to store the huge volumes of data
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
Types of DataBase SoftWare Systems
----------------------------------
1.DBMS
2.RDBMS
DBMS is Software Which is used to store the DATA and allows the users to
define,create ,maintain and control the access to the DataBase
Note : In DBMS Software it is not Possible to create the Relationships B/W the Two
tables
RDBMS is a Software which is used to Store the Data and Allows the Users to
Define,create,Maintain and Control the Access to the DataBase
Note : In RDBMS Software it is Possible to create the Relationships B/W the Two
tables
in rdbms data stored in multiple tables,each table have set of columns and
rows
SQL databases :-
NoSQL databases :-
MongoDB
cassandra
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
=> SQL SERVER is a rdbms (relational database management system) product from
microsoft which is used to create and to manage database.
Development Administration
SOFTWARES
SQL SERVER 2012 / 2014 / 2016 / 2017 / 2019 EE EDITION / DEVLOPER EDITION
SQL SERVER MANAGEMENT STUDIO [SSMS]
EDITIONS
ENTERPRISE EDITION, ENTERPRISE EVALUATION EDITION
DEVLOPER EDITION
BI EDITION, WEB EDITION
EXPRESS EDITION
version year
1 polybase
2 json
3 temporal table to save data changes.
4 dynamic data masking and row level security
1 identity cache
2 New String functions
3 Automatic Tuning
AUTHENTICATION : A COMMUNICATION PATH B/W SQL SERVER APPLICATION AND END USERS
CONNECT
NOTE : DURING INSTALLATION, A SET OF FIVE SYSTEM DATABASES ARE AUTO CREATED
1. MASTER
CONTROLS USER CONNECTIONS TO THE SERVER
2. MODEL
THIS DATABASE IS LIKE TEMPLATE FOR NEW DATABASES WHICH WE CREATE ON SERVER
3. MSDB
THIS DATABASE IS USED BY DBAs FOR REPAIRS, AUDITS, TROUBLESHOOTING, JOBS,
EMAILS ETC
4. TEMPDB
THIS DATABASE IS USED BY DEVLOPERS FOR QUERY OPERATIONS AND TEMPORARY DATA
STORAGE
5. RESOURCES
HIDDEN. READ-ONLY DATABASE
CONTROLS ALL ABOVE DATABASES
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
client/server architecture :-
-----------------------------
1 SERVER
2 CLIENT
SERVER :-
----------
=> server is a system where sql server software is installed and running
=> inside the server sql server manages databases
=> sql server recieves requests from client and process the requests
CLIENT :-
-------
1 connects to server
2 submit requests to server
3 recieves response from server
client tool :-
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
SQL
SQL------->Structured Query Language or sequel
=> user communicates with sql server by sending commands called queries.
=> a query is a command / instruction submitted to sql server to perform some
operation over db
SQL software will acts as a Backend Tool which is used to develop the Backend
Applications and to store the datain the form of Table
SQL is originally introduced by IBM and initial name of this lang was SEQUEL
and later it is renamed to SQL.
MS SQL Server
T-SQL
SQL server can be either installed on your computer with windows or linux os
=> to connect to sql server open SSMS and enter following details
server type :- db engine
server name :- WINCTRL-F9B3VH5\SQLEXPRESS
authentication :- sql server authentication
login :- SA (system admin)
password :- 123
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
Used to enter new data/ changing old data / deleting the data
from table.
GRANT REVOKE
SQL
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
CREATE DATABASE:
---------------
The CREATE DATABASE statement is used to create a new SQL database.
Tip: Make sure you have admin privilege before creating any database.
Once a database is created, you can check it in the list of databases with the
following SQL command: SHOW DATABASES;
Through Graphical
-----------------
1.First Connect To server
2.in object explorer select Databases,Right Click On Databases
3.Select New DataBase and give your DataBase Name
Enter Database Name :- DB7PM
4.Click On Ok.
=> Data File stores data and Log file stores operations
Drop Database:
--------------
The DROP DATABASE statement is used to drop an existing SQL database.
Note:we can select another database to drop curent Database.same database is not
possible.
Syntax:
----------
DROP DATABASE databasename;
Example:
-------------
DROP DATABASE testDB;
DROP DATABASE testDB1,testDB2,testDB3;
Syntax1:
alter database Old_database_name
modify name=New_Database_Name;
Example:
alter database database1
modify name=sampledb;
Syntax:
-------
BACKUP DATABASE databasename
TO DISK = 'filepath';
Example:
-------
BACKUP DATABASE testDB
TO DISK = 'D:\backups\testDB.bak';
Syntax:
----------
BACKUP DATABASE databasename
TO DISK = 'filepath'
WITH DIFFERENTIAL;
Tip: Always back up the database to a different drive than the actual database.
Then, if you get a disk crash, you will not lose your backup file along with the
database.
Example:
-------------
BACKUP DATABASE testDB
TO DISK = 'D:\backups\testDB.bak'
WITH DIFFERENTIAL;
Tip: A differential back up reduces the back up time (since only the changes are
backed up).
-------------------------------------------------------------
****************************-------------------------------------------------------
------------
DATATYPES
CHAR INTEGER FLOAT CURRENCY DATE
BINARY
char(size) :-
-------------
EX :- NAME CHAR(10)
SACHIN----
wasted
RAVI------
wasted
=> in char datatype extra bytes are wasted , so char is not recommended for
variable
length fields and it is recommended for fixed length fields.
STATE_CODE CHAR(2)
AP
TS
MH
UP
COUNTRY_CODE CHAR(3)
IND
USA
VARCHAR(SIZE) :-
-----------------
ex :- NAME VARCHAR(10)
SACHIN----
released
RAVI------
released
=> in varchar extra bytes are releases so varchar is recommended for variable
length fields
VARCHAR(MAX) :-
---------------
PANNO CHAR(10)
PASSWORD VARCHAR(12)
EMAILID VARCHAR(20)
NCHAR/NVARCHAR/NVARCHAR(MAX) :-
--------------------------------
=> allows unicode characters (65536 chars) that includes ascii chars & characters
belongs to different languages.
Integer Types :-
-----------------
=> integer types allows exact numbers i.e. numbers without decimal places
ex :- AGE TINYINT
EMPID SMALLINT
AADHARNO BIGINT
DECIMAL(P,S) :-
ex :- SALARY DECIMAL(7,2)
5000
5000.50
50000.50
500000.50 => not accepted
CURRENCY TYPES :-
-----------------
EX :- SALARY SMALLMONEY
BALANCE MONEY
ex :- DOB DATE
1995-10-15
LOGIN TIME
10:00:00
TXNDATE DATETIME
2021-07-24 11:00:00
BINARY TYPES :-
---------------
binary
varbinary
varbinary(max)
binary :-
----------
ex :- PHOTO BINARY(5000)
varbinary :-
------------
ex :- PHOTO VARBINARY(5000)
varbinary(MAX) :-
-----------------
create
alter
drop
truncate
=> DDL commands acts on table structure that includes columns,datatype and size
Through Graphical
-----------------
1.First Connect To server
2.Select your Databases
3.Expand your Database
4.right click on table and select New
5.select Table
6.Enter Coloumns Names and Data Types
7.Click On Save and it will Ask Table Name and enter Table Name
4.Click On Ok.
Through Command:
---------------
First select your DataBase.
Click On New Query
Syntax:
)
Rules :-
---------
emp123 valid
123emp invalid
emp 123 invalid
emp*123 invalid
emp_123 valid
Example :-
EMP
EMPID ENAME JOB SAL AGE HIREDATE
=> above command creates table structure that includes columns,datatype & size
Ex :- SP_HELP EMP
EMPID smallint no 2
ENAME varchar no 10
JOB varchar no 10
SAL smallmoney no 4
AGE tinyint no 1
HIREDATE date no 3
ALTER command :-
----------------
1 add column
2 drop column
3 modify a column
1 changing size
2 changing datatype
Adding a column :-
------------------
To add a column in a table, use the following
Syntax:
-------
ALTER TABLE table_name
ADD column_name datatype;
NOTE :- after adding column ,by default the new column is filled with NULLs , so
to insert data into this new column use update command.
Droping column :-
----------------
To delete a column in a table
Syntax:
ALTER TABLE table_name
DROP COLUMN column_name;
Modifyig a column :-
--------------------
To change the data type of a column in a table
syntax:
ALTER TABLE table_name
ALTER COLUMN column_name datatype;
syn:
alter table <table_name>
RENAME TO <new table name>;
DROP command :-
------------------
TRUNCATE command :-
-------------------
=> deletes all the data from table but keeps structure.
=> will empty the table.
=> it cannot deletes the partial data from a table.
=> Here the deletion is permanent .
=> we cannot get back deleted data.
=> releases memory allocated for table.
=> when we issue truncate command sql server goes to db and releases all the pages
allocated for table , when pages are released , data stored in pages are also
deleted.
DELETE VS TRUNCATE :-
---------------------
DELETE TRUNCATE
3 where cond can be used with delete where cond cannot be used with
truncate
4 deletes row-by-row deletes all rows at a time
5 slower faster
SP_RENAME :-
SP_RENAME 'EMP','EMPLOYEES'
SP_RENAME 'EMPLOYEES.COMM','BONUS'
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-
INSERT
UPDATE
DELETE
MERGE
DDL DML
SET IMPLICIT_TRANSACTIONS ON
=> after executing above command every operation should be explicitly saved.
=> to save the operation execute COMMIT command
=> to cancel the operation execute ROLLBACK command.
inserting nulls :-
-------------------
method 1 :-
method 2 :-
Displaying Data :-
------------------
SQL = ENGLISH
queries = sentences
clauses = words
UPDATE command :-
-----------------
=>update employees comm to 500 and sal to 50000 whose empno to 4584
=> increment sal by 20% and comm by 10% those working as salesman and joined in
1981 year ?
UPDATE emp
SET sal=sal+(sal*20/100),comm=comm+(comm*10/100)
WHERE job='SALESMAN'
AND
hiredate LIKE '1981%'
DELETE command :-
------------------
--------------------------------------------------------------
****************************************-------------------------------------------
--------------------
WHERE clause :-
----------------
=>The Where clause is used to filter the Records.
=> used to get specific row/rows from table based on a condition
Syntax:
SELECT columns
FROM tabname
WHERE condition
condition :-
Note:
1.for text values required single Quotes
2.for numeric values should not be in Quotes
OPERATOR must be any relational operator like > >= < <= = <>
compound condition :-
---------------------
=> display employees working as clerk and earning more than 5000 ?
scenario :-
STUDENT
SNO SNAME S1 S2 S3
1 A 80 90 70
2 B 30 60 50
IN operator :-
---------------
BETWEEN OPERATOR :-
-------------------
=> use BETWEEN for range comparision
10,20,30,40,50 LIST
1O TO 50 RANGE
SELECT * FROM emp WHERE hiredate NOT BETWEEN '2021-01-01' AND '2021-12-31'
scenario :-
TRANSACTIONS
TRID TTYPE TDATE TAMT ACCNO
1 W 28- 2000 100
2 D 29- 1000 101
SELECT *
FROM TRANSACTIONS
WHERE TDATE BETWEEN GETDATE()-7 AND GETDATE()
AND
ACCNO=100
Question :-
A ERROR
B RETURNS NO ROWS
C RETURN ROWS
D NONE
ANS :- B
NOTE :- use BETWEEN operator with lower and upper but not with upper and lower
=> display employees working as clerk,manager and earing between 5000 and 10000
and age between 30 and 40 and joined in 2021 year
SELECT *
FROM emp
WHERE job IN ('clerk','manager')
AND
sal BETWEEN 5000 AND 10000
AND
age BETWEEN 30 AND 40
AND
hiredate BETWEEN '2021-01-01' AND '2021-12-31'
scenario :-
PRODUCTS
prodid pname price category brand
=> display mobiles price between 10000 and 20000 and brand =
samsung,realme,redmi ?
SELECT *
FROM products
WHERE category='mobiles'
AND
price between 10000 and 20000
AND
brand IN ('samsung','redmi','realme')
2
CUSTOMERS
cid name addr gender age city state
SELECT *
FROM customers
WHERE gender='male'
AND
city in ('hyd','del','mum','blr')
AND
age BETWEEN 25 AND 40
LIKE operator :-
-----------------
=> display employee list where 'a' is 3rd char in their name ?
=> display employee list where 'a' is 3rd char from last ?
yyyy-mm-dd
Question :-
A ERROR
B RETURNS ONLY CLERK RECORDS
C RETURNS CLERK & MANAGER RECORDS
D NONE
ANS :- B
ANS :- C
IS operator :-
--------------
IS NULL : This Operator is used to Test for NULL values(whether column having Null
values or Not)
summary :-
-------------------------------------------------------------
***************************************--------------------------------------------
----------------------
ORDER BY clause :-
------------------
=> ORDER BY clause is used to sort data based on one or more columns either in
ascending order or in descending order.
Examples :-
SELECT *
FROM emp
ORDER BY sal DESC
1 A 3000 5 E 6000
2 B 2000 3 C 5000
3 C 5000 -----------> 4 D 4000
4 D 4000 1 A 3000
5 E 6000 2 B 2000
NOTE :-
SELECT *
FROM emp
ORDER BY 6 DESC
=> ORDER BY number should not be based on table , it should be based on select
list
SELECT empno,ename,hiredate,sal,deptno
FROM emp
ORDER BY 6 DESC => ERROR
SELECT empno,ename,hiredate,sal,deptno
FROM emp
ORDER BY 4 DESC
=> above query sorts based on 4th column in select list i.e. sal.
=> arrange employee list dept wise asc and with in dept sal wise desc ?
SELECT empno,ename,hiredate,sal,deptno
FROM emp
ORDER BY 5 ASC,4 DESC
1 A 3000 20 5 E 7000 10
2 B 4000 10 2 B 4000 10
3 C 6000 30 ----------> 4 D 5000 20
4 D 5000 20 1 A 3000 20
5 E 7000 10 3 C 6000 30
6 F 5000 30 6 F 5000 30
scenario :-
STUDENTS
SID SNAME M P C
1 A 80 90 70
2 B 60 50 70
3 C 90 80 70
4 D 90 70 80
=> arrange student list total marks wise desc ,m desc,p desc ?
SELECT *
FROM student
ORDER BY (M+P+C) DESC,M DESC,P DESC
3 C 90 80 70
4 D 90 70 80
1 A 80 90 70
2 B 60 50 70
=> display employees working as clerk,manager and arrange output sal wise desc
order ?
SELECT empno,ename,job,sal
FROM emp
WHERE job IN ('clerk','manager')
ORDER BY 4 DESC
FROM emp :-
1 A 5000 MANAGER
2 B 3000 CLERK
4 D 3000 CLERK
5 E 8000 MANAGER
ORDER BY 4 DESC :-
5 E 8000 MANAGER
1 A 5000 MANAGER
2 B 3000 CLERK
4 D 3000 CLERK
--------------------------------------------------------------
*********************************--------------------------------------------------
-------------------
GROUP BY clause :-
------------------
=> GROUP BY clause is used to group rows based on one or more columns to calculate
min,max,sum,avg,count for each group
EMP
EMPNO ENAME SAL DEPTNO
1 A 5000 10 10 13000
2 B 6000 20 ----------GROUP BY-------------> 20 15000
3 C 7000 30 30 7000
4 D 8000 10
5 E 9000 20
=> GROUP BY clause converts detailed into summarized data which is useful for
analysis
syntax :-
SELECT columns
FROM tabname
[WHERE cond]
GROUP BY <column>
[HAVING <cond>]
[ORDER BY <col> ASC/DESC]
Execution :-
FROM
WHERE
GROUP BY
HAVING
SELECT
ORDER BY
SELECT deptno,SUM(sal)
FROM emp
GROUP BY deptno
FROM emp :-
GROUP BY deptno :-
10
1 A 5000
4 D 8000
20
2 B 6000
5 E 9000
30
3 C 7000
SELECT deptno,SUM(sal) :-
10 13000
20 15000
30 7000
SELECT job,COUNT(*)
FROM emp
GROUP BY job
SELECT deptno,COUNT(*)
FROM emp
WHERE COUNT(*) > 4
GROUP BY deptno => ERROR
=> sql server calculates dept wise count after group by and it cannot calculate
before group by so apply the condition COUNT(*) > 4 after group by using
having clause.
16-aug-21
SELECT job,COUNT(*)
FROM emp
WHERE job IN ('CLERK','MANAGER')
GROUP BY job
HAVING COUNT(*)>3
WHERE VS HAVING :-
------------------
WHERE HAVING
=> display dept wise and with in dept job wise total salaries ?
SELECT deptno,job,SUM(sal)
FROM emp
GROUP BY deptno,job
ORDER BY 1 ASC
10 CLERK 1300
MANAGER 2500
PRESIDENT 5000
20 ANALYST 6000
CLERK 1900
MANAGER 3000
30 CLERK 1000
MANAGER 2900
SALESMAN 5700
Assignment :-
=> display year wise and with in year quarter wise no of employees joined ?
----------------------------------------------------------
******************************************-----------------------------------------
------------------------
Integrity Constraints
----------------------
=> Integrity Constraints are the rules to maintain data integrity i.e. data
quality.
=> Integrity Constraints are used to prevent users from entering invalid data.
=> Integrity Constraints are used to enforce rules like min sal must be 3000.
=> different integrity constraints in sql server
1 NOT NULL
2 UNIQUE
3 PRIMARY KEY
4 CHECK
5 FOREIGN KEY
6 DEFAULT
=> above constraints can be declared in two ways
1 column level
2 table level
column level :-
---------------
NOT NULL :-
-----------
ex :-
Testing :-
---------
UNIQUE :-
-------
ex :-
Testing :-
-----------
PRIMARY KEY :-
-------------
=> table may contains no of columns but one column should be used to uniquely
identify
the records in table and that column should be declared with primary key.
Ex :-
Testing :-
=> PRIMARY KEY column can be used to uniquely identify the records.
=> only one primary key is allowed per table , if we want two primary keys then
declare one column with primary key and another columns with unique & not null.
19-aug-21
CHECK constraint :-
-------------------
ex :- CHECK(condition)
FOREIGN KEY :-
---------------
PROJECTS
projid name duration cost client
100 A 5 YEARS 100 TATA MOTORS
101 B 3 YEARS 80 DBS
102 C 4 YEARS 120 L&T INFRA
EMP
EMPID ENAME SAL PROJID REFERENCES PROJECTS(PROJID)
1 A 5000 100
2 B 4000 101
3 C 6000 100
4 D 4000 999 => NOT ACCEPTED
5 E 3000 NULL => ACCEPTED
=> values entered in foreign key column should match with values entered in pk
column.
=> foreign key allows duplicates and nulls.
=> after declaring foreign key a relationship is established between two tables
called parent/child relationship.
=> pk table is parent and fk table is child.
=> by default sql server creates one to many (1:m) relationship between two tables,
to establish one to one (1:1) relationship declare foreign key with unique
constraint.
CREATE TABLE projects
(
projid int PRIMARY KEY,
pname VARCHAR(10),
duration VARCHAR(10)
)
Assignment :-
ACCOUNTS
ACCNO ACTYPE BAL
rules :-
TRANSACTIONS
TRID TTYPE TDATE TAMT ACCNO
rules :-
PROJECTS
projid name client
100
101
102
MANAGER
MGRNO MNAME PROJID
1 A 100
2 B 101
3 C 102
=> in the above example one project is managed by one manager and one manager
manages
one project so the relationship between two tables is one to one.
DEFAULT :-
-----------
=> while inserting if we skip hiredate then sql server inserts default value.
empno hiredate
100 2021-08-20
101 2021-01-01
102 null
TABLE LEVEL :-
--------------
=> if constraints are declared after declaring all columns then it is called table
level
=> use table level to declare constraints for multiple columns or combination of
columns
products
prodid pname mfd_dt exp_dt
100 A 2021-08-20 2021-01-01 => INVALID
21-aug-21
=> if combination of columns uniquely identifies the records then that combination
should be declared as primary key , if combination of columns declared primary
key
then it is called composite primary key.
Example :-
ORDERS PRODUCTS
ORDID ORD_DT DEL_DT CID PRODID PNAME PRICE
1000 100 A 1000
1001 101 B 2000
1002 102 C 3000
=> to establish relationship (m:n) between orders & products then create third
table
in third table take primary keys of both tables as foreign keys
ORDER_DETAILS
ORDID PRODID QTY
1000 100 1
1000 101 1
1001 100 1
1001 101 1
=> in the above table ordid + prodid combination uniquely identifies the records so
declare this combination as primary key at table level.
A UNIQUE
B CHECK
C PRIMARY KEY
D NOT NULL
E FOREIGN KEY
ANS :- D
23-aug-21
=> we cannot add primary key to nullable column , to add pk first change the column
to not null then add primary key.
=> while adding constraint sql server also validates existing data. The above
command
returns error because in table some of the employee salaries are less than 3000
so constraint cannot be added.
WITH NOCHECK :-
---------------
=> if constraint is added with "WITH NOCHECK" option then sql server will not
validate
existing data it validates only new data.
=> add foreign key to dno that should refer dept table primary key i.e. deptno
Droping constraints :-
-----------------------
NOTE :-
DELETE RULES :-
----------------
ON DELETE NO ACTION :-
----------------------
scenario :-
ACCOUNTS
ACCNO ACTYPE BAL
100
101
LOANS
ID TYPE AMT ACCNO
1 H 30 100
2 C 10 100
ON DELETE CASCADE :-
--------------------
=> if parent row is deleted then it is deleted along with child rows.
scenario :-
ACCOUNTS
ACCNO ACTYPE BAL
100
101
TRANSACTIONS
TRID TTYPE TDATE TAMT ACCNO
1 100
2 100
RULE :- after closing account along with account delete transactions also
=> parent row can be deleted without deleting child rows but fk will be set to
null
eno dno
1 NULL
2 NULL
scenario :-
PROJECTS
projid name duration
100
101
102
EMP
empid ename projid
1 100
2 101
3 102
=> parent row can be deleted without deleting child rows but fk will be set to
default
eno dno
1 20
2 20
------------------------------------------------------------
***********************************************------------------------------------
-----------------------
Aliases:
--------
1.Aliases are used to give a Table or a Column in a Table,a Temporary Name.
2.An aliases only exist for the Duration of That Query.
3.An Aliases is Created with the 'AS' Keyword.
Aliases Column :
---------------
Syntax:
Select Column_name AS Aliases_Name from table_name.
Ex:
select CID as ID from Customer.
select CID as ID,CName as Name from Customer.
Aliases TAble:
--------------
Syntax:
select Column_Name(s) from Table_Name AS Aliases_Name
EX:
Select o.rderid,c.CustomerName from order as o,customer as c.
-----------------------------------------------------------
****************************************************-------------------------------
------------------------
Coalesce():
-----------
it returns the first non-Null Values
------------------------------------------------------------
******************************************************-----------------------------
------------------------
24-aug-21 JOINS
-----
=> join is an operation performed to fetch data from two or more tables. -To fetch
data from two tables we need to join those two tables.
=> in DB tables are normalized i.e. related data stored in multiple tables , to
gather
or to combine data stored in multiple tables we need to join those tables.
Example :-
ORDERS CUSTOMERS
ordid ord_dt del_dt cid cid cname caddr
1000 10- 20- 10 10 a hyd
1001 11- 21- 11 11 b hyd
output :-
Types of joins :-
-----------------
Equi Join :-
------------
=> to perform equi join between the tables there must be a common field and name
of
the common field need not to be same and pk-fk relationship is not compulsory.
=> equi join is performed between the tables sharing common field with same
datatype.
SELECT columns
FROM tabname
WHERE join condition
join condition :-
-----------------
=> based on the given join condition sql server joins the records of two tables.
=> join condition decides which record of 1st table should be joined with which
record
of second table.
table1.commonfield = table2.commonfield
=> this join is equi join because here join condition based on "=" operator
Example :-
EMP DEPT
EMPNO ENAME SAL DEPTNO DEPTNO DNAME LOC
7369 smith 920.00 20 10 ACCOUNTS NEW YORK
7499 allen 1920.00 30 20 RESEARCH
7521 ward 1500.00 30 30 SALES
7566 jones 3421.25 20 40 OPERATIONS
7654 martin 1500.00 30
7698 blake 3420.00 30
7782 clark 2695.00 10
SELECT empno,ename,sal,dname,loc
FROM emp,dept
WHERE emp.deptno = dept.deptno
SELECT empno,ename,sal,
deptno,dname,loc
FROM emp,dept
WHERE emp.deptno = dept.deptno => ERROR
=> in join queries declare table alias and prefix column names with table alias for
two reasons
1 to avoid ambiguity
2 for faster execution
SELECT e.empno,e.ename,e.sal,
d.deptno,d.dname,d.loc
FROM emp as e,dept as d
WHERE e.deptno = d.deptno
25-aug-21
=> display employee details with dept details working at NEW YORK loc ?
SELECT e.empno,e.ename,e.sal,
d.deptno,d.dname,d.loc
FROM emp as e,dept as d
WHERE e.deptno = d.deptno /* join cond */
AND
d.loc='NEW YORK' /* fiter cond */
SELECT columns
FROM tab1,
tab2,
tab3,
-----
WHERE cond1
AND
cond2
AND
------
Example :-
SELECT e.ename,
d.dname,
l.city,l.state,
c.country_name
FROM emp e,
dept d,
locations l,
countries c
WHERE e.deptno = d.deptno
AND
d.locid = l.locid
AND
l.country_id = c.country_id
ANSI style :-
------------
=> Advantage of ANSI style is portability.
=> join queries becomes portable i.e. queries can migrated from one db to another
db.
=> in ANSI style tablenames are seperated by keywords
=> use ON clause for join conditions instead of WHERE clause
SELECT e.ename,d.dname
FROM emp e INNER JOIN dept d
ON e.deptno = d.deptno
SELECT e.ename,d.dname
FROM emp e INNER JOIN dept d
ON e.deptno = d.deptno
WHERE d.loc='NEW YORK'
SELECT columns
FROM tab1 INNER JOIN tab2
ON condition
INNER JOIN tab3
ON condition
--------------
SELECT e.ename,
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
27-aug-21
OUTER JOIN :-
-------------
=> equi join returns only matching rows but cannot return unmatched rows but to
get
unmatched rows also perform outer join.
Example :-
EMP DEPT
EMPNO ENAME SAL DEPTNO DEPTNO DNAME LOC
1 A 5000 10 10 ACCOUNTS
2 B 3000 20 20 RESEARCH
3 C 4000 30 30 SALES
4 D 2000 20 40 OPERATIONS => unmatched row
5 E 3000 NULL => unmatched row
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 table and matching rows from dept table.
A ACCOUNTS
B RESEARCH
C SALES
D RESEARCH
E NULL => unmatched row 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 ACCOUNTS
B RESEARCH
C SALES
D RESEARCH
NULL OPERATIONS => unmatched from dept table
FULL JOIN :-
--------------
A ACCOUNTS
B RESEARCH
C SALES
D RESEARCH
E NULL => unmatched row from emp
NULL OPERATIONS => unmatched row from dept
scenario :-
PROJECTS
projid name duration cost client
100
101
102
EMP
empid ename sal projid
1 100
2 101
3 100
4 null
=> display employee details with project details and also display employees not
assigned to any project ?
SELECT e.*,p.*
FROM emp e LEFT JOIN projects p
ON e.projid = p.projid
=> display employee details with project details and also display projects where
no employee assigned to it ?
SELECT e.*,p.*
FROM emp e RIGHT JOIN projects p
ON e.projid = p.projid
SELECT e.ename,d.dname
FROM emp e LEFT JOIN dept d
ON e.deptno = d.deptno
WHERE d.dname IS NULL
SELECT e.ename,d.dname
FROM emp e RIGHT JOIN dept d
ON e.deptno = d.deptno
WHERE e.ename IS NULL
28-AUG-21
=> non equi join is performed between the two tables not sharing a common field.
=> this join is called non equi join because here join condition is not based "="
operator and it is based on > < between operators.
Example :-
EMP SALGRADE
EMPNO ENAME SAL GRADE LOSAL HISAL
1 A 5000 1 700 1000
2 B 2500 2 1001 2000
3 C 1000 3 2001 3000
4 D 3000 4 3001 4000
5 E 1500 5 4001 9999
SELECT e.empno,e.ename,e.sal,s.grade
FROM emp e,salgrade s
WHERE e.sal BETWEEN s.losal and s.hisal
1 A 5000 5
2 B 2500 3
3 C 1000 1
4 D 3000 3
5 E 1500 2
ANSI style :-
-------------
SELECT e.empno,e.ename,e.sal,s.grade
FROM emp e JOIN salgrade s
ON e.sal BETWEEN s.losal and s.hisal
SELECT e.empno,e.ename,e.sal,s.grade
FROM emp e JOIN salgrade s
ON e.sal BETWEEN s.losal and s.hisal
WHERE s.grade = 3
SELECT e.ename,d.dname,s.grade
FROM emp e INNER JOIN dept d
ON e.deptno = d.deptno
JOIN salgrade s
ON e.sal BETWEEN s.losal and s.hisal
SELF JOIN :-
-------------
Example :-
EMP
EMPNO ENAME MGR
7369 SMITH 7902
7499 ALLEN 7698
7521 WARD 7698
7566 JONES 7839
7654 MARTIN 7698
7698 BLAKE 7839
7782 CLARK 7839
7788 SCOTT 7566
7839 KING NULL
7902 FORD 7566
=> above table contains MGR but to display manager name we need to perform self
join.
=> to perform self join the same table must be declared two times different alias
EMP X EMP Y
ANSI style :-
30-AUG-21
Question :-
TEAMS
ID COUNTRY
1 IND
2 AUS
3 RSA
IND VS AUS
IND VS RSA
AUS VS RSA
CROSS JOIN :-
-------------
A=1,2
B=3,4
=>if we perform cross join between two tables then each record of 1st table joined
with each and every record of second table.
=> to perform cross join submit the join query without join condition
SELECT e.ename,d.dname
FROM emp e,dept d
ANSI STYLE :-
SELECT e.ename,d.dname
FROM emp e CROSS JOIN dept d
CREATING NEW FROM THE QUERY OUTPUT :-
-------------------------------------
SELECT E.EMPNO,E.ENAME,E.SAL,
D.DEPTNO,D.DNAME,D.LOC INTO EMP_DEPT
FROM EMP E INNER JOIN DEPT D
ON E.DEPTNO = D.DEPTNO
=> display dept wise total sal ? display dept names in output ?
scenario :-
SALES
DATEID PRODID CUSTID QTY AMOUNT
2021-08-30 100 10 1 3000
PRODUCTS
PRODID PNAME PRICE CATEGORY
100 ELECTRONICS
CUSTOMERS
CUSTID NAME ADDR CITY STATE COUNTRY
CUST1 CUST2
CID NAME CITY CID NAME CITY
1 A HYD 1 A HYD
2 B CHE 2 B DEL
3 C BLR 3 C MUM
=> update cust2 city field with cust1 table city field ?
UPDATE CUST2
SET CUST2.city = cust1.city
FROM cust2 INNER JOIN cust1
ON cust2.cid = cust1.cid
---------------------------------------------------
*************************************----------------------------------------------
------------------------------
SET operators :-
----------------
=> in SQL SERVER set operations are performed between output of two select
statements
=> these operations are performed between set of rows return by two select
statement
Rules :-
---------
1 no of columns return by both queries must be same
2 corresponding columns datatype must be same
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 UNION ALL B = 1,2,3,4,1,2,5,6
A INTERSECT B = 1,2
A EXCEPT B = 3,4
B EXCEPT A = 5,6
SELECT STATEMENT 1
UNION / UNION ALL / INTERSECT / EXCEPT
SELECT STATEMENT 2
CLERK
MANAGER
ANALYST
CLERK
ANALYST
SALESMAN
SALESMAN
SALESMAN
MANAGER
SALESMAN
CLERK
UNION :-
---------
ANALYST
CLERK
MANAGER
SALESMAN
ANALYST 3000.00
CLERK 950.00
CLERK 1100.00
CLERK 2000.00
MANAGER 2850.00
MANAGER 2975.00
SALESMAN 1250.00
SALESMAN 1500.00
SALESMAN 1600.00
union vs join :-
----------------
union join
T1 T2
F1 C1
1 10
2 20
3 30
T1 U T2 :-
1
2
3
10
20
30
T1 JOIN T2 :-
1 10
2 20
3 30
scenario :-
-----------
EMP_US
ENO ENAME SAL DNO
DEPT
EMP_IND DNO DNAME LOC
ENO ENAME SAL DNO
SELECT E.*,D.*
FROM EMP_US E INNER JOIN DEPT D
ON E.DEPTNO = D.DEPTNO
SELECT E.*,D.*
FROM EMP_US E INNER JOIN DEPT D
ON E.DEPTNO = D.DEPTNO
UNION
SELECT E.*,D.*
FROM EMP_IND E INNER JOIN DEPT D
ON E.DEPTNO = D.DEPTNO
UNION ALL :-
-------------
3 slower faster
INTERSECT :-
-------------
=> returns common values from the output of two select statements
CLERK
MANAGER
EXCEPT :-
---------
=> returns values present in 1st query output and not present in 2nd query output
ANALYST
SALESMAN
Question :-
T1 T2
F1 C1
1 1
2 2
3 3
10 40
20 50
30 60
1 INNER JOIN
2 LEFT JOIN
3 RIGHT JOIN
4 FULL JOIN
5 UNION
6 UNION ALL
7 INTERSECT
8 EXCEPT
----------------------------------------------------
*****************************************************************------------------
--------------------------------
IDENTITY :-
-----------
syn :- IDENTITY(SEED,INCR)
Example :-
cid cname
100 A
101 B
102 C
103 D
05-AUG-21
DBCC CHECKIDENT(tablename,reseed,value)
DBCC CHECKIDENT('cust',reseed,99)
=> by default sql server will not allow explicit value into identity column
=> to insert explicit value into identity column execute the following command
ANS :- no
output :- ERROR
ANS :- no
output :- ERROR
-------------------------------------------------------
************************************************-----------------------------------
-----------------------------
------------------------------------------------------------------
****************-------------------------------------------------------------------
------------------
Types of Subqueries :-
-----------------------
=> if inner query returns one value then subquery is called single row subquery
syntax :-
SELECT columns
FROM tabname
WHERE colname OP (SELECT statement)
SELECT *
FROM emp
WHERE sal > (SELECT sal FROM emp WHERE ename='blake')
SELECT *
FROM emp
WHERE hiredate < (SELECT hiredate FROM emp WHERE ename='king')
SELECT ename
FROM emp
WHERE sal = MAX(sal) => ERROR
=> aggregates like min,max,sum,avg,count are not allowed in where clause and they
are allowed only in select,having clause.
SELECT ename
FROM emp
WHERE sal = (SELECT MAX(sal) FROM emp)
SELECT ename
FROM emp
WHERE hiredate = (SELECT MIN(hiredate) FROM emp)
UPDATE emp
SET sal=sal+(sal*0.1)
WHERE hiredate = (SELECT MIN(hiredate) FROM emp)
=> delete the employee having max experience ?
02-sep-21
multi-row subqueries :-
-----------------------
=> if subquery returns more than one value then it is called multirow subquery
SELECT columns
FROM tabname
WHERE colname OP (SELECT STATEMENT)
Example :-
SELECT *
FROM emp
WHERE job IN (
SELECT job
FROM emp
WHERE ename IN ('smith','blake')
)
ANY operator :-
---------------
=> used for comparision with any value i.e. atleast one
IF X=800 FALSE
X=1500 TRUE
X=4500 TRUE
IF X=800 TRUE
X=1500 TRUE
X=4500 FALSE
ALL operator :-
-----------------
WHERE X>ALL(1000,2000,3000)
IF X=800 FALSE
X=1500 FALSE
X=4500 TRUE
WHERE X<ALL(1000,2000,3000)
IF X=800 TRUE
X=1500 FALSE
X=4500 FALSE
single multi
= IN
SELECT *
FROM emp
WHERE sal > ALL (SELECT sal
FROM emp
WHERE job='MANAGER')
SELECT *
FROM emp
WHERE sal > ALL (SELECT sal
FROM emp
WHERE job='MANAGER')
co-related subqueries :-
------------------------
=> if inner query refers values of outer query then it is called co-related
subquery.
=> here execution starts from outer query and inner query is executed for each row
return by outer query.
=> use co-related subquery to execute subquery for each row return by outer query
03-sep-21
Example :-
EMP
EMPNO ENAME SAL DEPTNO
1 A 5000 10
2 B 4000 20
3 C 7000 30
4 D 8000 20
5 E 4000 10
=> display employee list earning more than avg(sal) of their dept ?
SELECT *
FROM emp x
WHERE sal > (SELECT AVG(sal)
FROM emp
WHERE deptno = x.deptno)
1 A 5000 10 5000 > (SELECT AVG(sal) FROM emp WHERE deptno=10) 4500 T
2 B 4000 20 4000 > (SELECT AVG(sal) FROM emp WHERE deptno=20) 6000 F
3 C 7000 30 7000 > (SELECT AVG(sal) FROM emp WHERE deptno=30) 7000 F
4 D 8000 20 8000 > (SELECT AVG(sal) FROM emp WHERE deptno=20) 6000 T
5 E 4000 10 4000 > (SELECT AVG(sal) FROM emp WHERE deptno=10) 4500 F
SELECT *
FROM emp x
WHERE sal = (SELECT MAX(sal)
FROM emp
WHERE deptno = x.deptno)
emp a emp b
SAL SAL
5000 5000 3 > (0) TRUE
1000 1000 3 > (4) FALSE
3000 3000 3 > (2) TRUE
2000 2000 3 > (3) FALSE
4000 4000 3 > (1) TRUE
EXISTS operator :-
-----------------
=> use EXISTS operator to check whether record exists in the table or not
SELECT
FROM tabname
WHERE EXISTS (SELECT STATEMENT)
Example :-
PRODUCTS
PRODID PNAME PRICE CATEGORY
100
101
102
ORDERS
ORDID PRODID QTY
1000 100 1
1000 101 2
1001 100 1
method 1 :-
SELECT *
FROM products p
WHERE EXISTS (SELECT * FROM orders WHERE prodid = p.prodid)
method 2 :-
SELECT *
FROM products
WHERE prodid IN (SELECT prodid FROM orders)
=> SQL SERVER recommends EXISTS operator instead of IN operator because EXISTS
gives
good performance than IN operator.
05-sep-21
Derived Tables :-
-----------------
SELECT columns/*
FROM (SELECT STATEMENT) <ALIAS>
[WHERE COND]
FROM
WHERE
GROUP BY
HAVING
SELECT
ORDER BY
Example 1 :-
=> above query displays annual salaries of all the employees but to display
employees
whose annual sal > 30000
=> column alias cannot be referenced in where clause because where clause is
executed
before select , to overcome this proble use derived tables.
SELECT *
FROM (SELECT ename,sal*12 as annsal
FROM emp) E
WHERE annsal>30000
Example 2 :-
SELECT empno,ename,sal,
DENSE_RANK() OVER (ORDER BY SAL DESC) AS RNK
FROM EMP
=> above query display ranks of all the employees but to display top 5 employees
SELECT empno,ename,sal,
DENSE_RANK() OVER (ORDER BY SAL DESC) AS RNK
FROM EMP
WHERE rnk <= 5 => ERROR
SELECT *
FROM (SELECT empno,ename,sal,
DENSE_RANK() OVER (ORDER BY SAL DESC) AS RNK
FROM EMP) E
WHERE rnk <= 5
Example 3 :-
SELECT *
FROM (SELECT empno,ename,sal,deptno ,
row_number() over (order by empno asc) as rno
FROM emp) E
WHERE rno<=5
SELECT *
FROM (SELECT empno,ename,sal,deptno ,
row_number() over (order by empno asc) as rno
FROM emp) E
WHERE rno=5
SELECT *
FROM (SELECT empno,ename,sal,deptno ,
row_number() over (order by empno asc) as rno
FROM emp) E
WHERE rno BETWEEN 5 AND 10
SELECT *
FROM (SELECT empno,ename,sal,deptno ,
row_number() over (order by empno asc) as rno
FROM emp) E
WHERE rno%2=0
06-sep-21
DELETE
FROM (SELECT empno,ename,sal,deptno ,
row_number() over (order by empno asc) as rno
FROM emp) E
WHERE rno<=5 => ERROR
----------------------------------------------------------------------
**************************************---------------------------------------------
--------------
CTE :-
-------
=> CTE stands for common table expression which is a named result which we can
refer
in another query like SELECT/INSERT/UPDATE/DELETE.
=> using CTEs we can use result of one operation in another operation.
syntax :-
WITH <name>
AS
(SELECT STATEMENT) ,
<name>
AS
(SELECT STATEMENT)
SELECT/INSERT/UPDATE/DELET STATEMENT
WITH E
AS
(SELECT empno,ename,sal,deptno ,
row_number() over (order by empno asc) as rno
FROM emp)
DELETE FROM E WHERE rno<=5
EMP33
ENO ENAME SAL
1 A 5000
2 B 6000
1 A 5000 => duplicate
2 B 6000 => duplicate
3 C 7000
SELECT eno,ename,sal,
ROW_NUMBER() OVER (PARTITION BY eno,ename,sal ORDER BY eno ASC) as rno
FROM emp33
1 A 5000 1
1 A 5000 2
2 B 6000 1
2 B 6000 2
3 C 7000 1
WITH E
AS
(SELECT eno,ename,sal,
ROW_NUMBER() OVER (PARTITION BY eno,ename,sal ORDER BY eno ASC) as rno
FROM emp33)
DELETE FROM E WHERE RNO>1
method 2 :-
-----------
EMP33
ENO ENAME SAL
1 A 5000
2 B 6000
1 A 5000 => duplicate
2 B 6000 => duplicate
3 C 7000
step 1 : - create temp table and copy distinct rows to temp table
temp
1 A 5000
2 B 6000
3 C 7000
Assignment :-
07-SEP-21
scalar subqueries :-
--------------------
Example 1 :-
emp dept
14 4
Example 2 :-
10 8750.00 21150.00
20 7100.00 21150.00
30 5300.00 21150.00
PCT = (dept_totsal/totsal)*100
OR
select
where clause
order by
functions
group by
joins
set operators
subqueries
-----------------------------------------------------------------------------
**************************************---------------------------------------------
-----
Types of functions :-
----------------------
1 date
2 string
3 mathematical
4 conversion
5 special
6 analytical
7 aggregate
DATE functions :-
-----------------
DATEPART(interval,date)
01 sunday
02 monday
03 tuesday
07 saturday
dayofyear => 217 out of 365 days
qq => 3 (quarter)
01 jan-mar
02 apr-jun
03 jul-sep
04 oct-dec
06-aug-21
DATENAME() :-
-------------
MM DW
DATEPART 08 6
SELECT ENAME,
DATEDIFF(mm,hiredate,GETDATE())/12 AS YEARS,
DATEDIFF(mm,hiredate,GETDATE())%12 AS MONTHS
FROM EMP
SMITH 40 8
SELECT ENAME,
CAST(DATEDIFF(mm,hiredate,GETDATE())/12 AS VARCHAR) + ' YEARS '
+ CAST(DATEDIFF(mm,hiredate,GETDATE())%12 AS VARCHAR) + ' MONTHS '
FROM EMP
07-aug-21
DATEADD() :-
DATEADD(interval,int,date)
NOTE :-
=> "=" comparision with GETDATE() always fails to overcome this problem use
FORMAT function
2021-08-07 = 2021-08-07
scenario :-
GOLD_RATES
DATEID RATE
2015-01-01 ????
2015-01-02 ????
2021-08-7 ????
EOMONTH(date,int)
Assignment :-
SELECT DATEADD(YY,DATEDIFF(yy,0,GETDATE()),0)
SELECT DATEADD(YY,DATEDIFF(yy,0,GETDATE())+1,0)
STRING functions :-
UPPER(arg)
string
colname
LOWER(arg)
string
colname
SELECT LOWER('HELLO') => hello
09-AUG-21
LEN(string/colname)
LEFT(string,len)
scenario :-
SELECT empno,ename,
LEFT(ename,3) + LEFT(empno,3) + '@microsoft.com' as emailid
FROM emp
RIGHT(string,len)
=> display employees name starts and ends with same char ?
SUBSTRING() :- used to extract part of the string starting from specific position
SUBSTRING(string,start,len)
CHARINDEX() :-
CHARINDEX(char,string,[start])
Assignment :-
CUST
CID CNAME
10 sachin tendulkar
11 virat kohli
SELECT CID,
SUBSTRING(cname,1,CHARINDEX(' ',CNAME)-1) AS FIRSTNAME,
SUBSTRING(cname,CHARINDEX(' ',CNAME)+1,LEN(CNAME)) AS LASTNAME
FROM CUST
REPLACE(str1,str2,str3)
TRANSLATE(str1,str2,str3)
e => a
l => b
o => c
SELECT empno,ename,
TRANSLATE(sal,'0123456789','$Kp*G%B^Q@') as sal
FROM emp
10-aug-21
Mathematical Functions :-
--------------------------
abs(-10) => 10
power(3,2) => 9
sqrt(16) => 4
square(5) => 25
sign(10) => 1
sign(-10) => -1
sign(0) => 0
ROUND(number,decimal places)
38------------------38.5--------------------39
number < avg => rounded to lowest
number >= avg => rounded to highest
300----------------------350----------------------400
380----------------------385-------------------------390
0-------------------------500---------------------------1000
CEILING(3.1) => 4
FLOOR(3.9) => 3
Analytical functions :-
-----------------------
Example :-
=> 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
=> diff b/w rank & dense_rank ?
1 rank function generates gaps but dense_rank will not generate gaps
2 rank function ranks may not be in sequence but in dense_rank ranks will be
always in sequence
11-aug-21
=> display ranks of the employees based on sal ? if salarie are same then ranking
should be based on experience ?
SELECT empno,ename,hiredate,sal,
DENSE_RANK() OVER (ORDER BY sal DESC,hiredate ASC) as rnk
FROM emp
PARTITION BY clause :-
-----------------------
=> used to find ranks with in group , for example to find ranks with in dept first
we need divide the table dept wise using PARTITION BY clause and apply
dense_rank
function on each partition instead of applying it on whole table.
SELECT deptno,empno,ename,sal,
dense_rank() over (partition by deptno order by sal desc) as rnk
FROM emp
ROW_NUMBER() :-
---------------
=> returns record numbers for the records return by select query
=> row_number is also based on some column
=> row_number also accepts sorted input
SELECT empno,ename,sal,
ROW_NUMBER() over (ORDER BY empno ASC) as rno
FROM emp
conversion functions :-
------------------------
1 CAST
2 CONVERT
CAST() :-
CAST(source-expr as target-type)
CONVERT() :-
CONVERT(target-type,source-expr)
=> using convert function we can display dates in different formats but not
possible
using cast function.
CONVERT(varchar,date,style-number)
6 106 - 6 = dd mon yy
106 = dd mon yyyy
7 107 7 = Mon dd, yy
107 = Mon dd, yyyy
8 108 - hh:mi:ss
Note: For a milliseconds (mmm) value of 0, the millisecond decimal fraction value
will not display. For example, the value '2012-11-07T18:26:20.000 displays as
'2012-11-07T18:26:20'.
- 127(6, 7) ISO8601 with time zone Z. yyyy-MM-ddThh:mm:ss.fffZ (no
spaces)
Note: For a milliseconds (mmm) value of 0, the millisecond decimal value will not
display. For example, the value '2012-11-07T18:26:20.000 will display as '2012-11-
07T18:26:20'.
- 130 (1,2) Hijri (5) dd mon yyyy hh:mi:ss:mmmAM
CONVERT(varchar,number,style-number)
special functions :-
ISNULL(arg1,arg2)
display ENAME,SAL,COMM,TOTSAL ?
TOTSAL = SAL+COMM
Aggregate Functions :-
-----------------------
=> Aggregate functions process group of rows and returns one value
MAX(arg)
MIN(arg)
SUM(arg)
39000-----------39500--------------40000
AVG(arg)
T1
F1
10
NULL
20
NULL
30
COUNT(F1) = 3
COUNT(*) = 5
NOTE :- GROUP functions are not allowed in where clause they are allowed only in
SELECT,HAVING clauses .
=> rollup & cube are used to display subtotals and grand totals.
GROUP BY ROLLUP(col1,col2,--)
GROUP BY CUBE(col1,col2,----)
ROLLUP :-
----------
=> ROLLUP displays subtotals for each group and also displays grand total
10 CLERK 1300.00
10 MANAGER 2500.00
10 PRESIDENT 5000.00
10 NULL 8800.00 => DEPT SUBTOTAL
20 ANALYST 6000.00
20 CLERK 1900.00
20 MANAGER 3000.00
20 NULL 10900.00 => DEPT SUBTOTAL
30 CLERK 1000.00
30 MANAGER 2900.00
30 SALESMAN 5700.00
30 NULL 9600.00 => DEPT SUBTOTAL
NULL NULL 29300.00 => GRAND TOTAL
CUBE :-
=> cube displays subtotal for each group by column(deptno,job) and also displays
grand total.
10 CLERK 1300.00
10 MANAGER 2500.00
10 PRESIDENT 5000.00
10 NULL 8800.00 => dept subtotal
20 ANALYST 6000.00
20 CLERK 1900.00
20 MANAGER 3000.00
20 NULL 10900.00 => dept subtotal
30 CLERK 1000.00
30 MANAGER 2900.00
30 SALESMAN 5700.00
30 NULL 9600.00 => dept subtotal
NULL ANALYST 6000.00 => job subtotal
NULL CLERK 4200.00 => job subtotal
NULL MANAGER 8400.00 => job subtotal
NULL PRESIDENT 5000.00 => job subtotal
NULL SALESMAN 5700.00 => job subtotal
NULL NULL 29300.00 => grand total
Assignment :-
SALES
DATEID PRODID CUSTID QTY AMOUNT
=> display year wise and with in year quarter wise total amount ? display year wise
subtotals ?
PERSONS
AADHARNO NAME GENDER AGE ADDR CITY STATE
=> display state wise and with in state gender wise population ? display state
wise and gender wise subtotals ?
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
08-sep-21
Database Transactions :-
-------------------------
=> a transaction is a unit of work that contains one or more dmls and must be
saved
as a whole or must be cancelled as a whole.
ex :- money transfer
acct1-----------------1000------------------->acct2
update1 update2
(bal=bal-1000) (bal=bal+1000)
=> every db transaction must gurantee a property called atomocity i.e. all or none
if transaction contains multiple operations , if all are successful then it
must be saved , if one of the operation fails then entire transaction must be
cancelled.
=> the following commands provided by sql server called TCL (transaction control
language)
commands to handle transactions
=> in sql server a txn begins implicitly with DML/DDL commands and ends implicitly
with COMMIT.
=> we can also start transaction explicitly with "BEGIN TRANSACTION" command and
ends explicitly with COMMIT/ROLLBACK.
Example 1 :-
=> if txn ends with commit then it is called successful transaction and operations
are saved
Example 2 :-
=> if txn ends with rollbck then it is called aborted transaction and operations
are cancelled
Example 3 :-
output :-
Example 5 :-
output :-
SAVE TRANSACTION :-
--------------------
=> we can declare save transaction and we can rollback upto the save transaction.
=> using save transaction we can cancel part of the transaction.
SELECT * FROM a
10
20
11-SEP-21
Database Security :-
--------------------
---------------------------------------------------------
**************************************************************---------------------
---------------------------
TABLES
VIEWS
SYNONYMS
SEQUENCES
INDEXES
VIEWS :-
---------
1 to provide security
2 to reduce complexity
=> view provides another level of security by granting specific rows & columns to
users
1 simple views
2 complex views
1 simple views :-
----------------
Example :-
CREATE VIEW V1
AS
SELECT empno,ename,job,deptno
FROM emp
=> when the above command is executed then sql server creates view v1 and stores
query
but not query output (data).
=> a view is called virtual because it doesn't store data and doesn't occupy memory
and it always derives data from base table
SELECT * FROM V1
=> when above query submitted to sql sever it executes the query as follows
=> after granting permission on view to vijay , vijay can access emp table through
view
VIJAY :-
---------
1 SELECT * FROM V1
=> above insert command inserts row into emp table and fields which are not
included
in view are filled with nulls.
CREATE VIEW V2
AS
SELECT empno,ename,job,deptno
FROM emp
WHERE deptno=20
VIJAY :-
=> above insert command executed successfully even though it is violating where
condition
=> if view created with "WITH CHECK OPTION" then any dml command through view
violates
where condition that dml is not accepted.
CREATE VIEW V3
AS
SELECT empno,ename,job,deptno
FROM emp
WHERE deptno=20
WITH CHECK OPTION
VIJAY :-
14-sep-21
complex views :-
-----------------
=> with the help of views complex queries can be converted into simple queries
Example 1 :-
=> after creating view , whenever we want emp & dept details instead of writing
join query write the simple query as follows
Example 2 :-
simple complex
Question :-
ans :- by default column is not added , to add this column to view it must be
recreated
Droping view :-
----------------
DROP VIEW V1
WITH SCHEMABINDING :-
---------------------
=> if view created with "WITH SCHEMABINDING" then sql server will not allow users
to
drop table if any view exists on the table , To drop table first we need to drop
view.
Rules ;-
-------------------------------------------------------------------
********************************************---------------------------------------
---------------
SEQUENCES :-
------------
syn :-
Example:-
CREATE SEQUENCE S1
START WITH 1
INCREMENT BY 1
MAXVALUE 5
CREATE SEQUENCE S2
START WITH 100
INCREMENT BY 1
MAXVALUE 1000
CREATE SEQUENCE S3
START WITH 1
INCREMENT BY 1
MAXVALUE 1000
INVNO INV_DT
KLM/0915/1
KLM/0915/2
CYCLE / NOCYCLE :-
=> default is NOCYCLE , if sequence created with NOCYCLE then it starts from start
with and generates
upto max and after reaching max then it stops.
=> if sequence created with CYCLE then it starts from start with and generates upto
to max and
after reaching max then it will be reset to min.
CREATE SEQUENCE S4
START WITH 1
INCRMENT BY 1
MAXVALUE 5
MINVALUE 1
CYCLE
1 A
2 B
3 C
4 D
5 E
1 F
2 G
3 H
4 I
5 J
CREATE SEQUENCE S5
START WITH 1
INCREMENT BY 1
MAXVALUE 1000
Droping sequence :-
-------------------
DROP SEQUENCE S1
-------------------------------------------------------
************************************************-----------------------------------
----------------------------
INDEXES :-
----------
=> when user submits a query , sql server goes through following steps to execute
the query
1 parsing
2 optimization
3 execution
parsing :-
----------
1 checks syntax
2 checks semantics
checks table exists in the db or not
checks columns belongs to the table or not
user has permission to access table or not
optimization :-
----------------
1 table scan
2 index scan
=> estimate the cost of each plan and selects best plan i.e. plan that takes less
cost
=> in table scan sql server scans whole table
=> in index scan on avg sql server scans half of the table
execution :-
--------------
=> sql server executes the query according to plan selected by optimizer.
=> indexes are created on columns and that column is called index key
Types of indexes :-
-------------------
=> if index created on single column then index is called simple index.
EMP 3000
SAL
5000
1000 2000 4000
3000
2000 1000 * 2500 * 4000 * 5000 *
4000 1500 * 3000 *,*
1500 2000 *
3000
2500
=> SQL SERVER uses above index for the queries where condition based on sal column
17-sep-21
composite index :-
-----------------
=> if index created on multiple columns then index is called composite index
=> sql server uses above index when where condition based on leading column of the
index i.e. deptno
unique index :-
---------------
=> unqiue index doesn't allow duplicate values into the column on which index is
created
G Q
=> primary key / unique columns are implicitly indexed by sql server , sql sever
creates a unique
index on primary key / unique columns and unique index doesn't allow
duplicates so primary key/
unique also doesn't allow duplicates .
CLUSTERED INDEX :-
------------------
=> a non clustered index stores pointers to actual records where as clustered
index stores actual records
=> in non clustered index order of the records in index and order of the records
in table is not same
where as in clustered index this order will be same.
50
30 70
10 A 40 C 60 D 80 B
20 E
SELECT * FROM CUST => sql server goes to clustered index and reads nodes
from left to right
10 A
20 E
40 C
60 D
80 B
=> only one clustered index is allowed per table and sql server creates
clustered index on priamry key column
sp_helpindex emp
Droping index :-
------------------
DROP INDEX I1
------------------------------------------------
***********************************************************------------------------
---------------------------------
synonyms :-
-----------
=> when tablename is lengthy or complex then we can give a simple and short name
to the table
and instead of using tablename we can use that simple and short name called
synonym.
=> after creating synonym instead of using tablename we can use synonym name in
SELECT/INSERT/UPDATE/DELETE queries
1 SELECT * FROM E
MERGE command :-
-----------------
scenario :-
17th sep
CUSTS
CID CNAME ADDR
1 A HYD
2 B MUM
CUSTT
CID CNAME ADDR
1 A HYD
2 B MUM
18th sep
CUSTS
CID CNAME ADDR
1 A BLR => updated
2 B MUM
3 C DEL => inserted
=> whatever changes (insert,update) made to custs we need to apply these changes
to custt ,
instead of executing insert & update seperately we can combine these two
commands into
one command called merge
20-sep-21
CUSTS
CID CNAME ADDR
1 A BLR => updated
2 B MUM
3 C DEL => delete
4 D CHE => inserted
CUSTT
CID CNAME ADDR
1 A HYD
2 B MUM
3 C DEL
PIVOT operator :-
-------------------
SELECT columns
FROM (SELECT required data) AS <ALIAS>
PIVOT
(
aggr-expr FOR colname IN (V1,V2,V3,--)
) AS <PIVOT-TABLE-NAME>
ORDER BY col ASC/DESC
Example 1 :-
10 20 30
SELECT *
FROM (SELECT deptno,job,sal FROM emp) AS E
PIVOT
(
SUM(sal) FOR deptno IN ([10],[20],[30])
) AS PIVOT_TBL
ORDER BY job ASC
Example 2 :-
1 2 3 4
1980 ? ? ? ?
1981 ? ? ? ?
1982 ? ? ? ?
1983 ? ? ? ?
SELECT *
FROM (SELECT DATEPART(yy,hiredate) as year,
DATEPART(qq,hiredate) as qrt,
empno
FROM emp) AS E
PIVOT
(
COUNT(empno) FOR qrt IN ([1],[2],[3],[4])
) AS PIVOT_TBL
ORDER BY year ASC
STUDENT
SNO SNAME SUBJECT MARKS
1 A MAT 90
1 A PHY 80
1 A CHE 60
2 B MAT 50
2 B PHY 40
2 B CHE 60
OUTPUT :-
SELECT *
FROM STUDENT
PIVOT
(
SUM(MARKS) FOR SUBJECT IN ([MAT],[PHY],[CHE])
) AS PIVOT_TBL
ORDER BY SNO ASC
----------------------------------------------------
******************************************************-----------------------------
-----------------------------
TSQL programming
----------------
Features :-
-----------
1 improves performance :-
-------------------------
=> using TSQL programming we can group sql commands into one program and we submit
that program to
sql server , so in TSQL programming no of requests and response between user and
sql server are
reduced and performance is improved.
=> TSQL supports conditional statements like if-then-else and using this we can
execute commands
based on conditions
3 supports loop :-
-------------------
=> in tsql , if any statement causes runtime error then sql server displays error
message , using
error handling we can replace system generated message with our own simple and
user friendly message
5 supports reusability :-
------------------------
=> TSQL programs can be centralized i.e. stored in db and applications which are
connected to db can
reuse these programs.
6 supports security :-
-----------------------
=> because these programs are stored in db and only authorized users can execute
these programs but
not unauthorized users.
1 anonymous blocks
2 named blocks
stored procedures
stored functions
triggers
Anonymous Blocks :-
--------------------
1 DECLARE
2 SET
3 PRINT
DECLARE statement :-
--------------------
ex :- DECLARE @x int
DECLARE @s varchar(10)
DECLARE @d date
SET statement :-
------------------
SET @x=100
SET @s='abc'
SET @d=GETDATE()
PRINT statement :-
------------------
PRINT @x
PRINT @s
PRINT @d
=> write a prog to input date and print day of the week ?
DECLARE @d date
SET @d='2021-10-15'
PRINT DATENAME(dw,@d)
=> to perform operations over db execute SQL commands from tsql program
=> the following commands can be executed from tsql program
1 DML (insert,update,delete,merge)
2 DQL (select)
3 TCL (commit,rollback,save transaction)
22-sep-21
=> write a prog to input empno and print name & salary ?
23-sep-21
conditional statements :-
-------------------------
1 if-else
2 multi if
3 nested if
1 if-else :-
------------
if cond
begin
statements
end
else
begin
statements
end
2 multi if :-
-------------
if cond1
begin
statements
end
else if cond2
begin
statements
end
else if cond3
begin
statements
end
else
begin
statements
end
3 nested if :-
---------------
if cond
begin
if cond
begin
statements
end
else
begin
statements
end
end
else
begin
statements
end
Example 1 :-
=> Write a prog to input empno and calculate experience , if expr > 40 the
delete record from table ?
=> write a prog to increment specific employee sal by specific amount and
after increment if sal exceeds 5000 then cancel that increment ?
24-sep-21
ACCOUNTS
ACCNO NAME BAL
100 A 10000
101 B 20000
=> write a prog to calculate particular student total,avg,result and insert into
result table ?
STUDENT
SNO SNAME S1 S2 S3
1 A 80 90 70
2 B 50 60 30
RESULT
SNO STOT SAVG SRES
WHILE LOOP :-
--------------
WHILE(cond)
BEGIN
statements
END
27-sep-21
DECLARE @x tinyint=1
WHILE(@x<=20)
BEGIN
PRINT @x
SET @x = @x+1
END
2022-01-01 ?
2022-01-02 ?
2022-12-31 ?
input :- BHARAT
output :-
B
H
A
R
A
T
INPUT :- INDIA
OUTPUT :-
I
IN
IND
INDI
INDIA
--------------------------------------------------------------------
*************************************----------------------------------------------
--------------
CURSORS :-
-----------
=> from tsql program if we submit a query to sql server , it goes to db and and
fetch the data
and copies that data into temporary memory and using cursor we can give name to
that memory
and access row-by-row into tsql program and process the row.
1 declare cursor
2 open cursor
3 fetch records from cursor
4 close cursor
5 deallocate cursor
declaring cursor :-
--------------------
opening cursor :-
-----------------
open <cursor-name>
OPEN C1
=> a fetch statement fetches one row at a time but to process multiple rows fetch
stmt should be
executed multiple times so fetch stmt should be inside a loop.
closing cursor :-
-----------------
close c1;
deallocating cursor :-
-----------------------
deallocate c1
@@FETCH_STATUS :-
------------------
=> write a prog to calculate total salary without using SUM function ?
=> write a prog to calculate all the students total,avg,result and insert into
result table ?
STUDENT
SNO SNAME S1 S2 S3
1 A 80 90 70
2 B 50 60 30
RESULT
SNO STOT SAVG SRES
29-sep-21
raise_salary
empno pct
7369 15
7499 10
7521 12
7566 20
7654 15
=> write a prog to increment employee salaries based on pct in raise_salary table ?
SCROLLABLE CURSOR :-
---------------------
=> by default cursor is forward only cursor and forward only cursor supports only
forward navigation
but doesn't support backward navigation.
=> if cursor declared with SCROLL then it is called scrollable cursor and a
scorllable cursor supports
both forward and backward navigation.
=> forward only cursor supports only FETCH NEXT statement but SCROLLABLE cursor
supports the following
fetch statements
Example 1 :-
------------------------------------------------------------
*************************************************----------------------------------
---------------------
1 syntax errors
2 logical errors
3 runtime errors
=> errors that are raised during program execution are called runtime errors
ex :- declare @x tinyint
set @x=1000 => runtime error
=> in TSQL programming if any statement causes runtime error then sql server
displays error message.
To replace system generated message with our own simple and user friendly
message then
we need to handle that runtime error
BEGIN TRY
statemens => causes runtime error
END TRY
BEGIN CATCH
statements => handles runtime error
END CATCH
=> in try block if any statement causes runtime error then control will be
transferred to catch block
and executes statements in catch block.
Example 1 :-
Example 2 :-
Example 3 :-
Example 1 :-
--------------
=> write a prog to increment specific employee sal by specific amount but sunday
updates are not allowed
Example 2 :-
01-oct-21
-----------------------------------------------------------------
*************************************----------------------------------------------
---------------
STORED PROCEDURES
STORED FUNCTIONS
TRIGGERS
SUB-PROGRAMS :-
--------------
STORED PROCEDURES
STORED FUNCTIONS
Advantages :-
--------------
1 modular programming :-
=> with the help of procedures & function a big tsql program can be divided into
small modules
2 reusability :-
=> procedures & function can be stored in db and application which are connected to
db can reuse
these programs.
3 security :-
=> procedures and functions are stored in db and they are secured , only
authorized users can execute
these programs
=> procedures & functions can be called from front-end applications like
java,.net,php etc.
5 improves performance :-
=> procedures improves performance because they are precompiled i.e. compiled
already and ready
for exectuion . when we create a procedure program is compiled and stored in db
and whenever
we call procedure only execution is repeated but not compilation.
STORED PROCEDURES :-
---------------------
=> a procedure is a named TSQL block that accepts some input perform some action
on db and may
or may not returns a value.
syntax :-
To Drop Procedure:
------------------
To delete the SP
or
1 INPUT
2 OUTPUT
INPUT :-
--------
OUTPUT :-
-----------
Example 1 :-
Execution :-
1 ssms
2 another program
3 front-end application
method 1 :- (positional)
method 2 :- (named)
02-oct-21
OUTPUT parameter :-
-------------------
=> create a procedure to increment specific employee sal by specific amount and
after increment
send the updated sal to calling program ?
Execution :-
DECLARE @s money
EXECUTE update_salary 7499,1000,@s OUTPUT
PRINT @s
DECLARE @s money
EXECUTE update_salary @eno=7499,@amt=1000,@newsal=@s OUTPUT
PRINT @s
Example 3 :-
ACCOUNTS
ACCNO ACTYPE BAL
100 S 10000
100 S 20000
TRANSACTIONS
TRID TTYPE TDATE TAMT ACCNO
04-oct-21
Execution :-
1 for calculation
2 to fetch value from db
=> if function returns one value then it is called scalar valued function
=> return type of these function must be scalar types like int,varchar,date etc
=> return expression must be scalar variable.
Modification:
-------------
Removeing:
----------
CREATE OR ALTER
FUNCTION CALC(@a int,@b int,@op char(1)) RETURNS int
AS
BEGIN
DECLARE @c int
IF @op='+'
SET @c=@a+@b
ELSE IF @op='-'
SET @c=@a-@b
ELSE IF @op='*'
SET @c=@a*@b
ELSE
SET @c=@a/@b
RETURN @c
END
Execution :-
1 sql commands
2 another pl/sql block
3 front-end applications
DECLARE @X INT
SET @X = DBO.CALC(10,20,'*')
PRINT @X
05-oct-21
Execution :-
-------------
Assignment :-
PRODUCTS
PRODID NAME PRICE
100 1000
101 2000
102 1500
ORDERS
ORDID PRODID QTY
1000 100 2
1000 101 1
1000 102 2
1001 100 2
syn :-
Example 1 :-
Execution :-
Example 2 :-
sachin
ramesh
tendulkar
procedures functions
scalar table
Assignment :-
ACCOUNTS
ACCNO NAME ACTYPE BAL
TRANSACTIONS
TRID TTYPE TDATE TAMT ACCNO
1 account opening
2 account closing
3 money deposit
4 money withdrawl
5 money transfer
6 balance enquiry
7 particular customer statement between two given dates
8 latest N transaction of particular customer
-----------------------------------------------------------------------
*************************************----------------------------------------------
------------
TRIGGERS :-
-------------
=> a trigger is also a named TSQL block like procedure but executed implicitly by
sql server
whenever user submits DML/DDL commands.
1 to control DMLs
2 to enforce complex rules and validations
3 to audit tables
3 to manage replicas
4 to generate values for primary key columns
syn :-
AFTER triggers :-
----------------
=> if trigger is AFTER then sql server will execute the trigger after executing
DML
INSTEAD OF trigger :-
--------------------
=> if trigger is INSTEAD OF then sql server executes the trigger instead of
executing DML.
Testing :- (getdate()=sunday)
Example 2 :-
Example 3 :-
08-oct-21
Magic Tables :-
----------------
1 INSERTED
2 DELETED
=> with the help of magic tables in triggers we can access data affected by dml
=> the record user is trying to insert is copied to inserted table
=> the record user is trying to delete is copied to deleted table
=> the record user is trying to update is copied to both inserted & deleted tables
INSERTED
empno sal
7499 2000
Testing :-
----------
UPDATE emp SET sal=1000 WHERE empno=7499 => ERROR
=> create trigger to insert details into emp_resign table when employee resigns
from organization ?
EMP_RESIGN
EMPNO ENAME HIREDATE DOR
Testing :-
INSTEAD OF trigger :-
------------------------
=> if trigger is instead of then sql server executes the trigger instead of
executing dml
EMP88
ENO ENAME SAL COMM HIREDATE
TESTING :-
-----------
10-oct-21
Auditing :-
------------
EMP_AUDIT
UNAME OPERATION OPTIME NEW_ENO NEW_ENAME NEW_SAL
OLD_ENO OLD_ENAME OLD_SAL
dbo INSERT ??? 100 A 5000 NULL
NULL NULL
dbo UPDATE ??? 100 A 6000 100
A 5000
dbo DELETE ??? NULL NULL NULL 100
A 6000
Droping Trigger :-
-------------------
DROP TRIGGER T2
Dynamic SQL :-
--------------
=> SQL commands build at runtime are called dynamic SQL commands
=> Dynamic SQL is useful when we don't know tablenames and columnnames until
runtime.
1 EXEC procedure
2 SP_EXECUTESQL procedure
using EXEC :-
--------------
=> dynamic sql command that you want to execute should be passed as a string to
EXEC
using SP_EXECUTESQL :-
Example 3 :-
EMP 14
DEPT 4
CUST 10
11-oct-21
backup command :-
-----------------
USE MASTER
BACKUP DATABASE [DB7PM] TO DISK = 'C:\DATA\DB7PM.BAK'
restore command :-
-----------------
USE MASTER
RESTORE DATABASE [DB7PM] FROM DISK = 'C:\DATA\DB7PM.BAK'