SlideShare a Scribd company logo
Try out the interactive SQL Basics course at LearnSQL.com, and check out our other SQL courses.
LearnSQL.com is owned by Vertabelo SA
vertabelo.com | CC BY-NC-ND Vertabelo SA
SQL Basics Cheat Sheet
SQL,orStructuredQueryLanguage,isalanguagetotalkto
databases.Itallowsyoutoselectspecificdataandtobuild
complexreports.Today,SQLisauniversallanguageofdata.Itis
usedinpracticallyalltechnologiesthatprocessdata.
SQL
SAMPLE DATA
CITY
id name country_id population rating
1 Paris 1 2243000 5
2 Berlin 2 3460000 3
... ... ... ... ...
COUNTRY
id name population area
1 France 66600000 640680
2 Germany 80700000 357000
... ... ... ...
ALIASES
COLUMNS
SELECT name AS city_name
FROM city;
TABLES
SELECT co.name, ci.name
FROM city AS ci
JOIN country AS co
ON ci.country_id = co.id;
QUERYING MULTIPLE TABLES
INNER JOIN
SELECT city.name, country.name
FROM city
[INNER] JOIN country
ON city.country_id = country.id;
CITY
id name country_id
1 Paris 1
2 Berlin 2
3 Warsaw 4
COUNTRY
id name
1 France
2 Germany
3 Iceland
JOIN (or explicitly INNER JOIN) returns rows that have
matching values in both tables.
LEFT JOIN
SELECT city.name, country.name
FROM city
LEFT JOIN country
ON city.country_id = country.id;
CITY
id name country_id
1 Paris 1
2 Berlin 2
3 Warsaw 4
COUNTRY
id name
1 France
2 Germany
NULL NULL
LEFT JOIN returns all rows from the left table with
corresponding rows from the right table. If there's no
matching row, NULLs are returned as values from the second
table.
RIGHT JOIN
SELECT city.name, country.name
FROM city
RIGHT JOIN country
ON city.country_id = country.id;
CITY
id name country_id
1 Paris 1
2 Berlin 2
NULL NULL NULL
COUNTRY
id name
1 France
2 Germany
3 Iceland
RIGHT JOIN returns all rows from the right table with
corresponding rows from the left table. If there's no
matching row, NULLs are returned as values from the left
table.
FULL JOIN
SELECT city.name, country.name
FROM city
FULL [OUTER] JOIN country
ON city.country_id = country.id;
CITY
id name country_id
1 Paris 1
2 Berlin 2
3 Warsaw 4
NULL NULL NULL
COUNTRY
id name
1 France
2 Germany
NULL NULL
3 Iceland
FULL JOIN (or explicitly FULL OUTER JOIN) returns all rows
from both tables – if there's no matching row in the second
table, NULLs are returned.
CITY
country_id id name
6 6 San Marino
7 7 Vatican City
5 9 Greece
10 11 Monaco
COUNTRY
name id
San Marino 6
Vatican City 7
Greece 9
Monaco 10
NATURAL JOIN
SELECT city.name, country.name
FROM city
NATURAL JOIN country;
NATURAL JOIN will join tables by all columns with the same
name.
NATURAL JOIN used these columns to match rows:
city.id, city.name, country.id, country.name
NATURAL JOIN is very rarely used in practice.
CROSS JOIN
SELECT city.name, country.name
FROM city
CROSS JOIN country;
SELECT city.name, country.name
FROM city, country;
CROSS JOIN returns all possible combinations of rows from
both tables. There are two syntaxes available.
CITY
id name country_id
1 Paris 1
1 Paris 1
2 Berlin 2
2 Berlin 2
COUNTRY
id name
1 France
2 Germany
1 France
2 Germany
QUERYING SINGLE TABLE
Fetchallcolumnsfromthecountry table:
SELECT *
FROM country;
Fetchidandnamecolumnsfromthecity table:
SELECT id, name
FROM city;
SELECT name
FROM city
ORDER BY rating DESC;
Fetchcitynamessortedbytherating column
intheDESCendingorder:
SELECT name
FROM city
ORDER BY rating [ASC];
Fetchcitynamessortedbytherating column
inthedefaultASCendingorder:
SELECT name
FROM city
WHERE name LIKE '_ublin';
Fetchnamesofcitiesthatstartwithanyletterfollowedby
'ublin'(like DublininIrelandorLublininPoland):
SELECT name
FROM city
WHERE name != 'Berlin'
AND name != 'Madrid';
FetchnamesofcitiesthatareneitherBerlinnorMadrid:
SELECT name
FROM city
WHERE rating IS NOT NULL;
Fetchnamesofcitiesthatdon'tmissaratingvalue:
SELECT name
FROM city
WHERE country_id IN (1, 4, 7, 8);
FetchnamesofcitiesthatareincountrieswithIDs1,4,7,or8:
FILTERING THE OUTPUT
SELECT name
FROM city
WHERE rating > 3;
Fetchnamesofcitiesthathavearatingabove3:
COMPARISON OPERATORS
SELECT name
FROM city
WHERE name LIKE 'P%'
OR name LIKE '%s';
Fetchnamesofcitiesthatstartwitha'P'orendwithan's':
TEXT OPERATORS
SELECT name
FROM city
WHERE population BETWEEN 500000 AND 5000000;
Fetch names of cities that have a population between
500K and 5M:
OTHER OPERATORS
• 
avg(expr) − average value for rows within the group
• count(expr) − count of values for rows within the group
• max(expr) − maximum value within the group
• min(expr) − minimum value within the group
• sum(expr) − sum of values within the group
AGGREGATE FUNCTIONS
CYCLING
id name country
1 YK DE
2 ZG DE
3 WT PL
... ... ...
SKATING
id name country
1 YK DE
2 DF DE
3 AK PL
... ... ...
AGGREGATION AND GROUPING
GROUP BY groupstogetherrowsthathavethesamevaluesinspecifiedcolumns.
Itcomputessummaries(aggregates)foreachuniquecombinationofvalues.
SUBQUERIES
Asubqueryisaquerythatisnestedinsideanotherquery,orinsideanothersubquery.
There are differenttypesofsubqueries.
SET OPERATIONS
Set operations are used to combine the results of two or more queries into a
single result. The combined queries must return the same number of columns and
compatible data types. The names of the corresponding columns can be different.
CITY
country_id count
1 3
2 3
4 2
CITY
id name country_id
1 Paris 1
101 Marseille 1
102 Lyon 1
2 Berlin 2
103 Hamburg 2
104 Munich 2
3 Warsaw 4
105 Cracow 4
EXAMPLE QUERIES
SELECT COUNT(*)
FROM city;
Findoutthenumberofcities:
SELECT COUNT(rating)
FROM city;
Findoutthenumberofcitieswithnon-nullratings:
SELECT COUNT(DISTINCT country_id)
FROM city;
Find outthenumberofdistinctivecountryvalues:
SELECT MIN(population), MAX(population)
FROM country;
Find outthesmallestandthegreatestcountrypopulations:
SELECT country_id, SUM(population)
FROM city
GROUP BY country_id;
Findoutthetotalpopulationofcitiesinrespectivecountries:
SELECT country_id, AVG(rating)
FROM city
GROUP BY country_id
HAVING AVG(rating)  3.0;
Find outtheaverageratingforcitiesinrespectivecountriesiftheaverageisabove3.0:
UNION
SELECT name
FROM cycling
WHERE country = 'DE'
UNION / UNION ALL
SELECT name
FROM skating
WHERE country = 'DE';
UNION combines the results of two result sets and removes duplicates.
UNION ALL doesn't remove duplicate rows.
This query displays German cyclists together with German skaters:
INTERSECT
SELECT name
FROM cycling
WHERE country = 'DE'
INTERSECT
SELECT name
FROM skating
WHERE country = 'DE';
INTERSECT returns only rows that appear in both result sets.
This query displays German cyclists who are also German skaters at the same time:
EXCEPT
SELECT name
FROM cycling
WHERE country = 'DE'
EXCEPT / MINUS
SELECT name
FROM skating
WHERE country = 'DE';
EXCEPT returns only the rows that appear in the first result set but do not appear
in the second result set.
This query displays German cyclists unless they are also German skaters at the
same time:
SINGLE VALUE
SELECT name FROM city
WHERE rating = (
SELECT rating
FROM city
WHERE name = 'Paris'
);
The simplest subquery returns exactly one column and exactly one row. It can be
used with comparison operators =, , =, , or =.
This query finds cities with the same rating as Paris:
MULTIPLE VALUES
SELECT name
FROM city
WHERE country_id IN (
SELECT country_id
FROM country
WHERE population  20000000
);
Asubquerycanalsoreturnmultiplecolumnsormultiplerows.Suchsubqueriescanbe
usedwithoperatorsIN,EXISTS, ALL,orANY.
Thisqueryfindscitiesincountriesthathaveapopulationabove20M:
CORRELATED
SELECT *
FROM city main_city
WHERE population  (
SELECT AVG(population)
FROM city average_city
WHERE average_city.country_id = main_city.country_id
);
Thisqueryfindscountriesthathaveatleastonecity:
SELECT name
FROM country
WHERE EXISTS (
SELECT *
FROM city
WHERE country_id = country.id
);
Acorrelatedsubqueryreferstothetablesintroducedintheouterquery.Acorrelated
subquerydependsontheouterquery.Itcannotberunindependentlyfromtheouter
query.
Thisqueryfindscitieswithapopulationgreaterthanthe average populationinthe
country:

