Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
137 views

Udemy Course Notes: Complete SQL Bootcamp

This document provides a summary of SQL concepts and PostgreSQL examples. It includes a table of contents covering SELECT statements and clauses like DISTINCT, WHERE, LIMIT, IN, ORDER BY, BETWEEN, JOINs and CREATE TABLE. Sections describe each clause in detail and provide PostgreSQL examples for SELECT, DISTINCT ON, WHERE conditions, LIMIT with OFFSET, IN and NOT IN operators, ORDER BY sorting, and BETWEEN ranges. The goal is to break down the complex PostgreSQL SELECT statement into tutorials on each individual clause.

Uploaded by

Zohaib Siddique
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
137 views

Udemy Course Notes: Complete SQL Bootcamp

This document provides a summary of SQL concepts and PostgreSQL examples. It includes a table of contents covering SELECT statements and clauses like DISTINCT, WHERE, LIMIT, IN, ORDER BY, BETWEEN, JOINs and CREATE TABLE. Sections describe each clause in detail and provide PostgreSQL examples for SELECT, DISTINCT ON, WHERE conditions, LIMIT with OFFSET, IN and NOT IN operators, ORDER BY sorting, and BETWEEN ranges. The goal is to break down the complex PostgreSQL SELECT statement into tutorials on each individual clause.

Uploaded by

Zohaib Siddique
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

Udemy Course Notes

Complete SQL
Bootcamp

Table of Contents
SELECT
SELECT DISTINCT
WHERE
PostgreSQL WHERE examples
LIMIT
IN Operator
PostgreSQL IN operator examples
NOT IN Operator
ORDER BY
PostgreSQL ORDER BY examples
BETWEEN
PostgreSQL BETWEEN operator examples
LIKE
GROUP BY
PostgreSQL GROUP BY with SUM function example
HAVING
Example
JOINS
SUBQUERY
CREATE TABLE and Constraints
PostgreSQL column constraints
PostgreSQL table constraints

PostgreSQL CREATE TABLE example

SELECT
Oneofthemostcommontasks,whenyouworkwithPostgreSQL,istoquerydatafrom
tablesbyusingthe
SELECT
statement.The
SELECT
statementisoneofthemost
complexstatementsinPostgreSQL.Ithasmanyclausesthatyoucancombinetoform
apowerfulquery.

Becauseofitscomplexity,wedividethePostgreSQL
SELECT
statementtutorialinto
manyshorttutorialssothatyoucanlearneachclauseofthe
SELECT
statementeasier.
Thefollowingaretheclausesthatappearinthe
SELECT
statement:

SelectdistinctrowsbyusingDISTINCToperator.
FilterrowsbyusingWHEREclause.
SortrowsbyusingtheORDERBYclause.
SelectrowsbasedonvariousoperatorssuchasBETWEEN,INandLIKE.
GrouprowsintogroupsbyusingGROUPBYclause
ApplyconditionforgroupsbyusingHAVINGclause.
JointoanothertablebyusingINNERJOIN,LEFTJOIN,RIGHTJOIN
clauses.

Letsstartwithabasicformofthe
SELECT
statementtoquerydatafromatable.The
followingillustratesthesyntaxofthe
SELECT
statement:

1 SELECTcolumn_1,column_2,
2 FROMtable_name

Letsexaminethe
SELECT
statementinmoredetail:

First,youspecifyalistofcolumnsinthetablefromwhichyouwanttoquery
datainthe
SELECT
clause.Youuseacommabetweeneachcolumnincase
youwanttoquerydatafrommultiplecolumns.Ifyouwanttoquerydata
fromallcolumn,youcanuseanasterisk(*)astheshorthandforall
columns.
Second,youindicatethetablenameafterthe
FROM
keyword

NoticethatSQLlanguageiscaseinsensitive.Itmeansifyouuse
SELECT
or
select
the
effectisthesame.Byconvention,wewilluseSQLkeywordsinuppercasetomakethe
codeeasiertoreadandstandoutclearly.

SELECT DISTINCT
The
DISTINCT
clauseisusedintheSELECTstatementtoremoveduplicaterowsfroma
resultset.The
DISTINCT
clausekeepsonerowforeachgroupofduplicates.Youcan
usethe
DISTINCT
clauseononeormorecolumnsofatable.

Thesyntaxof
DISTINCT
clauseisasfollows:

