SlideShare a Scribd company logo
1 of 2
Download to read offline
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
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
• 
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;
Find outthenumberofcities:
SELECT COUNT(rating)
FROM city;
Find outthenumberofcitieswithnon-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;
Find outthetotalpopulationofcitiesinrespectivecountries:
SELECT country_id, AVG(rating)
FROM city
GROUP BY country_id
HAVING AVG(rating)  3.0;
Findouttheaverageratingforcitiesinrespectivecountriesiftheaverageisabove3.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 Cheat.pdf

CS 542 Overview of query processing
CS 542 Overview of query processingCS 542 Overview of query processing
CS 542 Overview of query processingJ Singh
 
Bis 345-final-exam-guide-set-1-new
Bis 345-final-exam-guide-set-1-newBis 345-final-exam-guide-set-1-new
Bis 345-final-exam-guide-set-1-newassignmentcloud85
 
Introduction to structured query language
Introduction to structured query languageIntroduction to structured query language
Introduction to structured query languageHuda Alameen
 
My sql regis_handsonlab
My sql regis_handsonlabMy sql regis_handsonlab
My sql regis_handsonlabsqlhjalp
 
Learning sql from w3schools
Learning sql from w3schoolsLearning sql from w3schools
Learning sql from w3schoolsfarhan516
 
Intro to tsql unit 10
Intro to tsql   unit 10Intro to tsql   unit 10
Intro to tsql unit 10Syed Asrarali
 
ADV Powepoint 3 Lec.pptx
ADV Powepoint 3 Lec.pptxADV Powepoint 3 Lec.pptx
ADV Powepoint 3 Lec.pptxArjayBalberan1
 
Mysqlppt
MysqlpptMysqlppt
MysqlpptReka
 
DBMS_INTRODUCTION OF SQL
DBMS_INTRODUCTION OF SQLDBMS_INTRODUCTION OF SQL
DBMS_INTRODUCTION OF SQLAzizul Mamun
 
Beginers guide for oracle sql
Beginers guide for oracle sqlBeginers guide for oracle sql
Beginers guide for oracle sqlN.Jagadish Kumar
 

Similar to SQL Basic Cheat.pdf (20)

SQL Basics
SQL BasicsSQL Basics
SQL Basics
 
CS 542 Overview of query processing
CS 542 Overview of query processingCS 542 Overview of query processing
CS 542 Overview of query processing
 
Sql for biggner
Sql for biggnerSql for biggner
Sql for biggner
 
Bis 345-final-exam-guide-set-1-new
Bis 345-final-exam-guide-set-1-newBis 345-final-exam-guide-set-1-new
Bis 345-final-exam-guide-set-1-new
 
Introduction to DAX Language
Introduction to DAX LanguageIntroduction to DAX Language
Introduction to DAX Language
 
Sql
SqlSql
Sql
 
Introduction to structured query language
Introduction to structured query languageIntroduction to structured query language
Introduction to structured query language
 
SQL+for+Data+Science.pdf
SQL+for+Data+Science.pdfSQL+for+Data+Science.pdf
SQL+for+Data+Science.pdf
 
Mysqlppt
MysqlpptMysqlppt
Mysqlppt
 
My sql regis_handsonlab
My sql regis_handsonlabMy sql regis_handsonlab
My sql regis_handsonlab
 
Learning sql from w3schools
Learning sql from w3schoolsLearning sql from w3schools
Learning sql from w3schools
 
Sql
SqlSql
Sql
 
Intro to tsql unit 10
Intro to tsql   unit 10Intro to tsql   unit 10
Intro to tsql unit 10
 
ADV Powepoint 3 Lec.pptx
ADV Powepoint 3 Lec.pptxADV Powepoint 3 Lec.pptx
ADV Powepoint 3 Lec.pptx
 
SQL CHEAT SHEET
SQL CHEAT SHEETSQL CHEAT SHEET
SQL CHEAT SHEET
 
JDBC
JDBCJDBC
JDBC
 
Mysqlppt
MysqlpptMysqlppt
Mysqlppt
 
Ch3
Ch3Ch3
Ch3
 
DBMS_INTRODUCTION OF SQL
DBMS_INTRODUCTION OF SQLDBMS_INTRODUCTION OF SQL
DBMS_INTRODUCTION OF SQL
 
