0% found this document useful (0 votes)
157 views

SQL Zero To Hero

This document provides an overview of common SQL commands and functions. It explains concepts like aliases, grouping, joins, functions, window functions, and more. Examples are provided for most topics to illustrate how they can be used in SQL queries. The key topics covered include SELECT statements, WHERE clauses, GROUP BY, ORDER BY, different types of joins, aggregate functions, and string/date manipulation functions.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
157 views

SQL Zero To Hero

This document provides an overview of common SQL commands and functions. It explains concepts like aliases, grouping, joins, functions, window functions, and more. Examples are provided for most topics to illustrate how they can be used in SQL queries. The key topics covered include SELECT statements, WHERE clauses, GROUP BY, ORDER BY, different types of joins, aggregate functions, and string/date manipulation functions.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

~LIAS -AS

Gtroup
tte1'1in« J
·Ol2Da? BY e!_!j~ l]
d,t DcSC
nt

SQ
ALIAS AS
fxomRle=:
An Alicu is cna.tcd wtfh ·m · l'11e.1onf,
S€LEcT tolu.mn_n4me f\S aliClS-narne
FROM table .. ncimc~

GtROUP Sy
=) (GttooP sy cotuM tJI
E"Kcirnf?!t:
set~CT column_ nomc CS)
FROM tablt_name
WHERe condih·oo
Gtl?.OUP BY Column_~ls)
ORoei BY colamn_na111c cs>;
~ (H4Vin~ J SELECT' colitmn narwirC.I)
- - · FtoM table name
.£-.a.mple. WHera condition
GcRoUP BY col-."'n-namt 00
HA\'l ll<h Condition
OiD!R 8V tolumn...naM&tl);
➔ fORDeR BY (Ase~ or @RDefl By De~
rht order b~ ~wonl i, UJtd to Sort -f"1.
,.,!tllt -Se~ i1'1 o.sttriid in§ o.- dtsetnt!linJ order
E~nmp.k:
Se LECT colwnni, Columna, •••..
F~oM tciblt-no.mt
ORDE~ B'I coluwnni, tolu.rr,,at,, ..... Asc/DtS~

JOINS
:!J [rtJNeR 'J"OIN ]
'this kc~c.uord Selecfl -that- ho.Ve ma•chin§ VAl.w,
i"' boffi ta.Ya
€-ntmple: Setecr columl\_namces>
-== __. ~RoM hb\ei
:tNN£f101N t'Cll>lct
OM table .column_name= blbtcz. column_ narn,,;
_ _ _ _-.
~ ILeFT 101 NJ "
f-.omp le: SE l ecT t.olllmn_namc C.s)
- = fROM ta.blt.1
LEFT'JOIN tal,k '-
➔ ~ IGtHT!OIN]
ftamp,le : S~lecr cola111n-"6tw1e(s)
... ,=i- =-- FRoM ta~le i
RI Gt MT -JOIN ta.l>le ~
ON taliet.coluthn n4mt =- t:able2. cofumn_rnn,;
-
~ 1-
J: U-L.L_ TI>
_I N]
_____

f!4f!lp~ : SeLecr colurm_!la1u. ts)


