In-Depth T-SQL Course Overview
In-Depth T-SQL Course Overview
relational database
management system RDBMS DBE
DBE
RDBMS
Command(s) Successful
Skillgun Palle Master
SSMS and SQL Server Communication
Execute RDBMS
DBE
T-SQL query
CREATE DATABASE
TRAINING
SSMS MASTER DB
TRAINING
SQL SERVER
Data types in T-SQL
•Int •Binary • Timestamp
•Small int •Varbinary(max) • Table
•Bigint •Datetime • Real
•Tinyint •Date • Numeric
•Decimal •Time • Sql_variant
•Char •Smalldatetime • xml
•Nchar •datetime2
•Varchar •Money
•Nvarchar •Smallmoney
•Varchar(max) •bit
Datatypes Size in bytes
• Tinyint 1 byte
• Smallint 2 bytes
• Int 4 bytes
• Bigint 8 bytes
• decimal Can store upto 38 digits all can be
after decimal point
Char Nchar
A B C
A B C
Table
• Tables are the combination of Rows and Columns
Table = Row+Column
• Rows = tuples
Table1
• Columns = Attributes
or properties
Table creation syntax
Create table <table_name>
(
Column1 datatype1[(Size)],
Column2 datatype2,
Column3 datatype3,
……..
)
Note: As per industry standards table names and
column names must not be plurals.
table creation sample
Req:create a student table to store students details
sid,name,class,dob
student
table creation assignment
primary foreign
unique
key key
Default Constraints
Default constraints are useful for inserting default values
when user does not supply any value
Create table student
(
Sid int, Default
banglore
Name varchar(40),
City varchar(40) default ‘banglore ‘
)
DBE
NotNull Constraints
When you set the not null constraint to a specific column , that
column will not allow null value
NOT NULL
DBE
Not null constraint will not allow null values.
Check Constraints
By using check constraints we can limit the Range of permissible values
into specific column
18 - 60
Error
Whether DBE will accept this values?
Primary Key
primary key gives uniqueness to the tables rows
only one primary key is allowed per table
primary key will not allow null values and duplicate values
customer
DB
ERROR E
unique
unique constraint gives uniqueness to the tables rows
any number of unique constraints are allowed per table
unique contraint will not allow duplicate values and
allows only one null value
Unique
CUSTOMER
DBE
ERROR
Composite primary key
When we apply primary key constraint on more than one column,
then it is called Composite primary key.
primary key
Req:
Definitely the state column data are predictable data, because we have only
29 states in our country. All the 5000 students must belong to any 1 of 29 states.
Memory required for storing 1 state name is, Then for storing all the state names
how much memory is required ??
Very huge memory is required
How can we avoid this duplication, By splitting the single table into two tables
Now i have created 1 separate table for storing all the state names, and I have given a unique id
For each state
Now I will create a student table and in place of state column , I will give the state id.
UnNormalized table
ERROR student
Normalization lab1
Lab 1 solution
Foreignkey
Foreignkey
employee2 New_employee2
F.K
F.K F.K
Is it a valid data?
student student
country
city state
Normalization lab3
Req:Design Normalized Database
PK
F.K F.K
Batch
Types Of t-sql Statements
• t-sql statements categorized into
• DML Statements(Insert, Update, Delete, Select *
into )
• DDL Statements (Create, Alter)
• DQL Statements (All Select statements except
select * into )
• TCL Statements (Commit, Rollback)
• DCL Statements (Grant, Revoke used only by
DBA’s not by DB Programmers)
Generic Select Statement
SELECT select_list
[INTO new_table_name]
FROM table_list
[WHERE search_conditions]
[GROUP BY group_by_list]
[HAVING search_conditions]
DBE
Ask students to take table data in last page of their note.
Employee
Select sample-2
ERS
write a query for producing the following result set Fullname age
From employee table rajeevsukla 23
sowmyakumari 23
kishorekumar 27
Select fname+lname,age from employee abimanyubiswal 22
No column
Fullname
name age
rajeevsukla 23
sowmyakumari 23
kishorekumar 27
abimanyubiswal 22
DBE
• Table must be created without any constraints
Note: Create this table in the last pages of your
Table : Patient note book as this table used for explaining all
topics in t-sql.
Pid int
Fnamevarchar(40)
Lnamevarchar(40)
Ageint
BgVarchar(40)
Select Statement Lab-1
DBE
Employees table
int Varchar(40) Varchar(40) int int Varchar(40) date
Display employee
in desc order of
their first name
DBE
Draw the final result set .
Employees table
int Varchar(40) Varchar(40) int int Varchar(40) date
FRS
Order By Lab-1
• Identify the output for the following query?
Select fname+lname as ‘full name’, age from patient
order by age
• Identify the output for the following query?
select fname, lname, bg from patient order by bg
desc
Note: ascii for + is 43 and for – is 45
• Identify the output for the following query?
select fname, lname, pid from patient order by
lname, fname desc
Order By Lab-2
EMPLOYEES TABLE
QUERY: select distinct * from employees DBE
Lname
sukla
kumari
Kumar
biswal
_singh
_kumari
FRS
Distinct Lab-1
employee
Select top 3 fname,lname,age from employee DBE
FRS
IRS
Write a query to display the top 3 highest paid employee’s fullname and age
Select top 3 fname+lname as ‘fullname’ ,age from employee order by salary desc
IRS1
DBE
DBE
Query: select * from employees where salary>20000
Req: display all employees details whose salary is
between 15000 and 25000
FRS
employees
FRS
employees
FRS
employees
FRS
employees
FRS
employees
FRS created
employees
FRS created
employees
DBE
employees
FRS created
employees
FRS
Like clause Lab-1
employees
FRS
Req:update employee table with fname to rice, lname to paul
whose eid is 9
FRS employees
Req: delete a record from employee table whose eid is 9
DBE
delete employees where eid=9
employees FRS
Insert Update Delete Lab-1
• write a query for inserting the following patient
details into patient table?
patient id=10 fname=‘ahaha’ lname=‘kumar’
age=78 bg=‘o+ve’ ( write query using all possible
ways )
• write a query for inserting the following patient
details into patient table?
patient id=11 fname=‘silli’ lname=‘suresh’
age=81 bg is null ( write query using all possible
ways )
Insert Update Delete Lab-2
DBE
.ldf
DBE
No similar table will be created in .ldf
Drop table
.ldf
DBE
No similar table will be created in .ldf
Functions
Functions
Built In
functions User defined
functions
aggregate
functions
Cast and
Convert
aggregate functions
Note: we are not allowed to use aggregate functions in where clause
Note2: we are not allowed to use columns in
select list which are not linked with aggregate
Aggregate Functions functions when any column is linked with
aggregate function
Min
Max
Avg
Sum
Count
employee
DBE
Select COUNT(*) as ‘result’ from employee
Current Date
Time Functions datename datepart
GetDate()
dateadd datediff
GetUtcDate()
Date time function
DBE
DBE
Select datename(month,getdate())
Select datename(year,getdate())
@dob1
DBE 2018-06-12
2018-01-12
declare @d1 date
set @d1=GETDATE();
set @d1=dateadd(MONTH,5,@d1)
@dob2
declare @d2 date
set @d2=GETDATE(); 2018-01-27
2018-01-12
set @d1=dateadd(DAY,15,@d2)
@d1
declare @d1 date
1979-03-14
declare @d2 date DBE
set @d1='03/14/1979'
set @d2='12/18/2017'
@d2
2017-12-18
declare @y int
set @y=DATEDIFF(YEAR,@d1,@d2)
@y
38
declare @m int
set @m=DATEDIFF(MONTH,@d1,@d2) @m
465
declare @d int
@d
set @d=DATEDIFF(DAY,@d1,@d2)
14159
date time functions lab-1
21-06-2009
…………………..
cast and convert function lab-1
DBE
patient
having clause
having clause is used to filter records which are
produced by group by clause
as we cannot use aggregate function in where
clause in that place we will use having clause
select bg from patients group by bg having avg(age)>40 FRS
Avg(age)>40
DBE
Avg(age)>40
patient
Avg(age)>40
Avg(age)>40
group by lab - 1
non correlated
sub query correlated sub
query
Non-correlated sub query
input DBE
Final Output
non-correlated subquery samples.
• Display fullnames of employees whose bg is
same as fourth patient’s bg.
• Display all employees whose salary is greater
than ‘db’ departments average salary.
• Display all employees whose salary is between
Highest paid ‘.net’ dept employee’s salary and
least paid db dept employee’s salary.
non correlated sub queries lab-1
• write a query for displaying all patient details
whose age is greater the age of third
patient(pid=3)
• write a query for displaying all patient details
whose bg is same as 6th patient’s bg.
• write a query for displaying all patient details
whose age is not same as 1st patients age and 3rd
patients age and 9th patient’s age
• find the output for the following query?
select * from patient where age=(select age from
patient where pid in (1,3,6))
correlated sub query
Completely executed
Outer query1 (Inner query)
input DBE
Final Output
correlated sub query sample
select t1.* from t100 t1 where 1=(select count(*) from t100 t2 where t1.c3<t2.c3)
Where 1 = 10
23
DBE
employee
DBE
> [Link]
[Link]
FRS
correlated sub query
Cross joins
inner join
Patient1 p Bg b
Wherever there are no match in the right side table , null values
are included in the result set
SYNTAX:
Select pf.* , p.* from profession pf left outer join person p on [Link] = [Link]
In left outer join, all left table data must be added to result set
right outer join
In a right outer join , all the data from right side table will be
included in the result set ,And only the matched records from the
left side table is included to result set .
Wherever there are no match in the left side table , null values
are included in the result set
SYNTAX:
Profession pf Person p
Select pf.* , p.* from profession pf full outer join person p on [Link]=[Link]
DBE
Joining 3 or more tables
Student s City c State sn
select [Link],c.c_name,sn.state_name,cn.country_name from
Country cn
student s join city c on s.city_id=[Link]
join state sn on c.state_id=sn.state_id
join country cn on cn.country_id=[Link]
FRS ERS
DBE
cross join
A cross join with where clause will produce same
result as inner join
A cross join without where clause will produce the
cartesian products of the tables which are involved
in join
We must use cross join keyword for cross join
use where clause for specifying cross join condition
NOTE :
Must not use ON keyword for specifying cross join condition
profession person
Select p.*,pf.* from person p cross join profession pf
where [Link]=[Link]
DBE FRS
Cross join without where clause
profession person
Emp_mgr e1 Emp_mgr e2
T1 T2
tables required for joins lab
inner joins lab-1
Input
No Output
sp
Calling sp:
Stored Procedure sample 2
• write a sp with the name insertemployee for inserting new
employee into employee table (the sp must take @eid, @fn,
@ln, @age,@sal,@dept and @doj as input parameters)
Calling sp:
Stored Procedure Lab-1
SP UDF
Supports input & output parameters Supports only input parameters
Can write any type of sql queries Can’t write sql queries which modifies state of
db ( ex. insert/update/delete/create etc..)
clustered index
• In a clustered index , the actual table is stored in the leaf pages of b-tree
[binary tree]
• Only 1 clustered index is possible per table
syntax :-