Beginers guide for oracle sql
Beginers guide for oracle sqlBeginers guide for oracle sql
Beginers guide for oracle sql
 

Recently uploaded

办理(Vancouver毕业证书)加拿大温哥华岛大学毕业证成绩单原版一比一
办理(Vancouver毕业证书)加拿大温哥华岛大学毕业证成绩单原版一比一办理(Vancouver毕业证书)加拿大温哥华岛大学毕业证成绩单原版一比一
办理(Vancouver毕业证书)加拿大温哥华岛大学毕业证成绩单原版一比一F La
 
PKS-TGC-1084-630 - Stage 1 Proposal.pptx
PKS-TGC-1084-630 - Stage 1 Proposal.pptxPKS-TGC-1084-630 - Stage 1 Proposal.pptx
PKS-TGC-1084-630 - Stage 1 Proposal.pptxPramod Kumar Srivastava
 
GA4 Without Cookies [Measure Camp AMS]
GA4 Without Cookies [Measure Camp AMS]GA4 Without Cookies [Measure Camp AMS]
GA4 Without Cookies [Measure Camp AMS]📊 Markus Baersch
 
办美国阿肯色大学小石城分校毕业证成绩单pdf电子版制作修改#真实留信入库#永久存档#真实可查#diploma#degree
办美国阿肯色大学小石城分校毕业证成绩单pdf电子版制作修改#真实留信入库#永久存档#真实可查#diploma#degree办美国阿肯色大学小石城分校毕业证成绩单pdf电子版制作修改#真实留信入库#永久存档#真实可查#diploma#degree
办美国阿肯色大学小石城分校毕业证成绩单pdf电子版制作修改#真实留信入库#永久存档#真实可查#diploma#degreeyuu sss
 
RadioAdProWritingCinderellabyButleri.pdf
RadioAdProWritingCinderellabyButleri.pdfRadioAdProWritingCinderellabyButleri.pdf
RadioAdProWritingCinderellabyButleri.pdfgstagge
 
NLP Project PPT: Flipkart Product Reviews through NLP Data Science.pptx
NLP Project PPT: Flipkart Product Reviews through NLP Data Science.pptxNLP Project PPT: Flipkart Product Reviews through NLP Data Science.pptx
NLP Project PPT: Flipkart Product Reviews through NLP Data Science.pptxBoston Institute of Analytics
 
Generative AI for Social Good at Open Data Science East 2024
Generative AI for Social Good at Open Data Science East 2024Generative AI for Social Good at Open Data Science East 2024
Generative AI for Social Good at Open Data Science East 2024Colleen Farrelly
 
Top 5 Best Data Analytics Courses In Queens
Top 5 Best Data Analytics Courses In QueensTop 5 Best Data Analytics Courses In Queens
Top 5 Best Data Analytics Courses In Queensdataanalyticsqueen03
 
办理学位证中佛罗里达大学毕业证,UCF成绩单原版一比一
办理学位证中佛罗里达大学毕业证,UCF成绩单原版一比一办理学位证中佛罗里达大学毕业证,UCF成绩单原版一比一
办理学位证中佛罗里达大学毕业证,UCF成绩单原版一比一F sss
 
毕业文凭制作#回国入职#diploma#degree澳洲中央昆士兰大学毕业证成绩单pdf电子版制作修改#毕业文凭制作#回国入职#diploma#degree
毕业文凭制作#回国入职#diploma#degree澳洲中央昆士兰大学毕业证成绩单pdf电子版制作修改#毕业文凭制作#回国入职#diploma#degree毕业文凭制作#回国入职#diploma#degree澳洲中央昆士兰大学毕业证成绩单pdf电子版制作修改#毕业文凭制作#回国入职#diploma#degree
毕业文凭制作#回国入职#diploma#degree澳洲中央昆士兰大学毕业证成绩单pdf电子版制作修改#毕业文凭制作#回国入职#diploma#degreeyuu sss
 
Call Girls in Defence Colony Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Defence Colony Delhi 💯Call Us 🔝8264348440🔝Call Girls in Defence Colony Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Defence Colony Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
INTERNSHIP ON PURBASHA COMPOSITE TEX LTD
INTERNSHIP ON PURBASHA COMPOSITE TEX LTDINTERNSHIP ON PURBASHA COMPOSITE TEX LTD
INTERNSHIP ON PURBASHA COMPOSITE TEX LTDRafezzaman
 