1 SELECTDISTINCTcolumn_1
2 FROMtable_name

Ifyouspecifymultiplecolumns,the
DISTINCT
clausewillevaluatetheduplicatebased
onthecombinationofvaluesofthosecolumns.

1 SELECTDISTINCTcolumn_1,column_2
2 FROMtbl_name

PostgreSQLalsoprovidesthe
DISTINCTON
(expression)tokeepthefirstrowofeach
groupofduplicateswheretheexpressionisequal.Seethefollowingsyntax:

SELECTDISTINCTON(column_1),column_2

FROMtbl_name

ORDERBYcolumn_1,column_2

Theorderofrowsreturnedfromthe
SELECT
statementisunpredictablethereforethe
firstrowofeachgroupoftheduplicateisalsounpredictable.Itisgoodpracticeto

alwaysusethe
ORDERBY
clausewiththe
DISTINCTON(expression)
tomaketheresult
obvious.

Noticethatthe
DISTINCTON
expressionmustmatchtheleftmostexpressioninthe
ORDERBY
clause.

WHERE
ThesyntaxofthePostgreSQL
WHERE
clauseisasfollows:

1 SELECTcolumn_1,column_2column_n
2 FROMtable_name
3 WHEREconditions

The
WHERE
clauseappearsrightafterthe
FROM
clauseofthe
SELECT
statement.The
conditionsareusedtofiltertherowsreturnedfromthe
SELECT
statement.PostgreSQL
providesyouwithvariousstandardoperatorstoconstructtheconditions.

Thefollowingtableillustratesthestandardcomparisonoperators.

OPERATOR

DESCRIPTION

Equal

>

Greaterthan

<

Lessthan

>=

Greaterthanorequal

<=

Lessthanorequal

<>or!=

Notequal

AND

LogicaloperatorAND

OR

LogicaloperatorOR

Letspracticewithsomeexamplesofusingthe
WHERE
clausewithconditions.

PostgreSQL WHERE examples


Ifyouwanttogetallcustomerswhosefirstnamesare
Jamie
,youcanusethe
WHERE
clausewiththeequal(=)operatorasfollows:

1 SELECTlast_name,first_name
2 FROMcustomer
3 WHEREfirst_name='Jamie'

Ifyouwanttoselectthecustomerwhosefirstnameis
Jamie
andlastnamesis
rice
,you
canusethe
AND
logicaloperatorthatcombinestwoconditionsasthefollowingquery:

1 SELECTlast_name,first_name
2 FROMcustomer

3 WHEREfirst_name='Jamie'AND
4 last_name='Rice'

Ifyouwanttoknowwhopaidtherentalwithamountiseitherlessthan1USDorgreater
than8USD,youcanusethefollowingquerywith
OR
operator:

1 SELECTcustomer_id,amount,payment_date
2 FROMpayment
3 WHEREamount<=1ORamount>=8

LIMIT
PostgreSQLLIMITisusedintheSELECTstatementtogetasubsetofrowsreturnedby
thequery.ThefollowingisthecommonsyntaxoftheLIMITclause:

1 SELECT*
2 FROMTABLE
3 LIMITn

PostgreSQLreturns
n
numberofrowsgeneratedbythequery.If
n
iszeroor
NULL
,it
producestheresultthatissameasomittingthe
LIMIT
clause.

Incaseyouwanttoskipanumberofrowsbeforereturning
n
rows,youuse
OFFSET
clausefollowedbythe
LIMIT
clauseasfollows:

1 SELECT*FROMtable
2 LIMITnOFFSETm

PostgreSQLfirstskips
m
rowsbeforereturningnrowsgeneratedbythequery.Ifmis
zero,PostgreSQLwillbehavelikewithoutthe
OFFSET
clause.

Becausetheorderoftherowsinthedatabasetableisunknownandunpredictable,
whenyouusethe
LIMIT
clause,youshouldalwaysusethe
ORDERBY
clausetocontrol
theorderofrows.Ifyoudontdoso,youwillgetanunpredictableresult.

10

IN Operator
Youusethe
IN
operatorintheWHEREclausetocheckifavaluematchesanyvaluein
alistofvalues.Thesyntaxofthe
IN
operatorisasfollows:

1 valueIN(value1,value2,...)