More Related Content

Similar to sql basic.pdf

Select To Order By
Select  To  Order BySelect  To  Order By
Select To Order By
Krizia Capacio
 
The Ring programming language version 1.10 book - Part 127 of 212
The Ring programming language version 1.10 book - Part 127 of 212The Ring programming language version 1.10 book - Part 127 of 212
The Ring programming language version 1.10 book - Part 127 of 212
Mahmoud Samir Fayed
 
Sql
SqlSql
CS121Lec05.pdf
CS121Lec05.pdfCS121Lec05.pdf
CS121Lec05.pdf
georgejustymirobi1
 
SQL techniques for faster applications
SQL techniques for faster applicationsSQL techniques for faster applications
SQL techniques for faster applications
Connor McDonald
 
ORACLE NOTES
ORACLE NOTESORACLE NOTES
ORACLE NOTES
Sachin Shukla
 
Complete Sql Server querries
Complete Sql Server querriesComplete Sql Server querries
Complete Sql Server querriesIbrahim Jutt
 
Advanced MySQL Query Tuning
Advanced MySQL Query TuningAdvanced MySQL Query Tuning
Advanced MySQL Query Tuning
Alexander Rubin
 
Structured query language functions
Structured query language functionsStructured query language functions
Structured query language functions
Vineeta Garg
 