Beautiful Sapna Vip Call Girls Hauz Khas 9711199012 Call /Whatsapps
Beautiful Sapna Vip  Call Girls Hauz Khas 9711199012 Call /WhatsappsBeautiful Sapna Vip  Call Girls Hauz Khas 9711199012 Call /Whatsapps
Beautiful Sapna Vip Call Girls Hauz Khas 9711199012 Call /Whatsappssapnasaifi408
 
Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...
Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...
Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...Sapana Sha
 
From idea to production in a day – Leveraging Azure ML and Streamlit to build...
From idea to production in a day – Leveraging Azure ML and Streamlit to build...From idea to production in a day – Leveraging Azure ML and Streamlit to build...
From idea to production in a day – Leveraging Azure ML and Streamlit to build...Florian Roscheck
 
EMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM TRACKING WITH GOOGLE ANALYTICS.pptx
EMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM  TRACKING WITH GOOGLE ANALYTICS.pptxEMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM  TRACKING WITH GOOGLE ANALYTICS.pptx
EMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM TRACKING WITH GOOGLE ANALYTICS.pptxthyngster
 
办理(UWIC毕业证书)英国卡迪夫城市大学毕业证成绩单原版一比一
办理(UWIC毕业证书)英国卡迪夫城市大学毕业证成绩单原版一比一办理(UWIC毕业证书)英国卡迪夫城市大学毕业证成绩单原版一比一
办理(UWIC毕业证书)英国卡迪夫城市大学毕业证成绩单原版一比一F La
 
dokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.ppt
dokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.pptdokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.ppt
dokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.pptSonatrach
 

Recently uploaded (20)

办理(Vancouver毕业证书)加拿大温哥华岛大学毕业证成绩单原版一比一
办理(Vancouver毕业证书)加拿大温哥华岛大学毕业证成绩单原版一比一办理(Vancouver毕业证书)加拿大温哥华岛大学毕业证成绩单原版一比一
办理(Vancouver毕业证书)加拿大温哥华岛大学毕业证成绩单原版一比一
 
PKS-TGC-1084-630 - Stage 1 Proposal.pptx
PKS-TGC-1084-630 - Stage 1 Proposal.pptxPKS-TGC-1084-630 - Stage 1 Proposal.pptx
PKS-TGC-1084-630 - Stage 1 Proposal.pptx
 
GA4 Without Cookies [Measure Camp AMS]
GA4 Without Cookies [Measure Camp AMS]GA4 Without Cookies [Measure Camp AMS]
GA4 Without Cookies [Measure Camp AMS]
 
办美国阿肯色大学小石城分校毕业证成绩单pdf电子版制作修改#真实留信入库#永久存档#真实可查#diploma#degree
办美国阿肯色大学小石城分校毕业证成绩单pdf电子版制作修改#真实留信入库#永久存档#真实可查#diploma#degree办美国阿肯色大学小石城分校毕业证成绩单pdf电子版制作修改#真实留信入库#永久存档#真实可查#diploma#degree
办美国阿肯色大学小石城分校毕业证成绩单pdf电子版制作修改#真实留信入库#永久存档#真实可查#diploma#degree
 
RadioAdProWritingCinderellabyButleri.pdf
RadioAdProWritingCinderellabyButleri.pdfRadioAdProWritingCinderellabyButleri.pdf
RadioAdProWritingCinderellabyButleri.pdf
 
NLP Project PPT: Flipkart Product Reviews through NLP Data Science.pptx
NLP Project PPT: Flipkart Product Reviews through NLP Data Science.pptxNLP Project PPT: Flipkart Product Reviews through NLP Data Science.pptx
NLP Project PPT: Flipkart Product Reviews through NLP Data Science.pptx
 
E-Commerce Order PredictionShraddha Kamble.pptx
E-Commerce Order PredictionShraddha Kamble.pptxE-Commerce Order PredictionShraddha Kamble.pptx
E-Commerce Order PredictionShraddha Kamble.pptx
 
Generative AI for Social Good at Open Data Science East 2024
Generative AI for Social Good at Open Data Science East 2024Generative AI for Social Good at Open Data Science East 2024
Generative AI for Social Good at Open Data Science East 2024
 
Top 5 Best Data Analytics Courses In Queens
Top 5 Best Data Analytics Courses In QueensTop 5 Best Data Analytics Courses In Queens
Top 5 Best Data Analytics Courses In Queens
 
办理学位证中佛罗里达大学毕业证,UCF成绩单原版一比一
办理学位证中佛罗里达大学毕业证,UCF成绩单原版一比一办理学位证中佛罗里达大学毕业证,UCF成绩单原版一比一
办理学位证中佛罗里达大学毕业证,UCF成绩单原版一比一
 
Deep Generative Learning for All - The Gen AI Hype (Spring 2024)
Deep Generative Learning for All - The Gen AI Hype (Spring 2024)Deep Generative Learning for All - The Gen AI Hype (Spring 2024)
Deep Generative Learning for All - The Gen AI Hype (Spring 2024)
 
毕业文凭制作#回国入职#diploma#degree澳洲中央昆士兰大学毕业证成绩单pdf电子版制作修改#毕业文凭制作#回国入职#diploma#degree
毕业文凭制作#回国入职#diploma#degree澳洲中央昆士兰大学毕业证成绩单pdf电子版制作修改#毕业文凭制作#回国入职#diploma#degree毕业文凭制作#回国入职#diploma#degree澳洲中央昆士兰大学毕业证成绩单pdf电子版制作修改#毕业文凭制作#回国入职#diploma#degree
毕业文凭制作#回国入职#diploma#degree澳洲中央昆士兰大学毕业证成绩单pdf电子版制作修改#毕业文凭制作#回国入职#diploma#degree
 
Call Girls in Defence Colony Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Defence Colony Delhi 💯Call Us 🔝8264348440🔝Call Girls in Defence Colony Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Defence Colony Delhi 💯Call Us 🔝8264348440🔝
 
INTERNSHIP ON PURBASHA COMPOSITE TEX LTD
INTERNSHIP ON PURBASHA COMPOSITE TEX LTDINTERNSHIP ON PURBASHA COMPOSITE TEX LTD
INTERNSHIP ON PURBASHA COMPOSITE TEX LTD
 
Beautiful Sapna Vip Call Girls Hauz Khas 9711199012 Call /Whatsapps
Beautiful Sapna Vip  Call Girls Hauz Khas 9711199012 Call /WhatsappsBeautiful Sapna Vip  Call Girls Hauz Khas 9711199012 Call /Whatsapps
Beautiful Sapna Vip Call Girls Hauz Khas 9711199012 Call /Whatsapps
 
Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...
Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...
Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...
 
From idea to production in a day – Leveraging Azure ML and Streamlit to build...
From idea to production in a day – Leveraging Azure ML and Streamlit to build...From idea to production in a day – Leveraging Azure ML and Streamlit to build...
From idea to production in a day – Leveraging Azure ML and Streamlit to build...
 
EMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM TRACKING WITH GOOGLE ANALYTICS.pptx
EMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM  TRACKING WITH GOOGLE ANALYTICS.pptxEMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM  TRACKING WITH GOOGLE ANALYTICS.pptx
EMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM TRACKING WITH GOOGLE ANALYTICS.pptx
 
办理(UWIC毕业证书)英国卡迪夫城市大学毕业证成绩单原版一比一
办理(UWIC毕业证书)英国卡迪夫城市大学毕业证成绩单原版一比一办理(UWIC毕业证书)英国卡迪夫城市大学毕业证成绩单原版一比一
办理(UWIC毕业证书)英国卡迪夫城市大学毕业证成绩单原版一比一
 
dokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.ppt
dokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.pptdokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.ppt
dokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.ppt
 

SQL Basic Cheat.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
  • 2. 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 • 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; Find outthenumberofcities: SELECT COUNT(rating) FROM city; Find outthenumberofcitieswithnon-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; Find outthetotalpopulationofcitiesinrespectivecountries: SELECT country_id, AVG(rating) FROM city GROUP BY country_id HAVING AVG(rating) 3.0; Findouttheaverageratingforcitiesinrespectivecountriesiftheaverageisabove3.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: