‘SOL Commands by AS NAGER
SQL _(Structured Query Language) Commands
DATABASE : A collection of tables.
Tables: A collection of rows + 2 group of columns (Attributes).
We can say rons as tuples.
Each database has three types of conmands
DDL : Data Definition Language --> Like Database Structure Queries Create Table, Alter Table, Drop
Table or Database, Add Column or Drop Column
DML : Data Manipulation Language --> Insert, Update, Delete, Select, Clause ,0perators, Wild
Characters, Truncate,
DCL : Data Control Language --> Revoke, Commit, Rollback
CREATE DATABASE Institute 1 Database coats names es ete
USE Institute 1 Database vsed
Create Table Student
RoLINo int,
Name Varchar(5@), 1 Tab cote named as Sten
Class varchar(50),
PhoneNo varchar 10)
Narks decimal (5,2) ee
_»| RolNo Name Class PhoneNo Marks:
Select * fron Student
Insert Into Student Values (1, "Rambir’, "MCA" , "9992554784" , 89.25:
Insert Into Student Values (2, "Naveen", 'MBA’, "7876755755" , 75.75
Insert Into Student Values (3, *Sunil’, 'Btech’ ,'9541755755' ,64.25)
Insert Into Student Values "Btech’ ,'7878521755' ,95.14)
Insert Into Student Values ( "wrech" , "8224126755" 15.26)
Insert Into Student Values ( "MBA" , "9416094160" ,49.35)
Insert Into Student Values (7, "Pren’, "CA", "9896755741" ,10.36)
Insert Into Student Values (8, "Shashi", "MCA’ , "8896755755" 85.25:
Insert Into Student Values (9, Rishabh’, 'MA’, "7315211111" 52.75
Insert Into Student Values (10, 'Vaibhav' , "BCA" ,'7641236589" , 33.75)
>
Output
Select * from Student
--Insert data into selected colums
Insert Into Student (RolINo,Nane,Class,PhoneNo) Values(11, ‘Anshul', "BCOM’ , "8521478523"
Insert Into Student (Name, PhoneNo,Marks,RolINo) Values( "Rishi, "7412589632" ,85.21, 12)
Insert Into Student (Rol1No,Name,Class,PhoneNo,Marks) Values(13, "Anshul’ , "BCOM’ , "8521478523" , Null)
Insert Into Student Values (10, "Vaibhav’ , "BCA" ,' 7641236589" , 60.75) polis prinary
Insert Into Student Values (16, 'Vaibhav’ , 'BCA’ ,'7641236589" ,79.75)
Output
Select * from Student ———> Seon ae=-For Single column Update
Update Student
Set Nar
lihere RoLIN
Parveen Kumar"
a
Select * fron Student
--For Multiple column update
Update Student
set
Name="Anshul Sharma" ,
Class="McOM" ,
Narks-74.52
lihere Rol1No=11.
Select * from Student
-for Multiple where clause
Update Student
set
Names "Anshul Verma" ,
Class="MCOM",
Marks-64..52
lihere RolINo=11 and Class=""coM’
Select * fron Student
Output
=-Where with OR operator
Update Student
set
Name="Anshul Verma" ,
Class-"NcoM
Marks~64.52
et Secs
=-Delete a row with where
Delete from Student where Rol1No-13. ——————>
Output
Output
-Delete all rows
Delete fron Student
TRUNCATE TABLE dbo. Student ——>
select
Select
Select
Select
Select
Select
* from Student
RolINo, Nane, Class, PhoneNo,Marks from Student
Rol INo, Name, Marks, PhoneNo, Class from Student
RolNo, Nane,Marks fron Student
RolINo, Name, PhoneNo from Student
Name, PhoneNo from Student
OutputRecord insertion again
Insert Into Student Values (1, *Ranbir’, "MoA’, °9992554784",89.25) | on
Insert Into Student Values (2, "Naveen" , ‘MBA’ , '7876755755', 75.75) a Fron
Insert Into Student Values (3, 'Sunil’, 'Btech’, "9541755755" ,64.25) ee cool
Insert Into Student Values (4, 'Rakesh', 'Btech’ ,'7878521755',95.14) s ee
Insert Into Student Values (5, "Sanjay" MTech’ |"8226326755" 15.26) —
Insert Into Student Values (6, "Parveen, "MBA", "9416094160" 49.35) ; een
Insert Into Student Values (7,"Pren", "CA", "9896755741" 10.36) =a
Insert Into Student Values (8, ‘Shashi’, 'MCA', '9896755755' 85.25) Jonasasee
Insert Into Student Values (9, 'Rishabh', 'MA' ,'7315211111' 2.75) 3 Same
Insert Into Student Values (10, 'Vaibhav' ,' BCA" ,'7041236589' 33.75)
Insert Into Student Values (19,'Rishabh Khatri’, 'MA' 7315211100" 59.75)
Insert Into Student Values (13, "Vaibhav Roy *,"@Ca", *8412376589
select * fron student
=-Order by clause Output (order by RollNo/asc) | | Output (order by RollNo desc)
71 order by RollNo & RoLINo ase are sine peices || pee onion
Select * fron Student order by RollNo Sh Soame e Se ee eer lretor ae
Select * fron Student order by RollNo asc | ; sa, St Sina St || P Sis” sf mmm ne
Select * fron Student order by RolINo desc |: Sem, tem mama = || f Ziv i tim ae
Select * from Student order by Name Somer emt sat 2 Sk ee on
Select * fron Student order by Name desc |? Sex wa mmmuas ||: Sy iets comm aa
Select * fron Student order by Marks ee sees |) oe eee
Select * fron Student order by Marks desc | = vomit, mt ame an ||! Moe ter umm ne
Output (order by Name) Output (order by Name desc) Output (order by Marks) est oceania a
oad oes ne
ce Output ( Top 5 (Marks) ‘Output ( Top 3 Marks)
ome se
Select Top 5 * fron Student order by Marks desc | |t~ snr ws’ ose ae
Select Top 3 * fron Student order by Marks desc | { mh MA siencre are HA ez 28
Se + po to on a
=-Operator
SELECT * FROM dbo.Student WHERE RolINo-3 --Equal
SELECT * FROM dbo.Student WHERE RoLINo<>S
Output (where RoliNo=3)
SELECT * from Student where RollNo>S ————> ‘Output (where RollNo>5)
SELECT © fron Student vere RollN6>-5 \. as
‘Output (where RollNo>=5)_ —=
=-Not Equal, >
utat WHERE RaNoos)
Sega cto)
ak ewe
3 Gey oneSELECT * from Student where RollNo<5 ——»| _,Cutput (where RolNoss) ee
BEDE] * Hl stocore gg rotmnoces |
i
:
Select * from Student where RolINo between § and 10>/
SELECT * from Student where RolINo>S and RolINo
= Sand Rao) :
apa tata)
SELECT * from Student where RolINo:
‘and RoLINo<-10)
SELECT * fron Student where RolINo<-5 OR RoLINo,
10 —>|
Lye
if
Insert Into Student Values (15, "Ashish *, "BA" ,'75:
Select * from Student
TPE EEY
3476589" NULL) [>
—eaace
==
Select * from student vhere Marks is NLL —_, "arpummenmmaan] ==
Select * from Student where Marks IS NOT NULL) ———————————+| =o
=-Like Command
SELECT * FROM dbo.Student WHERE Name LIKE ‘RX’ —p) |;
7 where First chanater 1s Rn the Nane colum (RX) | 2
‘uiput where Name Uke A)
coy
SELECT * FROM dbo.Student WHERE Name LIKE 'XR’
Vf were Last charater is R in the lane column (8R)
SELECT * FROM dbo.Student WHERE Name LIKE 'XRX' ——>
// winere charater R/r exists anywnere in the Nane column (XR)
‘Output are Cas Like“)
SELECT * FROM dbo.Student WHERE Class LIKE "CA"
17 where class 4s CA in the Class colum
SELECT * FROM dbo.Student WHERE Class LIKE "CAX'——>| F™Jne oe samme Ten
// séhere First two characters are CA in the Class column (Cx)
up heres Uke Os) ||" Oxo wheres Lhe 3)
SELECT * FROM dbo.Student WHERE Class LIke ‘wea? ———— Ln
71 were last two characters are CA in the Class colunn (¥CA)
SELECT * FROM dbo.Student WHERE Class LIKE "CA" ———p
1/ where characters CA exist anywhere in the Class column (2CA%)
--Wild Cards
SELECT * FROM dbo.Student WHERE Name LIKE 'R mx!) ——————________»
77 uhere First character is Rand third character is m anywhere in
1 Rm (First character is R, second character 15,
SELECT * FROM dbo.Student WHERE Name LI)
so | EE eS
up hore Nae ke Fe}
‘the Name coluon (Rae)
“underscore (single underscore) and third character ism )
‘Ouput where Name Uke $_)
J S_xh (first character is S, second, third & fourth characters are _ —— (
#iFtn character in)
SELECT * FROM doo.Student WHERE Name LI)
‘Output where Name Lke"R_r)
the —— | nts
] eres underscores
and
1 Lb (tre cinch is, Sacre, HHP, Gath RPE NTRS
naar (Fase in inlay oad SST Gr Te ATSELECT * FROM doo.Student WHERE Name LIKE '[A-2]x*§ ————>
7/ whore first character starts fran A to Z in the Name colum)
‘oe nets TT)
SELECT * FROM doo.Student WHERE Name LIKE *(A-K]x"“|_[SC/SS. 6” Ssh st
/] where fist character starts fron Ato K in the Nane collar
‘Output (where Name Like TAZ
SELECT * FROM dbo.Student WHERE Name LIKE '[K-P]%"
U/ where first character starts fron K to P in the Nane colum |
=-Both query will show same result
SELECT * FROM doo.Student WHERE Name LIKE '[aRS]x"| >
7/ where first character starts from A, R, § in the Mane column
‘Oupet where Nome Like [485%
oS Ma Gee
SELECT * FROM dbo.Student WHERE Name LIKE "[SAN]&'—>| "7 )Nnem wax Sunmanss
71 where first character starts from 5,A,N in the Name colunn Sar en em
5 ter Wien atts
‘utp where Name ike SAN)
tire |[ ouput (where Name tke IAIe
ts |] onDeR BY ame
tus |] § Sey Wes ann as
SELECT * FROM dbo.Student WHERE Name LI
7/ where first character starts from S,A,N in the Name column ORDER BY Name
"[SAN]%" ORDER BY Name ——————>| sm tan oatinems um
SELECT * FROM dbo.Student WHERE Name NOT LIKE "[SAN]%" ORDER BY Nane —>|
// NOT LIKE = shore First character 1s Not being started fron S,A,N in the Nane column
(ALL records, except S,A,N as first character in the Name colunn ( ORDER 8Y None
=-Distinct will show not repeated values from 2 column
Select distinct Class from Student >|
‘Output whore Name NOT LKE (SANS)
ORDER Namo)
=-Order by (sorting)
Select * from Student
Select * fron Student order by Name ———>|
Select * fron Student order by Class
‘upet (order by
er eager ee
=-Multiple column sorting
Select Class,Name from Student order by Class ——>
Select Class,Name from Student order by ote
=-Top Conmand
(ER
ouput
SELECT Top 3° from Student where Marks>=49 and Marks<-98 order by Marks desc —p|_* Stam tet soerams =
ouput
SELECT Top 10 percent * from Student where Marks>=4@ and Marks<-98 order by Marks desc—b| [Tryin tex wns oe
SELECT Top 45 percent * from Student where Marks>=8@ ond Marks<-99 onder by Marks desc—p) jst fe caAliase Name
SELECT * FROM dbo. Student
SELECT
RoLINo AS "Roll No",
Name AS "Full Name’
Class AS "Class Name",
PhoneNo AS 'Phone No",
Marks AS ‘Obtaines Marks"
FROM dbo. Student
--2 method
SELECT
RolINo ‘Roll No",
Name "Full Name",
Class ‘Class Nane',
Phone ‘Phone No",
Marks ‘Obtaines Marks’
FROM dbo. student,
=-for changing table name on run time
SELECT * FROM Student as NewTable ——>|
SELECT * FROM Student NewTable
SELECT NewTable.Rol1No, NewTable.Name, NewTable.Class FROM
=-Simple Arithnatic Operation using Select
SELECT (25+52+95°95-98) AS ‘Hello’ >
Student
uput
Select 8254555.2'755456.25 ——>| yg
New?
rable—>|
=-Aggregate Function
Select * fron Student
ouput
Select "Ax(Marks) from Student —>|
eo
Select "X(Marks) as ‘Marks’ from Student —>|
Select MIN(Marks) from Student >|
Select MIN(Marks) from Student
Ouput
our
alter table student add Scholarship int
update Student set Scholarship -2080 where RoLINo=2
update Student set Scholarship -2500 where RollNo-2
update Student set Scholarship -1700 where RolINo-3
update Student set Scholarship -1000 where RollNo=8
update Student set Scholarship -7e0 where RolINo-5
update Student set Scholarship -2780 where RollNo-6
update Student set Scholarship -1680 where RollNo-7
update Student set Scholarship -350 where RolINo-8
update Student set Scholarship ~355@ where RollNo-9
300 where RoLINO=18
update Student set Scholarship -£00 where RolINo-13
update Student set Scholarship -2250 where RollNo-15,
update Student set Scholarship
update Student set Scholarship
update in table (adding Scholarship column in student table)
———
vipat
(ee Plo as Sc
avaae eeups
Select WX(Scholarship) from Student —>| guscannsi
Output
Select MIN(Scholarship) as ‘Scholarship’ fron Student —>|
See
ss
Select SUM(Scholarship) from Student
Select SUM(Scholarship) as ‘Scholarship’ from Student >|
‘put foeaourneh
Select AVG(Scholarship) from Student ———______|
ouput
Select AVG(Scholarship) as ‘Average’ from Student |
ouput
Select COUNT(*) from Student —————* | gestae
11 couns(*) neane total (911) rove in table oxo
Select COUNT(*) as "Total Rows’ fron Student —
Onrout
Select COUNT(*) from Student where Rol1No>S———>| ism nas
// Select * from Student
select —
follNo, F
UPPER(Name) as "Name", :
Upper Class) as "Class", :
Shoe. :
Marks, &
Scholarship :
from Student: &
select
ane,
‘LEN(Name)
fron student |
select
Phone,
LEN PhoneNo) P|
from Student where Len(PhoneNo)<1@ and Len(PhoneNo)>10_
Oxiput
Poetic (No cae ane)
Yr romlt is opty, becte oy phone ramber Ss gover than 58 dgite and lots Than 19 cite
Select >
PhoneNo, Ly
LEN(PhoneNo) as ‘Length"
from Student where Len(PhoneNo)<=2 and Len(PhoneNo)
10
select J) oxo horee nt cast)
shoneto, Poneto (Nocekmn name)
LEN(PhoneNo) 7
fron Student where Len(PhoneNo) <>10
11 © moans not equal, 18 wane not equal of 38
Select (uipet Phoneto not eval f 10) (10)
Name,
PhoneNo,
LEN(PhoneNo) as ‘Length’
from Student where Len(PhoneNo)<>1@
PhoneNo Length
‘753476580 9Select
Nane,
LEN(Name) as ‘Length’
from Student order by LEN(Name) desc
Math Funct: =
ee tie ctumn name)
Select SIN(9e) ——>| (eisssussasseasdas"
Select C0s(45) -
‘ouput
Select TAN(4s) —>] qupammene mamas
Select Log(s2). —————>|
ouput
Select Logi0(s2) >| jq¥paquams nomen up
Sea aaa
Select
CETLING(10,25) ———>|
Select FLOOR(10.51)-»| —
i
Output
SELECT
Select ‘Hello’ , LEN(*Hello" )
Select ‘Hello’ , LEN(*Hello
Select ‘Hello',LEN(* Hello *) >|
Select ‘Hello’, LTRIN(' Hello").
Output
Select ‘Hello’, LEN(LTRIN(' Hello *))->} festenane)_ testa)
Select ‘Hello’, LEN(RTRIN(LTRIN(’ Hello *))) >
Outpt
SELECT SUBSTRING( ‘Aeroplane’ ,3,3)
SELECT SUBSTRING( ‘Aeroplane’ ,3,5)
2. $$
ry
| SSateaseeasasy3"|
==
Oxput
“(Ne column neme),
One
SELECT ASCII(‘A")
(No column nme)
Select ASCII("2")
SELECT
=
aa
SELECT ASCII('0") —>|
seme)
SELECT
ASCIT('9") as ‘ASCCI Value of 9'——I
Ourput
fmenmn ena,
[e-m
ASCE 4°) —————— >|
ouput
(No cotumn name)
i=
ASCH Velwes of 9
ouput
SELECT CAST(1@ AS INT) ——>]
‘onput
i
SELECT
SELECT
CAST(1@ AS DECIMAL (10,2))——»] f
CONVERT (DECIMAL (18,2), 16)———__________,|SELECT a=
RolINo, :
Warks,
CAST(Marks AS DECIMAL(1@,1)),
CONVERT (DECIMAL (18,6), Marks)
FROM dbo. Student
ono
SELECT GerpaTE() ——»| Sagres
‘SELECT CONVERT (DATE, GETDATE()) ——————>| ror
SELECT CONVERT (TIME, GeTDATE()) >| i#saazzeoo
SELECT convert (varchar, getdate(), 100)
Nov 16 2816 6:56pm
mon dd yyy hhinm AM (or Pt) ——p|
out
Ss
SELECT convert(varchar, getdate(), 101) -- mn/dd/yyyy - 13/14/2016 —»
SELECT convert (varchar, getdate(), 102)
SELECT convert (varchar, getdate(), 103)
SELECT convert (varchar, getdate(), 104)
SELECT convert (varchar, getdate(), 105)
SELECT convert (varchar, getdate(), 106)
SELECT convert (varchar, getdate(), 107)
SELECT convert (varchar, getdate(), 108)
SELECT convert (varchar, getdate(), 109)
yyyy.nm.dd - 2026.21.14
d/nn/yyyy ~ 14/21/2016
éd.nn.yyyy
ad-mn-yyyy
dd non yyyy
mon dd, yyy
hnhzin:ss
non dd yyyy hs
Nov 14 2016 7:12:32:023H
m-dd-yyyy
yyyy/nm/dd
yyyyrndd
4d mon yyy hmm: nm
4d Nov 2016 11:62:07:577
hnhsmn:ss:mam(2¢h)
yyyy-am-dd hhsmn:ss (26h)
yyyy-amedd_ hhmn:ss mmm
yyyy-nm-ddThh mn: mmm
SELECT convert(varchar, getdate(), 110)
SELECT convert(varchar, getdate(), 111)
SELECT convert(varchar, getdate(), 112)
SELECT convert(varchar, getdate(), 113)
SELECT convert (varchar, getdate(), 114)
SELECT convert (varchar, getdate(), 120)
SELECT convert (varchar, getdate(), 121)
SELECT convert (varchar, getdate(), 126)
nm AM (or PM)
2016-11-14710:52:47.513
‘SELECT DATEADD (DAY, 5@, GETDATE()) ———____—>
/ today is 14 Novenber 2816, what will be date after 50 days from today
Ouout
{No coh nas)
[aorroras 9505200,
‘SELECT DATEADD(WEEK.,5@, GETDATE ()) ———______________>|
// today is 14 Novenber 2616, what will be date after 0 week from today—>|
ourpu
{econ rome)
2017-10-90 201101 8
SELECT DATEADD(WONTH, 50,GETDATE())—| “Gas cameteay =
// date after S@ week from today | |soarorta07a3007 olen ane
{2086-11-14 202400173
SELECT DATEADD( YEAR, 58,GETOATE() }————_——| SMa
// date after 58 year from today(14 Nov 2016)
SELECT DATEADD(MILLISECOND, 5000, GETDATE()) CS ae
// after 5080 millisecond from now
SELECT DATEADD(MINUTE,50,GETDATE()) - date after 50 minutes from now (14 Nov
‘SELECT DATEADD(HOUR,S®,GETDATE()) - date after S@ hours from now -> [Bae%
SELECT DATEADD (QUARTER, 1, GETOATE()) —————_____________>
17 quarter neans 3 months (1 quarter = 3 months), date after 1 quarter——>|
SELECT DATEDIFF(DAY,GETDATE(),"@13an2017") ~ difference in days fron now(téNovi6) to 1 Jan 2017 (48 days) -> 48
SELECT DATEDIFF (DAY, '@13an2016" , '@13an2017') - days between 1 Jan 2016 to 1 Jan 2017 (366 days) ->
‘SELECT DATEDIFF (WEEKDAY, "@1Jan2016" ,"@1Jan2017") - weekdays between 1 Jan 2016 to 1 Jan 2017 (366 days) ->
OutputSELECT
SELECT
SELECT
SELECT
seect
SELECT
SELECT
SELECT
seLecT
DATEDIFF (DAYOFYEAR, '@1Jan2016" , '@13an2017")
DATEDIFF (DAVOFYEAR, '@1Jan2016" , '@13an2@18" )
DATEDIFF (MONTH, '@13an2016" , *@13an2017" )
DATEDIFF (YEAR, *@13an2016" , ‘@1an2617" )
DATEDIFF (SECOND, '@13an2016" , '@1Jan2017" )
DATEDIFF (MINUTE, '@1Jan2036" , "@19an2017" )
DATEDIFF (HOUR, "@13an2016" , “@1Jan2617")
DATEDIFF (WEEK, "@1Jan2016" , ‘@13an2017" )
DATEDIFF (QUARTER, @13an2@16" , "@1Jan2017")
SELECT * FROM dbo. Student
=-Use to copy data fron One Table to another table
SELECT * INTO StudentTemp FROM dbo. Student
7 copy all data in StudentTenp Table fron Stucent Table
SELECT * FROM dbo. StudentTemp ——————>
TRUNCATE TABLE dbo.StudentTenp - all data deleted of StudentTenp table
SELECT * FROM dbo.StudentTemp
DROP TABLE dbo.Student Temp
~ weekdays between 1 Jan 2016 to 1 Jan 2017 : 366 days
weekdays between 1 Jan 2016 to 1 Jan 2617 : 731 days
- Wonths between 1 Jen 2016 to 4 3an 2017: 42 Honthe
«years betveen 1 Jan 2016 to 4 Jan 2017 4 year
+ seconds between 1 3an 2016 to 1 2an 2017. : 31622400
= ninutes between 1 2an 2016 t0 1 24m 2017. + 527080 wn
Vours between 1 Jan 2016 to 1 Jan 2017: 8786 tears
= Wecks between 1 Jan 2016 to 4 Jan 2017: 52 weeks
= quarters between 1 2an 2016 to 1 Jan 2017 : 4 quarters
i eh ton tenga,
ove
StudentTenp table deleted
SELECT * INTO dbo.StudentTemp FROM dbo.Student WHERE Rol1No-S2541 -> alte Nene Goes Phonstis Mois Suir
7/ no any record inserced because RoLINo 52541 does not exist in table record
SELECT * INTO dbo.StudentTemp FROM dbo.Student WHERE Rol1No>S ——>|
SELECT * FROM dbo. Student
SELECT * FROM doo. StudentTemp
~ all record
~ only record where RoLINo>S
ouput
Union Operator: The UNION operator is used to combine the result set of two or more SELECT statements. Notice that each SELECT
‘tatomont within the UNION must have the samo numer columns. The calurmns must also have similar data typos. Also, the columns in each
SELECT statement must be Inthe same order SELECT cote. aa OMT
Ne eee ae aes by deaut, —sytax—»| Stn mt
Toallow cuiptate vale, use the ALL Keyword wth UNION, SS an ele OMTD
- np
SELECT * FROM dbo. Student ganic terete tear =
‘sTON Pte eet =
SELECT * FROM dbo. StudentTemp i Saas =
// ai distinet record’ by; default ree a x
SELECT * FROM dbo. Student i. 2 GEES as ==
UNION ALL See = & =e
SELECT * FROM dbo. student Temp = S aS
/Aishisce rected) OF lath tale > resird GF Sealant Toba EA aps arten rel] {tfc eee
SELECT * FROM dbo. Student
SELECT * FROM dbo. StudentTenp
up
--For adding a column in table fata ee tity Oy
ALTER TABLE dbo.StudentTenp ADD City VARCHAR(SA) (sty cum sie | [EIPemm 1 Sonim tm NLL
ALTER TABLE dbo.StudentTemp ADO State VARCHAR(S@) j/ctae ctu ssae | $ Sem MA Man tas 2 wk we
SELECT * FROM dbo. student Tenp >] Mate ek un yaFor Increasing size of a colum data type
ALTER TABLE dbo.StudentTemp ALTER COLUMN Name VARCHAR(100)
‘//nou the size of ‘Name? column will be varchar(200), its size was varchar(5@)
For changing the data types
ALTER TABLE dbo.StudentTemp ALTER COLUWN State CHAR(S@)
11 type of “State? column was varchar, now its type will be CHAR
--for deleting a column of a table
ALTER TABLE dbo.StudentTemp DROP COLUMN State
// State column deleted fron StudentTenp table
SELECT * FROM dbo. Student Temp ———_____-__——>)
ouput
DROP TABLE dbo.StudentTemp // StudentTenp table deleted
SELECT * INTO StudentTemp FROM dbo.Student KHERE Rol1No>58254
(// again StusensTonp table crestec bit ro record ir there because Roliko 58254 doos not exict in Student Table
‘Rata Nene Gast howls Mee shale
—w
SELECT * FROM dbo. Student $$
output
Falta None Gem Pl ae Slip
SELECT * FROM dbo. StudentTemp —»|
INSERT INTO StudentTenp Select * FRON Student
7/ ali data of Student table will be copied in StudentTemp table
So output of StudentTenp table will be sane as Student table's output
Select * from Student Temp ———______5
Drop Table StudentTenp // StudentTenp table deleted
SELECT " INTO StudentTemp FROM dbo. Student NHERE Rol1No>5825458
athe Nome Close FroneNo More Schlahip
// again StudentTenp table created but no record is there because RoLlNo SE25458 does not exist An Student Table
--for inserting values in particular colunns
INSERT INTO StudentTenp (Rol1No,Nane,Marks Class, PhoneNo)
Select Rol1No, Name, Marks, Class,PhoneNo FROM Student
SELECT * FROM dbo. StudentTemp
[oli particular recone (Bello, lane Mors, Clase,Pronee) will be ineerteaexcapt other colum
Ourput
HY
#
SELECT * FROM doo. Student
SELECT
create table Country
Class, SUM(Scholarship) FROM dbo.Student GROUP BY Class ———___—>
c
Id int,
Name varchar(5@) Heme.
)
insert
insert
insert
insert
insert
into
into
into
into
into
country
Country
Country
Country
Country
values(1, 'India")
values(2, 'Japan')
values(3, 'US')
values(4, ‘Pakistan’ )
values(S, ‘Australia’ )
* fron Country, ——___________» |
bee
selectcreate table State
(
Id int, ‘Out
Nane varchar(5@), Id Name Countryld
Countryié INT
select * fron State
insert into State values(1, ‘Haryana’ ,'1') Ovout
insert into State values(2, "Rajastan’, '1') 4_ Nome Countrkd
insert into State values(3, ‘Gujrat’, '1") Ina Fenona. |
insert into State values(4, "Punjab", "1" alae
insert into State values(5, "Himachal, '1") afer
insert into State values(6,"MP", '1") 3 mnchat
insert into State values(7,"Tanil' ,"1') oom 4
insert into State values(8, "Jannu’ ,'1 7 Tom 4
insert into State values(9, "UP", '1°) aE
insert into State values(10, "Bihar", ‘1") 2 ou 4
insert into State values(11, ‘Lahore’ 4") 10 Binor
insert into State values(12, 'Florida’,'3") ai eee
insert into State values(13, "Osaka','2') aL
insert into State values(14, 'okinava’ '2") ae
insert into state values(45,"Punjab',"4°) vaustars nan suse] | 14 OMtmm 2
insert into State values(16, ‘Sydney' ,'10") 4 pa
select * fron State . oar
create table city >
c
Id int, L Oost
Name varchar(50), ld Name Stateld
stateld int
) 4
vou
insert into City values(1, itisar’ eet
insert into City velues(2, ‘Hansi',1) (jeer 4
insert into City values(3, 'chandinagar',3) Po vem
insert into City values(4, ‘Amritsar’ ,4) 3 Ghananaper
insert into City values(5, "Kanpur" 9) + porter 4
insert into City values(6, ‘Patna’ 10) 3 tape 9
insert into City values(7, 'Massoori' ,5) © Fare 10
insert into City values(8, ‘Jaipur’ ,2) 7 Meoi 8
insert into City values(9, 'Vellore’,7) 3 sew 2
insert into City values(11,"san andreas’,12)/ | ® wiwe 7
insert into City values(12, "Tokyo" ,13) gy eee
inuert into City valuws(13,?aethen Cityt.20)| | (2a 1
insert into City values(14,"Dacoit’ 12) 1 (piserciy_ 14
insert into City values(15, ‘Karachi ,31) false laT
select * fron City.
select * fron Country on
select * from State
select * fron City
Joins
SQL JOIN Clause is used to merge or conbine two or nore tables
--Inner Join (simple join)
Left Join
Right Join
Full Join
-Self Join
bee eee eee eeg‘SQL Joins are used to combine rows from two or more tables.
INNER JOIN keyword selects all rows from both tables as long as there is a match between the columns in
both tables.
LEFT JOIN keyword returns all rows from left table (tablei), with the matching rows in the right table
(tablez). The result is NULL in the right side when there is no match.
RIGHT JOIN keyword returns all rows from the right table (table2), with the matching rows in the left
table (table1). The result is NULL in the left side when there is no match.
FULL JOIN keyword returns all rows when there is a match in ONE of the tables.
‘The FULL OUTER JOIN keyword returns all rows from the left table (tables) and fron the right table (table2).
‘The FULL OUTER JOIN Keyword combines the result of both LEFT and RIGHT Joins.
SELF JOIN is used to join a table to itself as if the table were two tables temporarily renaming at
least one table in the SQL statement.
SELECT * FROM dbo.Country —____ | wpa
SELECT * FROM dbo. State
=-Inner Join oe
SELECT Country.Name as ‘CountryName’ ,State.Name as 'StateNiane’ =
FROM dbo.Country rNINER JOIN dbo.State ON dbo.Country. 1d-dbo.State.Countryrd oa
order by Country. Name, State.Nane =
put
ena
=-tefe Join
Ce
HHH
(ON dbo.Country. Td-dbo. state.CountryId
|
SELECT Country.Name as "CountryName’,State.Name as 'StateNane” 7
FROM dbo.Country LEFT JOIN dbo.State ON dbo.country.Id-dbo.state.countryid —»| fist”
order by Country.Nane,State.Nane =
=-Right Join
SELECT * FROM dbo.Country Right JOIN dbo.State
‘ON dbo. Country. Td-dbo. State.countryTd
=-Full Join
SELECT * FROM doo.Country Full JOIN dbo. State
‘ON dbo. Country .Id-dbo. State. CountryTd
poversesesie
Select Country Name, Count (State.Name) from Country Left Join State
on Country. Id-State.Countryd group by Country.Name
Select State.Name,Count(City-Name) from State Left join city
on State.Id-City.Stateld group by State.Nane
Select State.Name,Count(City.Name) from State Left join City on
State.Id-City.Stateld group by State.Name having COUNT(City.Name)-@
mhCREATE TABLE Parent
f owen
Id int not null, Af value can’t be null Wd Neme Parenti
Name varchar(18@) not null, —1/ value cat be ull
ParentId int
> I
select*from Parent tre tae tre tr
Tne ate
INSERT INTO Parent VALUES (1, 'Anit’,null) ‘one ee — fat —| ep
INSERT INTO Parent VALUES (2, ‘Rajesh’ ,1) ene __ Poet ‘Rake Mane it fom LL
INSERT INTO Parent VALUES (3, Ankit ".4) cs
INSERT INTO Parent VALUES (4, Nonu’ 2) iat oe
INSERT INTO Parent VALUES (5, "Rajan‘, 3) se soso om
INSERT INTO Parent VALUES (6, Jyoti" ,4) om ee toms
INSERT INTO Parent VALUES (7, Karan’ ,6) $m 3 aN
INSERT INTO Parent VALUES (8, Shiv kumar’, 3) see = momo
INSERT INTO Parent VALUES (9, 'Anit Bansal’ ,4) cons Be LR
INSERT INTO Parent VALUES (10, "Rohit’,5) ‘eiteet uk
AS
Select * from Parent
Select Level1.Nane, Level2.Nane, Level3 Name, Level4.Name, Level5.Nane] aE
‘from Parent Levell fae
Left join Parent Level2 on Level1.Zd-Level2.Parenttd a re OS
Left Join Parent Level3 on Level? Id-Level3 ParentId Bie
Left Join Parent Level4 on Level3.Id-Level4ParentId ed
Left Join Parent LevelS on Level4.Id-Levels.ParentId Srow os
SELECT * FROM dbo. student ed
SELECT Rol1No, Name, Class, PhoneNo, ISWULL (Marks, 9.0) ,Scholarship —— closes
FROM dbo. Student pete ee pa
SELECT * FROM dbo.StudentTemp ———————o (SS : Som ose
SELECT MAX(RO1INo) FROM dbo.StudentTemp — |: Sy Sa s © Sacme oe
SELECT "™X(RolINo)+1 FROM doo.StudentTemp—|| } 2. seme cS
DELETE FROM dbo puters eT “] | Nl ge
Fa Hane Cas Pao Mats Senne
‘SELECT TSNULL(MAX(ROLINo),0)+4 FROM dbo. StudentTemp—>|
Create Table Transactions |
14 uniquetdentifier, co
Date Datetine, L__ | ‘bee Trensconiipe Aoi Die
TransactionType varchar(10@) , _ -
Amount decimal (18,2),
Description varchar 3000)
)
SELECT * FROM dbo. TransactionsInsert
Insert
Insert
Insert
Insert
Insert
Insert
SELECT
SELECT
into Transactions values (NEWID(),'612an2036",, ‘Credit’ 10900, "By Cash’)
into Transactions values (NEWID(),"05Jan2016",, ‘Credit, 5090, ‘By Cheque’
into Transactions values (NEWID(),"@73an2036",, ‘Debit’ ,2000, 'By ATM")
into Transactions values (NEWID(),'@1Feb2036", ‘Debit’ 2000, 'By ATM")
into Transactions values (NEWID(),"25Feb2036" , ‘Debit’ 5000, ‘By Cash’)
into Transactions values (NEWID(),"@2Mar2016" , ‘Debit’ 18080, "Internet Banking’
into Transactions values (NEWID(),"25Feb2016", "Credit 5008, ‘By Cash’)
* FROM dbo. Transactions ——————»| , namie a
aa oeoIeMmM oe ION Hoe
ROAD MMO-SMOM Ot — IO BOme
Tea RenroRESE” axnoe@me oe MM BAM
emaesaEATOIMeRT AmeeemOND oe NO) BH
cman Tees DeIMDN oe STO) Ho
Date,
Description,
(CASE WHEN TransactionType-'Credit’ THEN Amount ELSE NULL END) AS "Credit",
(CASE WHEN TransactionType-'Debit’ THEN Anount ELSE NULL END) AS ‘Debit’
FROM dbo. Transactions ORDER BY Date
Constraints : Rule for Inserting, Updating & Deleting Data
Type of Constraints
Primary Key : Primary Key will not allow to insert duplicate data in @ column,
Unique Key : It is same as Primary Key. itis also not accept duplicate data.
Each table can have a single Primary key.
Primary Key column will not accept Null Value
Each table can have more than one Unique Key.
[Unique Key column can accept a single row with Null Values:
Not Null: This will not accept Null Values in a Column.
Check This will check data before insert or update.
Default IT user not pass data for this type of column then default value will inserted or updated
Create Table StudentSmart
)
select
Insert
Insert
Insert
Insert
Insert
Insert
Insert
Insert
Insert
Select
RoLINo INT PRIMARY KEY, Rolo’ primary key end will not allow duplicate data in RolINo column
Name Varchar(5@) NOT NULL, _//datain Name column cannot be NULL
Class varchar(5@) NOT NULL, // alain Glass column cannot be NULL os
PhoneNio varchar(18) NULL, /datain Class column can be NULL RolNo |Neme Cless PhoneNio Merks
Marks decimal(5,2), =
* fron Studentsmart
Into StudentSmart Values (1, 'Ranbir Nager',, 'MCA' "9992554784", 95.45) /record willbe inserted
Into StudentSmart Values (2, "Ashish *,’MBA', "9999765445", 75.75) 1/ record wile inserted
Into StudentSmart Values (3,NULL, 'Btech" , "9541755755" 64.25)
Tleror-rcord wil not be inserted because Name column caribe NULL
Into StudentSmart Values (3, ‘Sunil’, "Btech’, '9541755755" ,64.25) 1/record willbe nsered
Into StudentSmart Values (3, ‘Sunil’ , "Btech" , '9541755755" ,64.25)
“eot- record vil not be inserted because RolINo column wil nol allow duplicate data (RolNo 3)
Into StudentSmart Values (NULL, "Sunil", "Btech” , 9541755755" ,64.25) ‘/erer- Rae col does nat low ule
Into Studentsmart Values (3, "Sunil" ,NULL, "9541755755" 64.25) ore -Cas coum dos nt alow nas (ainsened)
Into StudentSmart Values (4, Rakesh’ , ‘tech’ ,'7878521755",95.14) record wilbe inserted
Into Student Smart Values (5, 'Sanjay", "MTech" ,'8224126755",15.26) _‘/recordwillbe inserted
* fron StudentSmart————________,] ,ALTER TABLE dbo.StudentSmart ALTER COLUMN Name VARCHAR(5®)
‘mow Name column can take NULL value
Insert Into StudentSmart Values (6, ULL, ‘MTech’ , "9924126756" ,75.26)
Select * from StudentSnart:
ALTER TABLE dbo.StudentSmart ALTER COLUMN Name VARCHAR(S®) NOT NULL
SELECT RoLINo AS "Roll No" ,Name AS "Full Name" Class, PhoneNo
|AS ‘Phone No’ ,Marks, Scholarship FRON dbo. Student WHERE Nane~
1 Name column cannot take Null valve
ae Fens Ce Pate Mae ip
CREATE TABLE StudentResult
RoLINo INT PRIMARY KEY,
Fito Name Fabeame teamed Engst lh SoonShes Scene Nook
Name VARCHAR(5@), *
FatherName VARCHAR (58) ,
NotherNane VARCHAR(5®),
Hindi DECINAL( 10,2),
English DECIMAL(19,2),
Math DECIMAL(10,2),
Socialstudies DECIMAL(1@,2),
Science DECIMAL(10,2),
Moraléducation DECIMAL(10,2)
) =
select * from StudentResult
Insert Into StudentResult
Insert Into StudentResult
Insert Into StudentResult
Insert Into StudentResult
values
values (2, ‘Suni Verma’ “Rajesh Verma", ‘Sneh
values
values (4, "Deep Kunar', ‘Rajan Kumar"
Insert Into StudentResult values
select * fron |
(2, anit Kunar’, ‘Rakesh Kumar’, "Mamta Rani 45.08, 78.00,95.08, 74.00, 96.08,75.00)
75.00, 74.00, 72.00, 47.00, 67.00, 71.08)
(3, "Rahul, "Amit Sharma’ , ‘Anju Rani",74.08,99,08,95.08,71.00,84.00,54.00)
Priya Mittal’ ,72.00,85.08,72.08,77.08, 44.00,72.00)
(5, 'Deepak', ‘Deepanshu Soni", "Radhika Soni, 72.00, 51.00, 66.00, 44.00, 55.00, 49.00)
Noteene
one Fi
Seca
ui
Pista
Despanhu Soni Raila Son
E
6m TO
50 AO
7400 5800
nao #800
T0510
5500 00
m0 7100
$500 7100
no 7100
5300 400
ind Enh ah SocaSudes Scere Median
600
700
m0
400
00
30
70
00
nw
20Select =
Rol1No AS ‘Rol No’
Nane AS "Full Name",
FatherName AS ‘Father Name",
MotherNane AS "Wother Name",
Hindi,
English,
Math,
SocialStudies AS ‘Social Studies’,
Science,
Moraléducation AS ‘Moral Education’,
(Hindi +English+Math+SocialStudies+ScienceMoralEducation) AS "Obtained Marks’,
600.00 AS ‘Total’,
CONVERT (DECIMAL (10,2), ( (Hindi +English+Math sSocialStudies+Science:Moraléducation) *10.00/600.00) )
AS ‘Percentage’,
CASE i caso stated
WHEN CONVERT (DECINAL(20,2), ((Hindi English-Math:Socialstudies/Science:aralEducation)"100.00/690.00))>98.08 20
‘CONVERT (DECIMAL (18,2), ((Hind’-Englishisath:Socialstudies:Science:HoralEducat ion) '100.00/602.0))<-108 THEN "A"
WEN CONVERT DECIMAL (10, 2), ( (Hindi sEnglishiMathsSocialStudies-Science+HoralEducation)*100..00/600.08))>80.00 Ai
‘CONVERT (DECIMAL (18,2), ((Hind’+EnglishsMath:Socialstudies:Science:MoralEducation '100,0/600.00))<-90 THEN
WEN CONVERT DECIMAL (10, 2), ( (Hindi +English:Math+Socialstudies-Science-HoralEducation) *100..00/680.08))>70.0@ AN
‘CONVERT (DECIMAL (10,2), (Hindi English Math:SocialStudies 'Science:MoralEducation "100.09/608.00) )<-80 THEN
EN CONVERT (DECIMAL (10, 2), ( (Hindi EngLish:Math+Socialstudies-Science-HoralEducation) "100.28 /680.08))>60.00 AN
CONVERT (DECIMAL(10,2), ((Hindi English Math: SocialStudies Science MoralEducation)100.00/600.00)).-7® THEN "OD"
WEN CONVERT DECIMAL (10, 2), ( (Hindi +EngLish:Math:Socialstudies-Science+MoralEducation) "108.08 /680.08))>50.@ AND
‘CONVERT (DECIMAL(18,2), ((HindiEngl ish Math;SocialStudies Science MoralEducat ion) '100,@/600.00))<-60 THEN "E"
EN CONVERT DECIMAL (20, 2), ( (Hind: sEng]ishiMathiSocialstudies Sclence+NoralEducation)*100.0/680.08))>40.8@ AND
CONVERT (DECIMAL (10,2), ((Hinds English Math: SocialStudies Science Moraleducation '100.0@/600.00))--5® THEN "F*
NEW CONVERT OECTAAL(28,2), ((Hindi-English-Math-SocialStudies-Sctence-MoralEducatton)*109.00/600.08) )