45 Essential SQL Interview Questions
45 Essential SQL Interview Questions45 Essential SQL Interview Questions
45 Essential SQL Interview Questions
Best SEO Tampa
 
Introduction to DAX Language
Introduction to DAX LanguageIntroduction to DAX Language
Introduction to DAX Language
Antonios Chatzipavlis
 
Introduction to structured query language
Introduction to structured query languageIntroduction to structured query language
Introduction to structured query language
Huda Alameen
 
SQL
SQLSQL

Similar to sql basic.pdf (20)

Select To Order By
Select  To  Order BySelect  To  Order By
Select To Order By
 
The Ring programming language version 1.10 book - Part 127 of 212
The Ring programming language version 1.10 book - Part 127 of 212The Ring programming language version 1.10 book - Part 127 of 212
The Ring programming language version 1.10 book - Part 127 of 212
 
Sql
SqlSql
Sql
 
CS121Lec05.pdf
CS121Lec05.pdfCS121Lec05.pdf
CS121Lec05.pdf
 
SQL Queries .pdf
SQL Queries .pdfSQL Queries .pdf
SQL Queries .pdf
 
SQL techniques for faster applications
SQL techniques for faster applicationsSQL techniques for faster applications
SQL techniques for faster applications
 
Module03
Module03Module03
Module03
 
ORACLE NOTES
ORACLE NOTESORACLE NOTES
ORACLE NOTES
 
Complete Sql Server querries
Complete Sql Server querriesComplete Sql Server querries
Complete Sql Server querries
 
Advanced MySQL Query Tuning
Advanced MySQL Query TuningAdvanced MySQL Query Tuning
Advanced MySQL Query Tuning
 
Mysql1
Mysql1Mysql1
Mysql1
 
Pointer
PointerPointer
Pointer
 
Structured query language functions
Structured query language functionsStructured query language functions
Structured query language functions
 
45 Essential SQL Interview Questions
45 Essential SQL Interview Questions45 Essential SQL Interview Questions
45 Essential SQL Interview Questions
 
Introduction to DAX Language
Introduction to DAX LanguageIntroduction to DAX Language
Introduction to DAX Language
 
Introduction to structured query language
Introduction to structured query languageIntroduction to structured query language
Introduction to structured query language
 