Theexpressionreturnstrueifthevaluematchesanyvalueinthelisti.e.,value1,
value2,etc.Thelistofvaluesisnotlimitedtoalistofnumbersorstringsbutalsoa
resultsetofa
SELECT
statementasshowninthefollowingquery:

1 valueIN(SELECTvalueFROMtbl_name)

Thestatementinsidetheparenthesesiscalledasubquery,whichisaquerynested
insideanotherquery.

PostgreSQL IN operator examples


Supposeyouwanttoknowtherentalinformationofcustomerid1and2,youcanuse
the
IN
operatorintheWHEREclauseasfollows:

1 SELECTcustomer_id,rental_id,return_date
2 FROMrental
3 WHEREcustomer_idIN(1,2)

11

4 ORDERBYreturn_dateDESC

NOT IN Operator
Youcancombinethe
IN
operatorwiththe
NOT
operatortoselectrowswhosevaluesdo
notmatchthevaluesinthelist.Thefollowingstatementselectsrentalsofcustomers
whosecustomeridisnot1or2.

1 SELECTcustomer_id,rental_id,return_date
2 FROMrental
3 WHEREcustomer_idNOTIN(1,2)

12

ORDER BY
Whenyouquerydatafromatable,PostgreSQLreturnstherowsintheorderthatthey
wereinsertedintothetable.Inordertosorttheresultset,youusethe
ORDERBY
clause
intheSELECTstatement.

The
ORDERBY
clauseallowsyoutosorttherowsreturnedfromthe
SELECT
statementin
ascendingordescendingorderbasedoncriteriaspecifiedbydifferentcriteria.

Thefollowingillustratesthesyntaxofthe
ORDERBY
clause:

1 SELECTcolumn_1,column_2
2 FROMtbl_name
3 ORDERBYcolumn_1ASC,column_2DESC

Letsexaminethesyntaxofthe
ORDERBY
clauseinmoredetail:

Specifythecolumnthatyouwanttosortinthe
ORDERBY
clause.Ifyousort
theresultsetbymultiplecolumns,useacommatoseparatebetweentwo
columns.
Use
ASC
tosorttheresultsetinascendingorderand
DESC
tosorttheresult
setindescendingorder.Ifyouleaveitblank,the
ORDERBY
clausewilluse
ASC
bydefault.

13

LetstakesomeexamplesofusingthePostgreSQL
ORDERBY
clause.

PostgreSQL ORDER BY examples


Thefollowingquerysortscustomersbythefirstnameinascendingorder:

1 SELECTfirst_name,last_name
2 FROMcustomer
3 ORDERBYfirst_nameASC

14

BETWEEN
Weusethe
BETWEEN
operatortomatchavalueagainstarangeofvalues.Thefollowing
illustratesthesyntaxofthe
BETWEEN
operator:

1 valueBETWEENlowANDhigh

Ifthevalueisgreaterthanorequaltothelowvalueandlessthanorequaltothehigh
value,theexpressionreturnstrue,orviceversa.

Wecanrewritethe
BETWEEN
operatorbyusingthegreaterthanorequal(
>=
)orless
thanorequal(
<=
)operatorsasthefollowingstatement:

1 value>=lowandvalue<=high

Ifwewanttocheckifavalueisoutofarange,weusethe
NOTBETWEEN
operatoras
follows:

1 valueNOTBETWEENlowANDhigh

Thefollowingexpressionisequivalenttotheexpressionthatusesthe
NOTBETWEEN
operator:

1 value<lowORvalue>high

WeoftenusetheBETWEEN

operatorintheWHEREclauseofaSELECT,INSERT,
UPDATEorDELETEstatement.

15

PostgreSQL BETWEEN operator examples


Letstakealookatthe
payment
tableinthesampledatabase.

Thefollowingqueryselectsanypaymentwhoseamountisbetween8and9:

1 SELECTcustomer_id,payment_id,amount
2 FROMpayment
3 WHEREamountBETWEEN8AND9

16

LIKE
Supposethestoremanagerasksyoufindacustomerthathedoesnotremember
thenameexactly.Hejustremembersthatcustomersfirstnamebeginswith
somethinglike
Jen
.Howdoyoufindtheexactcustomerthatthestoremanageris
asking?Youmayfindthecustomerinthe
customer
tablebylookingatthefirst
namecolumntoseeifthereisanyvaluethatbeginswith
Jen
.Itiskindoftedious
becausetheremanyrowsinthe
customer
table.