F~Otll tlblci
Fu LL ouk.r 10,n ta.I.le a,
Ot-l tab~1.Colulfl\1\Clme.~ ~t2. columnvtoma;
WKett: cond1f:fOI\ -
l=UNCT(ONS

~ jAVGi () I Selecr AV& (c1lurm_hOnW


f-ca.mp~ : FROM ta.W.e_ ncune
WHe re- Condi ~iDn ;

9 JSUM n] St:tecr .SUM(CDlumn.. rw.mc)


FRo M blbl~ no.me.
e~o.mpk = wH~et condition i
I
'=9 fCOUNT o SEtecr CPncb1d :co)
~umol~ ~ FROM Ptod.urb;
"=9 (MIN C>} SELECT Mltl (CotiAmn_nome)
FROM table_ name
Eta.mp~ : wHe Re condition;
➔ (MAX O ] Setecr MA>t(tolumn_nami)
f•o.,!!'p.!£. ~ FROM t:al,lt_narru..
WH,ie conditionj
WHE-Re-
=;, [.L.1 l<E-J =9 {:I: N I
fll.O.tn Pcle ~ f,ll~ ple :
.5tLecr cotumni, cou.mt_,.... .Sctccr column_no.rrw.CS)
FROM ~a.blt. _ name. 1=Ro M t-o.blc_nGme
Wttcl?6 CowmnN Ll~S Pattern WHE-Re colutlW\._namt I'tJ
(volut.1. 1 value~, ....);
=tis~-rw~e:N I ➔ [ANY)
~CLmple ~ E(unplc:
SE.t~cT colu.mn_Mme
5etecrrcolurm_nQmt
~o M tClblt _nan,e.
°'
F~oM to.bt~_name WH~Re cowmn_nama,
WHt Rt COltlm n_no.mc B6TWl:eN t: ~TG.to r ~y
\__SetecT cotu.rnn_~
\J4lut1 AfJD4'o.lu.e2.~ FRo M tclbt e_ no.me
=, \f1ists I SetecT colu.mn_no.meCS)
FROM table-name
ho.111p$ = Wttcee tlisis
SeLecr cotumn_no.mc FROM ta1'le-nam,.
wHcRe condi f:ioo),
~ (AL~j Setecr tlLL column_n4meCs)
fta.lllple! FROM toJie...no.me
- LOHtRG condi~on;
-l. [AN D) St tec T Colurnn1., column a, ....
-, P~OM tttble-no.me
t'M.OJl\p.!£_: WHe~& Condi~onj AWOCo nd iti~ AND Crldltfon3 •. .')
{ot 1 5€.te.CT colurrri 'l, colurtlt'I 2.,.....
~ t1. m le· FtoM f:able_nanie
J P • WHt~E- condioni OT condilion~ orcondihiwl3 •... ;
~( NOT) S€L€CT colu.mn:t., Oll1tmn2., •...
f" \ •PROM tab le_ name
tllllfflf2 e • WH t '1 € f..l OT Con di l-i 00 j
TOP J0 S4k C om mands
(must know)
Case when:
Tt allows you to wrtte compleL Conditioral stolcirents
f you want to allocote a cotain vaue or clas depen
-dino' on othet vara bles. Less Comnonly krown, 2t also allows
-ding
you to pirot data.
Select Disiodt:
SeLecT Dp1STINCT isiS Some thino that you hould aluwoy
haye at the back ot e rcbtemuly Common
Use SeECT DICTI stalements with arcfate
functions (wohich is #3)
fumple
SeLECT
CoUNT (order_ id)/ couNT (DISINCT Custona_id) as
0rders Pes cust
ROM
customes_orders
AQÙreÙate tunctions:
Related to Point #tR, you should have strong
wndercBard imÙ of arefate functiong like min, max,
Sum, count, etc., Thií o mean thal you have
Srong undexstanding of the GROUP 'By ard HAvINOY
ClQuse.
Example : Answer
Id Email SeLecT
Email
ab.om FROM
R cod.com Person
a @b.com GtRoUP By
Enail
HAVING
CoUNT Cenail) > 1
Left jont v, îmer Joint
tor those oho aYe velatiely new to SQL or
hove not wsed it in a while, Dt can be ealy o
mix up Left jount and inner jouns. Make &ur you
clearly undert tond, tow each jont derives difel
Tesulfs.
Self qains :
A $aD Self-join jons a table with itsd.
you riht thimk that Serves no purpose, Buf youd
be Swprised at how coron his is. In many real he
Seltnß, Data is storc d in one lare tade rthes than
many snallet tables. In Such Oses, selfjoins may be
Teayikad to Solve uniqu problems,
Eranple:
Name Marojer Jd
Salary
1 Joe foDDD
Hemy Booo0
Som G00DO NULL
Max 40000 NULL
Ansuer
SeLecT
as Employee
a. Name as
PRoM
Employee a a
TOIN Employee as b on o. Maraa TD= b.TA
WHCRE a.Salary > b.Sdlay
Sub querie3:
A Sub qury ,is also known as an iner quany or
a nested ury, is oa query with in a qury and is
embedded in The WHeRe clouse. this is a
to solve unigue problemt that vequiÝte multiple
quois n aequine in oder pradu a fiven out
Come. Gub qyies and wiTH AS Statamerz ave both
hemdy útin ten quorjing so you choud abolt
ely make Bwe that you know how to use -hem.
thern.

Example:
Table: customers. Table. orders Answe
Id Name Id Customo SeLecT
Joe
Name as cuttomers
fROM
3
Heny
Sam
Custo mer
WHeRE
Id NoTINC
SeLecT
Customy Id
ROM Orders
String ormmatting:
string fundtiöns are impotant espeoaly wohen
woskin with data that isnt clearn. Thuk, compani e,
may test yau on Stino fomattinß and mani pula ltön
to make `use that you krow how to
data. manipulate
Strin formatting incdudea thine ike:
"EFT, RIGHT CONCAT
" TRIM " UPPER, LOWER
"PosiTION
COA LESCe
" SUBSTeR

Date - Tine Manipuldlion.


you Should definitely erpect sorme Sort of so
Questons that învolues date- time dala. tor cample
you may be Teguted to roup data by monthe ooY
ioTVert a varidble fomat from DD- MM- Yyyy
to Simply the manih.
Some furcibnt you ehould tra are
" ExTRACT
DATE DIFF
fomle :
IA(INT) Record Date (DATe) Tenperatuxe CINT)
2015- 01- 01 10
Q015- 0|- 02 5
Aol5-Dl - 03
9ol5- o - 0 30

Ansuere
SeLecT
a.Id
FROM
Weather a,
Weather b
WHERe
a.Temperatote> b.Tenperátote
AND DATEDIFF (0.Recovd Dale, b. Recoxd Dat)=1
Window Functions:
Windouw functioo dllouw ybu to perform an aiedte
Value on all 700s, mst eod of relkn ory ne (owCuhicl
is what o GROUP By statenert does). Tts euhremay use a
you want to rank os,caleulte cumulatue Sums,,
and more.
Example
depname empno Salary
develop 5R0D

develop 4200
develo p 4500
develop 8

develop 5 RO0
Personnel 3500
Personnel 3900
Sales 3 H800
Sales
Cales 5000
A80D
Answe
WITH Sal_ rank AS
(SeLECT
empno,
RANKC)oveR (ORDER BY salary Des) Tnk
continuss
FROM
Salaies)
SerecT
empno
FROM
Sal_vank
WHeRe

Union:
As a bonus, ttlo s UNIONI ohile it doecnt Come
up aften, you'l be atked abot this the odd tine
and is Sood to knau) in Qenetal. ff you have to0
tables uwith the Lame coturons and you wat to
Con bine tfom, this is ohen youd ue UNIDN.

You might also like