SQL
SQLSQL
SQL
 
Mysql
MysqlMysql
Mysql
 
Mysql
MysqlMysql
Mysql
 
Mysql
MysqlMysql
Mysql
 

More from NiravPanchal50

SQL cheat sheet.pdf
SQL cheat sheet.pdfSQL cheat sheet.pdf
SQL cheat sheet.pdf
NiravPanchal50
 
SQL Short Notes.pdf
SQL Short Notes.pdfSQL Short Notes.pdf
SQL Short Notes.pdf
NiravPanchal50
 
SQL EXCLUSIVE NOTES .pdf
SQL EXCLUSIVE NOTES .pdfSQL EXCLUSIVE NOTES .pdf
SQL EXCLUSIVE NOTES .pdf
NiravPanchal50
 
SQL and DBMS INTERVIEW QUESTIONS .pdf
SQL and DBMS INTERVIEW QUESTIONS .pdfSQL and DBMS INTERVIEW QUESTIONS .pdf
SQL and DBMS INTERVIEW QUESTIONS .pdf
NiravPanchal50
 
SQL Joins.pdf
SQL Joins.pdfSQL Joins.pdf
SQL Joins.pdf
NiravPanchal50
 
𝙅𝙖𝙫𝙖 𝙄𝙣𝙩𝙚𝙧𝙫𝙞𝙚𝙬 𝙌𝙪𝙚𝙨𝙩𝙞𝙤𝙣𝙨 𝙉𝙤𝙩𝙚𝙨.pdf
𝙅𝙖𝙫𝙖 𝙄𝙣𝙩𝙚𝙧𝙫𝙞𝙚𝙬 𝙌𝙪𝙚𝙨𝙩𝙞𝙤𝙣𝙨 𝙉𝙤𝙩𝙚𝙨.pdf𝙅𝙖𝙫𝙖 𝙄𝙣𝙩𝙚𝙧𝙫𝙞𝙚𝙬 𝙌𝙪𝙚𝙨𝙩𝙞𝙤𝙣𝙨 𝙉𝙤𝙩𝙚𝙨.pdf
𝙅𝙖𝙫𝙖 𝙄𝙣𝙩𝙚𝙧𝙫𝙞𝙚𝙬 𝙌𝙪𝙚𝙨𝙩𝙞𝙤𝙣𝙨 𝙉𝙤𝙩𝙚𝙨.pdf
NiravPanchal50
 
Javascript String Methods.pdf
Javascript String Methods.pdfJavascript String Methods.pdf
Javascript String Methods.pdf
NiravPanchal50
 
Java Interview.pdf
Java Interview.pdfJava Interview.pdf
Java Interview.pdf
NiravPanchal50
 
Java Algorithm Interview Questions & Answers .pdf
Java Algorithm Interview Questions & Answers .pdfJava Algorithm Interview Questions & Answers .pdf
Java Algorithm Interview Questions & Answers .pdf
NiravPanchal50
 

More from NiravPanchal50 (9)

SQL cheat sheet.pdf
SQL cheat sheet.pdfSQL cheat sheet.pdf
SQL cheat sheet.pdf
 
SQL Short Notes.pdf
SQL Short Notes.pdfSQL Short Notes.pdf
SQL Short Notes.pdf
 
SQL EXCLUSIVE NOTES .pdf
SQL EXCLUSIVE NOTES .pdfSQL EXCLUSIVE NOTES .pdf
SQL EXCLUSIVE NOTES .pdf
 
SQL and DBMS INTERVIEW QUESTIONS .pdf
SQL and DBMS INTERVIEW QUESTIONS .pdfSQL and DBMS INTERVIEW QUESTIONS .pdf
SQL and DBMS INTERVIEW QUESTIONS .pdf
 
SQL Joins.pdf
SQL Joins.pdfSQL Joins.pdf
SQL Joins.pdf
 