Fortunately,youcanusethePostgreSQL
LIKE
operatortoasthefollowingquery:

1 SELECTfirst_name,last_name
2 FROMcustomer
3 WHEREfirst_nameLIKE'Jen%'

Noticethatthe
WHERE
clausecontainsaspecialexpression:the
first_name
,the
LIKE
operatorandastringthatcontainsapercent
(%
)character,whichisreferredasa
pattern
.
Thequeryreturnsrowswhosevaluesinthefirstnamecolumnbeginwith
Jen
andmay
befollowedbyanysequenceofcharacters.Thistechniqueiscalledpatternmatching.

17

Youconstructapatternbycombiningastringwithwildcardcharactersandusethe
LIKE
or
NOTLIKE
operatortofindthematches.PostgreSQLprovidestwowildcardcharacters:

Percent(
%
)formatchinganysequenceofcharacters.
Underscore(
_
)formatchinganysinglecharacter.

18

GROUP BY
The
GROUPBY
clausedividestherowsreturnedfromtheSELECTstatementinto
groups.Foreachgroup,youcanapplyanaggregatefunctione.g.,tocalculatethesum
ofitemsorcountthenumberofitemsinthegroups.

Thefollowingstatementillustratesthesyntaxofthe
GROUPBY
clause:

1 SELECTcolumn_1,aggregate_function(column_2)
2 FROMtbl_name
3 GROUPBYcolumn_1

The
GROUPBY
clausemustappearrightafterthe
FROM
or
WHERE
clause.Followedby
the
GROUPBY
clauseisonecolumnoralistofcommaseparatedcolumns.Youcanalso
putanexpressioninthe
GROUPBY
clause.

PostgreSQL GROUP BY with SUM function example


The
GROUPBY
clauseisusefulwhenitisusedinconjunctionwithanaggregate
function.Forexample,togethowmuchacustomerhasbeenpaid,youusethe
GROUP
BY
clausetodividethe
payments
tableintogroupsforeachgroup,youcalculatethe

totalamountsofmoneybyusingthe
SUM
functionasthefollowingquery:

19

1 SELECTcustomer_id,
2 SUM(amount)
3 FROMpayment
4 GROUPBYcustomer_id

20

HAVING
Weoftenusethe
HAVING
clauseinconjunctionwiththeGROUPBYclausetofilter
grouprowsthatdonotsatisfyaspecifiedcondition.

Thefollowingstatementillustratesthetypicalsyntaxofthe
HAVING
clause:

1 SELECTcolumn_1,aggregate_function(column_2)
2 FROMtbl_name
3 GROUPBYcolumn_1
4 HAVINGcondition

The
HAVING
clausesetstheconditionforgrouprowscreatedbythe
GROUPBY
clause
afterthe
GROUPBY
clauseapplieswhiletheWHEREclausesetstheconditionfor
individualrowsbefore
GROUPBY
clauseapplies.Thisisthemaindifferencebetweenthe
HAVING
and
WHERE
clauses.

InPostgreSQL,youcanusethe
HAVING
clausewithoutthe
GROUPBY
clause.Inthis
case,the
HAVING
clausewillturnthequeryintoasinglegroup.Inaddition,the
SELECT
listand
HAVING
clausecanonlyrefertocolumnsfromwithinaggregate

functions.Thiskindofqueryreturnsasinglerowiftheconditioninthe
HAVING
clauseis
trueorzerorowifitisfalse.

21

Example
Youcanapplythe
HAVING
clausetoselectstheonlycustomerwhohasbeenspending
morethan
200
asthefollowingquery:

1 SELECTcustomer_id,
2 SUM(amount)
3
4
5

FROMpayment
GROUPBYcustomer_id
HAVINGSUM(amount)>200

22

JOINS
A full review of SQL JOINS is available online here:
https://medium.com/@josemarcialportilla/review-of-sql-joins-ac5463dc71c9#.ayjcuatvj

23

SUBQUERY
Asubqueryisaquerynestedinsideanotherquerysuchas
SELECT,INSERT,DELETE
and
UPDATE
.Inthistutorial,wearefocusingonthe
SELECT
statementonly.

Toconstructasubquery,weputthesecondqueryinbracketsanduseitintheWHERE
clauseasanexpression:

1 SELECTfilm_id,title,rental_rate
2 FROMfilm
3 WHERErental_rate>(
4 SELECTAVG(rental_rate)
5 FROMfilm)

Thequeryinsidethebracketsiscalledasubqueryoraninnerquery.Thequerythat
containsthesubqueryisknownasanouterquery.

PostgreSQLexecutesthequerythatcontainsasubqueryinthefollowingsequence:

First,executesthesubquery.
Second,getstheresultandpassesittotheouterquery.
Third,executestheouterquery.

24

CREATE TABLE and Constraints


TocreateanewtableinPostgreSQL,youusethe
CREATETABLE
statement.The
followingillustratesthesyntaxofthe
CREATETABLE
statement:

1 CREATETABLEtable_name(
2 column_nameTYPEcolumn_constraint,
3 table_constrainttable_constraint
4 )INHERITSexisting_table_name

Letsexaminethesyntaxofthe
CREATETABLE
statementinmoredetail.

First,youspecifythenameofthenewtableafterthe
CREATETABLE
clause.
The
TEMPORARY
keywordisforcreatingatemporarytable,whichwewill
discussinthetemporarytabletutorial.
Next,youlistthecolumnname,itsdatatype,andcolumnconstraint.You
canhavemultiplecolumnsinatable,eachcolumnisseparatedbya
comma(,).Thecolumnconstraintdefinestherulesforthecolumne.g.,
NOTNULL.
Then,afterthecolumnlist,youdefineatablelevelconstraintthatdefines
rulesforthedatainthetable.
Afterthat,youspecifyanexistingtablefromwhichthenewtableinherits.It
meansthenewtablecontainsallcolumnsoftheexistingtableandthe

25

columnsdefinedinthe
CREATETABLE
statement.ThisisaPostgreSQLs
extensiontoSQL.

PostgreSQLcolumnconstraints
ThefollowingarethecommonlyusedcolumnconstraintsinPostgreSQL:

NOTNULLthevalueofthecolumncannotbe
NULL
.
UNIQUEthevalueofthecolumnmustbeuniqueacrossthewholetable.
However,thecolumncanhavemany
NULL
valuesbecausePostgreSQL
treatseach
NULL
valuetobeunique.NoticethatSQLstandardonlyallows
one
NULL
valueinthecolumnthathasthe
UNIQUE
constraint.
PRIMARYKEYthisconstraintisthecombinationof
NOTNULL
and
UNIQUE
constraints.Youcandefineonecolumnas
PRIMARYKEY
byusing

columnlevelconstraint.Incasetheprimarykeycontainsmultiplecolumns,
youmustusethetablelevelconstraint.
CHECKenablestocheckaconditionwhenyouinsertorupdatedata.For
example,thevaluesinthe
price
columnofthe
product
tablemustbe
positivevalues.
REFERENCESconstrainsthevalueofthecolumnthatexistsinacolumn
inanothertable.Youuse
REFERENCES
todefinetheforeignkeyconstraint.

26

PostgreSQL table constraints


Thetableconstraintsaresimilartocolumnconstraintsexceptthattheyareappliedto
theentiretableratherthantoanindividualcolumn.

Thefollowingarethetableconstraints:

UNIQUE(column_list)
toforcethevaluestoredinthecolumnslistedinside
theparenthesestobeunique.
PRIMARYKEY(column_list)
todefinetheprimarykeythatconsistsof
multiplecolumns.
CHECK(condition)
tocheckaconditionwheninsertingorupdatingdata.
REFERENCES
toconstrainthevaluestoredinthecolumnthatmustexistin
acolumninanothertable.

PostgreSQLCREATETABLEexample
Wewillcreateanewtablenamed
account
thathasthefollowingcolumnswiththe
correspondingconstraints:

user_idprimarykey
usernameuniqueandnotnull
passwordnotnull
emailuniqueandnotnull
created_onnotnull

27

last_loginnull

Thefollowingstatementcreatesthe
account
table:

1 CREATETABLEaccount(
2 user_idserialPRIMARYKEY,
3 usernameVARCHAR(50)UNIQUENOTNULL,
4 passwordVARCHAR(50)NOTNULL,
5 emailVARCHAR(355)UNIQUENOTNULL,
6 created_onTIMESTAMPNOTNULL,
7 last_loginTIMESTAMP)

28

You might also like