𝙅𝙖𝙫𝙖 𝙄𝙣𝙩𝙚𝙧𝙫𝙞𝙚𝙬 𝙌𝙪𝙚𝙨𝙩𝙞𝙤𝙣𝙨 𝙉𝙤𝙩𝙚𝙨.pdf
𝙅𝙖𝙫𝙖 𝙄𝙣𝙩𝙚𝙧𝙫𝙞𝙚𝙬 𝙌𝙪𝙚𝙨𝙩𝙞𝙤𝙣𝙨 𝙉𝙤𝙩𝙚𝙨.pdf𝙅𝙖𝙫𝙖 𝙄𝙣𝙩𝙚𝙧𝙫𝙞𝙚𝙬 𝙌𝙪𝙚𝙨𝙩𝙞𝙤𝙣𝙨 𝙉𝙤𝙩𝙚𝙨.pdf
𝙅𝙖𝙫𝙖 𝙄𝙣𝙩𝙚𝙧𝙫𝙞𝙚𝙬 𝙌𝙪𝙚𝙨𝙩𝙞𝙤𝙣𝙨 𝙉𝙤𝙩𝙚𝙨.pdf
 
Javascript String Methods.pdf
Javascript String Methods.pdfJavascript String Methods.pdf
Javascript String Methods.pdf
 
Java Interview.pdf
Java Interview.pdfJava Interview.pdf
Java Interview.pdf
 
Java Algorithm Interview Questions & Answers .pdf
Java Algorithm Interview Questions & Answers .pdfJava Algorithm Interview Questions & Answers .pdf
Java Algorithm Interview Questions & Answers .pdf
 

Recently uploaded

一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
bakpo1
 
Final project report on grocery store management system..pdf
Final project report on grocery store management system..pdfFinal project report on grocery store management system..pdf
Final project report on grocery store management system..pdf
Kamal Acharya
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
TeeVichai
 
Hierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power SystemHierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power System
Kerry Sado
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
Kamal Acharya
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
Kamal Acharya
 
WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234
AafreenAbuthahir2
 
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang,  ICLR 2024, MLILAB, KAIST AI.pdfJ.Yang,  ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
MLILAB
 
Runway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptxRunway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptx
SupreethSP4
 
English lab ppt no titlespecENG PPTt.pdf
English lab ppt no titlespecENG PPTt.pdfEnglish lab ppt no titlespecENG PPTt.pdf
English lab ppt no titlespecENG PPTt.pdf
BrazilAccount1
 
Architectural Portfolio Sean Lockwood
Architectural Portfolio Sean LockwoodArchitectural Portfolio Sean Lockwood
Architectural Portfolio Sean Lockwood
seandesed
 
block diagram and signal flow graph representation
block diagram and signal flow graph representationblock diagram and signal flow graph representation
block diagram and signal flow graph representation
Divya Somashekar
 
The Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdfThe Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdf
Pipe Restoration Solutions
 
Planning Of Procurement o different goods and services
Planning Of Procurement o different goods and servicesPlanning Of Procurement o different goods and services
Planning Of Procurement o different goods and services
JoytuBarua2
 
HYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationHYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generation
Robbie Edward Sayers
 
Standard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - NeometrixStandard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - Neometrix
Neometrix_Engineering_Pvt_Ltd
 
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
ydteq
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
thanhdowork
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Sreedhar Chowdam
 
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation & Control
 

Recently uploaded (20)

一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
 
Final project report on grocery store management system..pdf
Final project report on grocery store management system..pdfFinal project report on grocery store management system..pdf
Final project report on grocery store management system..pdf
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
 
Hierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power SystemHierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power System
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
 
WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234
 
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang,  ICLR 2024, MLILAB, KAIST AI.pdfJ.Yang,  ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
 
Runway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptxRunway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptx
 
English lab ppt no titlespecENG PPTt.pdf
English lab ppt no titlespecENG PPTt.pdfEnglish lab ppt no titlespecENG PPTt.pdf
English lab ppt no titlespecENG PPTt.pdf
 
Architectural Portfolio Sean Lockwood
Architectural Portfolio Sean LockwoodArchitectural Portfolio Sean Lockwood
Architectural Portfolio Sean Lockwood
 
block diagram and signal flow graph representation
block diagram and signal flow graph representationblock diagram and signal flow graph representation
block diagram and signal flow graph representation
 
The Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdfThe Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdf
 
Planning Of Procurement o different goods and services
Planning Of Procurement o different goods and servicesPlanning Of Procurement o different goods and services
Planning Of Procurement o different goods and services
 
HYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationHYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generation
 
Standard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - NeometrixStandard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - Neometrix
 
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
 
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
 

sql basic.pdf

  • 1. Try out the interactive SQL Basics course at LearnSQL.com, and check out our other SQL courses. LearnSQL.com is owned by Vertabelo SA vertabelo.com | CC BY-NC-ND Vertabelo SA SQL Basics Cheat Sheet SQL,orStructuredQueryLanguage,isalanguagetotalkto databases.Itallowsyoutoselectspecificdataandtobuild complexreports.Today,SQLisauniversallanguageofdata.Itis usedinpracticallyalltechnologiesthatprocessdata. SQL SAMPLE DATA CITY id name country_id population rating 1 Paris 1 2243000 5 2 Berlin 2 3460000 3 ... ... ... ... ... COUNTRY id name population area 1 France 66600000 640680 2 Germany 80700000 357000 ... ... ... ... ALIASES COLUMNS SELECT name AS city_name FROM city; TABLES SELECT co.name, ci.name FROM city AS ci JOIN country AS co ON ci.country_id = co.id; QUERYING MULTIPLE TABLES INNER JOIN SELECT city.name, country.name FROM city [INNER] JOIN country ON city.country_id = country.id; CITY id name country_id 1 Paris 1 2 Berlin 2 3 Warsaw 4 COUNTRY id name 1 France 2 Germany 3 Iceland JOIN (or explicitly INNER JOIN) returns rows that have matching values in both tables. LEFT JOIN SELECT city.name, country.name FROM city LEFT JOIN country ON city.country_id = country.id; CITY id name country_id 1 Paris 1 2 Berlin 2 3 Warsaw 4 COUNTRY id name 1 France 2 Germany NULL NULL LEFT JOIN returns all rows from the left table with corresponding rows from the right table. If there's no matching row, NULLs are returned as values from the second table. RIGHT JOIN SELECT city.name, country.name FROM city RIGHT JOIN country ON city.country_id = country.id; CITY id name country_id 1 Paris 1 2 Berlin 2 NULL NULL NULL COUNTRY id name 1 France 2 Germany 3 Iceland RIGHT JOIN returns all rows from the right table with corresponding rows from the left table. If there's no matching row, NULLs are returned as values from the left table. FULL JOIN SELECT city.name, country.name FROM city FULL [OUTER] JOIN country ON city.country_id = country.id; CITY id name country_id 1 Paris 1 2 Berlin 2 3 Warsaw 4 NULL NULL NULL COUNTRY id name 1 France 2 Germany NULL NULL 3 Iceland FULL JOIN (or explicitly FULL OUTER JOIN) returns all rows from both tables – if there's no matching row in the second table, NULLs are returned. CITY country_id id name 6 6 San Marino 7 7 Vatican City 5 9 Greece 10 11 Monaco COUNTRY name id San Marino 6 Vatican City 7 Greece 9 Monaco 10 NATURAL JOIN SELECT city.name, country.name FROM city NATURAL JOIN country; NATURAL JOIN will join tables by all columns with the same name. NATURAL JOIN used these columns to match rows: city.id, city.name, country.id, country.name NATURAL JOIN is very rarely used in practice. CROSS JOIN SELECT city.name, country.name FROM city CROSS JOIN country; SELECT city.name, country.name FROM city, country; CROSS JOIN returns all possible combinations of rows from both tables. There are two syntaxes available. CITY id name country_id 1 Paris 1 1 Paris 1 2 Berlin 2 2 Berlin 2 COUNTRY id name 1 France 2 Germany 1 France 2 Germany QUERYING SINGLE TABLE Fetchallcolumnsfromthecountry table: SELECT * FROM country; Fetchidandnamecolumnsfromthecity table: SELECT id, name FROM city; SELECT name FROM city ORDER BY rating DESC; Fetchcitynamessortedbytherating column intheDESCendingorder: SELECT name FROM city ORDER BY rating [ASC]; Fetchcitynamessortedbytherating column inthedefaultASCendingorder: SELECT name FROM city WHERE name LIKE '_ublin'; Fetchnamesofcitiesthatstartwithanyletterfollowedby 'ublin'(like DublininIrelandorLublininPoland): SELECT name FROM city WHERE name != 'Berlin' AND name != 'Madrid'; FetchnamesofcitiesthatareneitherBerlinnorMadrid: SELECT name FROM city WHERE rating IS NOT NULL; Fetchnamesofcitiesthatdon'tmissaratingvalue: SELECT name FROM city WHERE country_id IN (1, 4, 7, 8); FetchnamesofcitiesthatareincountrieswithIDs1,4,7,or8: FILTERING THE OUTPUT SELECT name FROM city WHERE rating > 3; Fetchnamesofcitiesthathavearatingabove3: COMPARISON OPERATORS SELECT name FROM city WHERE name LIKE 'P%' OR name LIKE '%s'; Fetchnamesofcitiesthatstartwitha'P'orendwithan's': TEXT OPERATORS SELECT name FROM city WHERE population BETWEEN 500000 AND 5000000; Fetch names of cities that have a population between 500K and 5M: OTHER OPERATORS • avg(expr) − average value for rows within the group • count(expr) − count of values for rows within the group • max(expr) − maximum value within the group • min(expr) − minimum value within the group • sum(expr) − sum of values within the group AGGREGATE FUNCTIONS CYCLING id name country 1 YK DE 2 ZG DE 3 WT PL ... ... ... SKATING id name country 1 YK DE 2 DF DE 3 AK PL ... ... ... AGGREGATION AND GROUPING GROUP BY groupstogetherrowsthathavethesamevaluesinspecifiedcolumns. Itcomputessummaries(aggregates)foreachuniquecombinationofvalues. SUBQUERIES Asubqueryisaquerythatisnestedinsideanotherquery,orinsideanothersubquery. There are differenttypesofsubqueries. SET OPERATIONS Set operations are used to combine the results of two or more queries into a single result. The combined queries must return the same number of columns and compatible data types. The names of the corresponding columns can be different. CITY country_id count 1 3 2 3 4 2 CITY id name country_id 1 Paris 1 101 Marseille 1 102 Lyon 1 2 Berlin 2 103 Hamburg 2 104 Munich 2 3 Warsaw 4 105 Cracow 4 EXAMPLE QUERIES SELECT COUNT(*) FROM city; Findoutthenumberofcities: SELECT COUNT(rating) FROM city; Findoutthenumberofcitieswithnon-nullratings: SELECT COUNT(DISTINCT country_id) FROM city; Find outthenumberofdistinctivecountryvalues: SELECT MIN(population), MAX(population) FROM country; Find outthesmallestandthegreatestcountrypopulations: SELECT country_id, SUM(population) FROM city GROUP BY country_id; Findoutthetotalpopulationofcitiesinrespectivecountries: SELECT country_id, AVG(rating) FROM city GROUP BY country_id HAVING AVG(rating) 3.0; Find outtheaverageratingforcitiesinrespectivecountriesiftheaverageisabove3.0: UNION SELECT name FROM cycling WHERE country = 'DE' UNION / UNION ALL SELECT name FROM skating WHERE country = 'DE'; UNION combines the results of two result sets and removes duplicates. UNION ALL doesn't remove duplicate rows. This query displays German cyclists together with German skaters: INTERSECT SELECT name FROM cycling WHERE country = 'DE' INTERSECT SELECT name FROM skating WHERE country = 'DE'; INTERSECT returns only rows that appear in both result sets. This query displays German cyclists who are also German skaters at the same time: EXCEPT SELECT name FROM cycling WHERE country = 'DE' EXCEPT / MINUS SELECT name FROM skating WHERE country = 'DE'; EXCEPT returns only the rows that appear in the first result set but do not appear in the second result set. This query displays German cyclists unless they are also German skaters at the same time: SINGLE VALUE SELECT name FROM city WHERE rating = ( SELECT rating FROM city WHERE name = 'Paris' ); The simplest subquery returns exactly one column and exactly one row. It can be used with comparison operators =, , =, , or =. This query finds cities with the same rating as Paris: MULTIPLE VALUES SELECT name FROM city WHERE country_id IN ( SELECT country_id FROM country WHERE population 20000000 ); Asubquerycanalsoreturnmultiplecolumnsormultiplerows.Suchsubqueriescanbe usedwithoperatorsIN,EXISTS, ALL,orANY. Thisqueryfindscitiesincountriesthathaveapopulationabove20M: CORRELATED SELECT * FROM city main_city WHERE population ( SELECT AVG(population) FROM city average_city WHERE average_city.country_id = main_city.country_id ); Thisqueryfindscountriesthathaveatleastonecity: SELECT name FROM country WHERE EXISTS ( SELECT * FROM city WHERE country_id = country.id ); Acorrelatedsubqueryreferstothetablesintroducedintheouterquery.Acorrelated subquerydependsontheouterquery.Itcannotberunindependentlyfromtheouter query. Thisqueryfindscitieswithapopulationgreaterthanthe average populationinthe country: