SlideShare a Scribd company logo
1 of 23
By
Mahir Mahtab Haque
Introduction to SQL
Onboarding
SQL (Structured Query
Language) is the language for
interacting with data stored in
relational databases (a collection
of tables) and is designed exactly
for this purpose. SQL can be used
to create and modify databases.
Query: A request for data from a
database table or a combination
of tables. Querying is an essential
skill for a data scientist.
2
Selecting single columns
• In SQL, you can select data from a table using a SELECT statement. For example: The
following query selects the NAME column from the PEOPLE table:
• In this query, SELECT and FROM are keywords, meaning you can write the same query as:
• But it’s good practice to make SQL keywords uppercase to distinguish them. In addition,
it’s also good practice to include a ‘;’ at the end of your query. This tells SQL where the
end of your query is.
SELECT name
FROM people;
select name
from people;
3
Selecting multiple columns
• In practice, you will often want to select multiple columns. To select
multiple columns from a table, simply separate the column names with
commas. For example: This query selects two columns, NAME and
BIRTHDATE from the PEOPLE table.
• Sometimes you may want to select all columns from a table:
• If you want only to return a certain number of results, you can use the
LIMIT keyword to limit the number of rows returned:
SELECT name, birthdate
FROM people;
SELECT *
FROM people;
SELECT *
FROM people
LIMIT 10; 4
Selecting distinct
• Often your results will include duplicates, so if you want to select
unique/distinct values from a column, use the DISTINCT keyword. For
example: You want to know which languages are represented in the
FILMS table:
SELECT DISTINCT language
FROM films;
5
Learning to count
• What if you want to count the number of employees in your
EMPLOYEES table? Use the keyword COUNT, which will tell you how
many rows are in a table.
• If you want to count the number of non-missing values in a particular
column, you can call COUNT on just that column. For example: To
count the number of BIRTHDATES present in the PEOPLE table:
• It is also common to combine COUNT and DISTINCT for counting the
number of distinct values in a column.
SELECT COUNT(*)
FROM employees;
SELECT COUNT(birthdate)
FROM people;
SELECT COUNT(DISTINCT birthdate)
FROM people; 6
Filtering results (WHERE)
• In SQL, the WHERE keyword allows you to filter based on both text and
numeric values in a table. There are a few different comparison operators
you can use:
• For example: You can filter text records such as title. The following code
returns all films with the title ‘Metropolis’.
• WHERE clause always comes after the FROM statement.
= <> < > <= >=
SELECT title
FROM films
WHERE title = ‘Metropolis’;
7
Filtering results (cont.)
• Often you will want to select data based on multiple conditions. You
can build up your WHERE queries by combining multiple conditions
with the AND keyword.
• This gives you the titles of films released between 1994 and 2000.
SELECT title
FROM films
WHERE release_year > ‘1994’
AND release_year < ‘2000’;
8
Filtering results (cont.)
• What if you want to select rows based on multiple conditions, where
some but not all of the conditions need to be met? For this, SQL has
the OR operator. For example: The following returns all films released
either in 1994 or 2000:
• When combining AND or OR, be sure to enclose the individual clauses
in parentheses:
SELECT title
FROM films
WHERE release_year = ‘1994’
OR release_year = ‘2000’;
SELECT title
FROM films
WHERE (release_year = 1994 OR release_year = 2000)
AND (certification = ‘PG’ OR certification = ‘R’); 9
BETWEEN
• BETWEEN keyword provides a useful shorthand for filtering values
within a specified range.
• It is inclusive which means that the beginning and end values are
included in the results.
SELECT title
FROM films
WHERE release_year >= 1994
AND release_year <= 2000;
SELECT title
FROM films
WHERE release_year
BETWEEN 1994 AND 2000;
10
BETWEEN (cont.)
• The BETWEEN clause can be used with multiple AND and OR
operators, so you can build up your queries and make them even
more powerful!
• For example: Suppose you have a table called KIDS, we can get the
names of all the kids between the ages of 2 and 12 from the United
States.
SELECT name
FROM kids
WHERE age BETWEEN 2 AND 12
AND nationality = ‘USA’;
11
WHERE IN
• If you want to filter based on many conditions, use the IN operator.
• The IN operator allows you to specify multiple values in a WHERE
clause, making it easier and quicker to specify multiple OR conditions.
SELECT name
FROM kids
WHERE age = 2
OR age = 4
OR age = 6
OR age = 8;
SELECT name
FROM kids
WHERE age IN (2, 4, 6, 8);
12
NULL & IS NULL
• In SQL, NULL represents a missing or unknown value. You can check
for null values using the expression IS NULL. For example: To count
the number of missing birth dates in the PEOPLE table:
• IS NULL is useful when combined with WHERE to figure out what data
you are missing. Sometimes you will want to filter out missing values,
so you get only the results which are not null. To do this, you can use
the IS NOT NULL operator.
SELECT COUNT (*)
FROM people
WHERE birthdate IS NULL;
SELECT name
FROM people
WHERE birthdate IS NOT NULL; 13
LIKE & NOT LIKE
• In practice, you will often want to search for a pattern rather than a specific text-string. In SQL,
the LIKE operator can be used in a WHERE clause to search for a pattern in a column. To
accomplish this, you use something called a wildcard as a placeholder for some other values.
There are two wildcards you can use with LIKE:
- ‘%’ This wildcard will match zero, one or many characters in text. For example: The following
query matches companies like ‘Data’, ‘DataC’, ‘DataCamp’, ‘DataMind’ and so on:
- ‘_’ This wildcard match a single character. For example: The following query matches companies
like ‘DataCamp’, ‘DataComp’ and so on:
- You can also use the NOT LIKE operator to find records that don’t match the pattern you specify.
SELECT name
FROM companies
WHERE name LIKE ‘Data%’;
SELECT name
FROM companies
WHERE name LIKE ‘DataC_mp’;
14
Aggregate functions
• Often you will want to perform some calculation on the data in a
database. SQL provides a few functions called ‘aggregate functions’ to
for calculation:
• This gives you the average value from the BUDGET column of the
FILMS table.
• Similarly, the MAX function returns the highest budget:
SELECT AVG(budget)
FROM films;
SELECT MAX(budget)
FROM films;
15
Aggregate functions (cont.)
• The SUM function returns the result of adding up the numeric values
in a column:
• Same goes for MIN function:
• Combining aggregate functions with WHERE: Aggregate functions can
be combined with the WHERE clause to gain insights from the data.
For example: To get the total budget of movies made in the year 2000
or later:
SELECT SUM(budget)
FROM films;
SELECT MIN(budget)
FROM films;
SELECT SUM(budget)
FROM films
WHERE release_year >= 2000;
16
A note on arithmetic & Aliasing
• SELECT (4*3); = 12
• SELECT (4/3); = 1
• If you want more precision when dividing, you can add decimal places
to your numbers. For example: SELECT (4.0/3.0) AS result; = 1.333
• Aliasing: You assign a temporary name to something. To alias, you use
the AS keyword, which makes it readable. For example:
SELECT MAX(budget) AS MAX_budget,
MAX(duration) AS MAX_duration
FROM films;
17
Aliasing (cont.)
• SQL assumes that if you divide an integer by another integer, you want to
get an integer back. This means that the following will erroneously result in
400.0:
• This is because 45/10 evaluates to an integer 4, and not a decimal number
like we would expect. So, when you are dividing make sure at least one of
your numbers has a decimal place:
• The above now gives the current answer of 450.0, since the numerator
(45*100.0) of the division.
SELECT 45/10*100.0;
SELECT
45*100.0/10.0;
18
ORDER BY
• In SQL, the ORDER BY keyword is used to sort results in ascending or
descending order according to the values of one of more columns. By
default, ORDER BY will sort in ascending order but if you want to sort
the results in descending order, you use the DESC keyword. For
example: The query gives you the titles of films by release year from
newest to oldest.
• ORDER BY can also be used to sort on multiple columns. It will sort by
the first column specified, then sort by the next and so on. For
example:
SELECT title
FROM films
ORDER BY release_year DESC;
SELECT birthdate, name
FROM people
ORDER BY birthdate, name;
19
GROUP BY
• You might want to count the number of male and female employees
in your company. Here, what you want is to group all the males
together and count them, and same goes for all the females.
• In SQL, GROUP BY allows you to group a result by one or more
columns:
• Commonly, GROUP BY is used with aggregate functions like COUNT()
and MAX().
• Note: GROUP BY always comes after FROM clause.
SELECT sex, count(*)
FROM employees
GROUP BY sex;
20
GROUP BY (cont.)
• SQL will return an error if you try to SELECT a field that is not in your
GROUP BY clause without using it calculate some kind of value about
the entire group.
• Note: You can combine GROUP BY with ORDER BY to group your
results, calculate something about them and then order your results.
• ORDER BY always comes after GROUP BY, even after HAVING.
SELECT sex, count(*)
FROM employees
GROUP BY sex
ORDER BY count DESC;
21
HAVING
• In SQL, aggregate functions cannot be used in WHERE clauses. For
example: The following query is invalid.
• Thus, if you want to filter based on the result of an aggregate function, you
need the HAVING clause.
• This shows only those years in which more than 10 films were released.
SELECT release_year
FROM films
GROUP BY release_year
WHERE COUNT(title) > 10;
SELECT release_year
FROM films
GROUP BY release_year
HAVING COUNT(title) > 10;
22
JOIN
• You want to get the ID of the movie from the FILMS table and then use it to get the IMDB information
from the REVIEWS table. In SQL, this concept is known as JOIN.
• For example:
SELECT title, imdb_score
FROM films
JOIN reviews
ON films.id = reviews.film_id
WHERE title = ‘To kill a mockingbird’;
23

More Related Content

What's hot

Database Assignment
Database AssignmentDatabase Assignment
Database AssignmentJayed Imran
 
Sql notes, sql server,sql queries,introduction of SQL, Beginner in SQL
Sql notes, sql server,sql queries,introduction of SQL, Beginner in SQLSql notes, sql server,sql queries,introduction of SQL, Beginner in SQL
Sql notes, sql server,sql queries,introduction of SQL, Beginner in SQLPrashant Kumar
 
SQL select statement and functions
SQL select statement and functionsSQL select statement and functions
SQL select statement and functionsVikas Gupta
 
Tableau Visual analytics complete deck 2
Tableau Visual analytics complete deck 2Tableau Visual analytics complete deck 2
Tableau Visual analytics complete deck 2Arun K
 
SQL practice questions - set 3
SQL practice questions - set 3SQL practice questions - set 3
SQL practice questions - set 3Mohd Tousif
 
Power BI: Types of gateways in Power BI
Power BI: Types of gateways in Power BIPower BI: Types of gateways in Power BI
Power BI: Types of gateways in Power BIAmit Kumar ☁
 
joins and subqueries in big data analysis
joins and subqueries in big data analysisjoins and subqueries in big data analysis
joins and subqueries in big data analysisSanSan149
 
Data visualisation & analytics with Tableau
Data visualisation & analytics with Tableau Data visualisation & analytics with Tableau
Data visualisation & analytics with Tableau Outreach Digital
 
Oracle Course
Oracle CourseOracle Course
Oracle Courserspaike
 
Data Manipulation Language
Data Manipulation LanguageData Manipulation Language
Data Manipulation LanguageJas Singh Bhasin
 
Relational Data Model Introduction
Relational Data Model IntroductionRelational Data Model Introduction
Relational Data Model IntroductionNishant Munjal
 
Tableau online training
Tableau online trainingTableau online training
Tableau online trainingsuresh
 
Query evaluation and optimization
Query evaluation and optimizationQuery evaluation and optimization
Query evaluation and optimizationlavanya marichamy
 

What's hot (20)

Database Assignment
Database AssignmentDatabase Assignment
Database Assignment
 
Sql notes, sql server,sql queries,introduction of SQL, Beginner in SQL
Sql notes, sql server,sql queries,introduction of SQL, Beginner in SQLSql notes, sql server,sql queries,introduction of SQL, Beginner in SQL
Sql notes, sql server,sql queries,introduction of SQL, Beginner in SQL
 
Oracle Database Sequence
Oracle Database SequenceOracle Database Sequence
Oracle Database Sequence
 
SQL select statement and functions
SQL select statement and functionsSQL select statement and functions
SQL select statement and functions
 
Sql commands
Sql commandsSql commands
Sql commands
 
Dml and ddl
Dml and ddlDml and ddl
Dml and ddl
 
Tableau Visual analytics complete deck 2
Tableau Visual analytics complete deck 2Tableau Visual analytics complete deck 2
Tableau Visual analytics complete deck 2
 
Transaction Processing in DBMS.pptx
Transaction Processing in DBMS.pptxTransaction Processing in DBMS.pptx
Transaction Processing in DBMS.pptx
 
SQL practice questions - set 3
SQL practice questions - set 3SQL practice questions - set 3
SQL practice questions - set 3
 
Power BI: Types of gateways in Power BI
Power BI: Types of gateways in Power BIPower BI: Types of gateways in Power BI
Power BI: Types of gateways in Power BI
 
joins and subqueries in big data analysis
joins and subqueries in big data analysisjoins and subqueries in big data analysis
joins and subqueries in big data analysis
 
Dbms lab questions
Dbms lab questionsDbms lab questions
Dbms lab questions
 
Data visualisation & analytics with Tableau
Data visualisation & analytics with Tableau Data visualisation & analytics with Tableau
Data visualisation & analytics with Tableau
 
SQL Views
SQL ViewsSQL Views
SQL Views
 
Oracle Course
Oracle CourseOracle Course
Oracle Course
 
Data Manipulation Language
Data Manipulation LanguageData Manipulation Language
Data Manipulation Language
 
Relational Data Model Introduction
Relational Data Model IntroductionRelational Data Model Introduction
Relational Data Model Introduction
 
Join sql
Join sqlJoin sql
Join sql
 
Tableau online training
Tableau online trainingTableau online training
Tableau online training
 
Query evaluation and optimization
Query evaluation and optimizationQuery evaluation and optimization
Query evaluation and optimization
 

Similar to Introduction to SQL

Beginers guide for oracle sql
Beginers guide for oracle sqlBeginers guide for oracle sql
Beginers guide for oracle sqlN.Jagadish Kumar
 
FOUNDATION OF DATA SCIENCE SQL QUESTIONS
FOUNDATION OF DATA SCIENCE SQL QUESTIONSFOUNDATION OF DATA SCIENCE SQL QUESTIONS
FOUNDATION OF DATA SCIENCE SQL QUESTIONSHITIKAJAIN4
 
Subqueries, Backups, Users and Privileges
Subqueries, Backups, Users and PrivilegesSubqueries, Backups, Users and Privileges
Subqueries, Backups, Users and PrivilegesAshwin Dinoriya
 
Intro to T-SQL – 2nd session
Intro to T-SQL – 2nd sessionIntro to T-SQL – 2nd session
Intro to T-SQL – 2nd sessionMedhat Dawoud
 
Chinabankppt
ChinabankpptChinabankppt
Chinabankpptnewrforce
 
Data Base Management System Lecture 10.pdf
Data Base Management System Lecture 10.pdfData Base Management System Lecture 10.pdf
Data Base Management System Lecture 10.pdfhowto4ucontact
 
Data Exploration with Apache Drill: Day 2
Data Exploration with Apache Drill: Day 2Data Exploration with Apache Drill: Day 2
Data Exploration with Apache Drill: Day 2Charles Givre
 
The ultimate-guide-to-sql
The ultimate-guide-to-sqlThe ultimate-guide-to-sql
The ultimate-guide-to-sqlMcNamaraChiwaye
 
The ultimate-guide-to-sql
The ultimate-guide-to-sqlThe ultimate-guide-to-sql
The ultimate-guide-to-sqlMcNamaraChiwaye
 
Basic SQL Statments
Basic SQL StatmentsBasic SQL Statments
Basic SQL StatmentsUmair Shakir
 
SQL Lesson 6 - Select.pdf
SQL Lesson 6 - Select.pdfSQL Lesson 6 - Select.pdf
SQL Lesson 6 - Select.pdfMadhusha15
 
SQL Notes
SQL NotesSQL Notes
SQL Notesmitmak
 
Introduction to SQL (for Chicago Booth MBA technology club)
Introduction to SQL (for Chicago Booth MBA technology club)Introduction to SQL (for Chicago Booth MBA technology club)
Introduction to SQL (for Chicago Booth MBA technology club)Jennifer Berk
 

Similar to Introduction to SQL (20)

Sql 2006
Sql 2006Sql 2006
Sql 2006
 
Beginers guide for oracle sql
Beginers guide for oracle sqlBeginers guide for oracle sql
Beginers guide for oracle sql
 
FOUNDATION OF DATA SCIENCE SQL QUESTIONS
FOUNDATION OF DATA SCIENCE SQL QUESTIONSFOUNDATION OF DATA SCIENCE SQL QUESTIONS
FOUNDATION OF DATA SCIENCE SQL QUESTIONS
 
012. SQL.pdf
012. SQL.pdf012. SQL.pdf
012. SQL.pdf
 
Subqueries, Backups, Users and Privileges
Subqueries, Backups, Users and PrivilegesSubqueries, Backups, Users and Privileges
Subqueries, Backups, Users and Privileges
 
Intro to T-SQL – 2nd session
Intro to T-SQL – 2nd sessionIntro to T-SQL – 2nd session
Intro to T-SQL – 2nd session
 
Chinabankppt
ChinabankpptChinabankppt
Chinabankppt
 
Data Base Management System Lecture 10.pdf
Data Base Management System Lecture 10.pdfData Base Management System Lecture 10.pdf
Data Base Management System Lecture 10.pdf
 
75864 sql
75864 sql75864 sql
75864 sql
 
SQL
SQLSQL
SQL
 
Sql
SqlSql
Sql
 
Data Exploration with Apache Drill: Day 2
Data Exploration with Apache Drill: Day 2Data Exploration with Apache Drill: Day 2
Data Exploration with Apache Drill: Day 2
 
The ultimate-guide-to-sql
The ultimate-guide-to-sqlThe ultimate-guide-to-sql
The ultimate-guide-to-sql
 
The ultimate-guide-to-sql
The ultimate-guide-to-sqlThe ultimate-guide-to-sql
The ultimate-guide-to-sql
 
Basic SQL Statments
Basic SQL StatmentsBasic SQL Statments
Basic SQL Statments
 
SQL Lesson 6 - Select.pdf
SQL Lesson 6 - Select.pdfSQL Lesson 6 - Select.pdf
SQL Lesson 6 - Select.pdf
 
SQL- Introduction to MySQL
SQL- Introduction to MySQLSQL- Introduction to MySQL
SQL- Introduction to MySQL
 
SQL Notes
SQL NotesSQL Notes
SQL Notes
 
Sql basics
Sql  basicsSql  basics
Sql basics
 
Introduction to SQL (for Chicago Booth MBA technology club)
Introduction to SQL (for Chicago Booth MBA technology club)Introduction to SQL (for Chicago Booth MBA technology club)
Introduction to SQL (for Chicago Booth MBA technology club)
 

More from Mahir Haque

Principles of marketing 15th Edition
Principles of marketing 15th Edition Principles of marketing 15th Edition
Principles of marketing 15th Edition Mahir Haque
 
JOINING with SQL
JOINING with SQLJOINING with SQL
JOINING with SQLMahir Haque
 
Introduction to data science
Introduction to data scienceIntroduction to data science
Introduction to data scienceMahir Haque
 
Marketing analytics
Marketing analyticsMarketing analytics
Marketing analyticsMahir Haque
 
Marketing in a Digital World
Marketing in a Digital WorldMarketing in a Digital World
Marketing in a Digital WorldMahir Haque
 
Fundamentals of Digital Marketing
Fundamentals of Digital MarketingFundamentals of Digital Marketing
Fundamentals of Digital MarketingMahir Haque
 
Global Exchange Rate Arrangements
Global Exchange Rate ArrangementsGlobal Exchange Rate Arrangements
Global Exchange Rate ArrangementsMahir Haque
 
Operations management of IKEA
Operations management of IKEAOperations management of IKEA
Operations management of IKEAMahir Haque
 
John F. Kennedy (Leadership style)
John F. Kennedy (Leadership style)John F. Kennedy (Leadership style)
John F. Kennedy (Leadership style)Mahir Haque
 

More from Mahir Haque (9)

Principles of marketing 15th Edition
Principles of marketing 15th Edition Principles of marketing 15th Edition
Principles of marketing 15th Edition
 
JOINING with SQL
JOINING with SQLJOINING with SQL
JOINING with SQL
 
Introduction to data science
Introduction to data scienceIntroduction to data science
Introduction to data science
 
Marketing analytics
Marketing analyticsMarketing analytics
Marketing analytics
 
Marketing in a Digital World
Marketing in a Digital WorldMarketing in a Digital World
Marketing in a Digital World
 
Fundamentals of Digital Marketing
Fundamentals of Digital MarketingFundamentals of Digital Marketing
Fundamentals of Digital Marketing
 
Global Exchange Rate Arrangements
Global Exchange Rate ArrangementsGlobal Exchange Rate Arrangements
Global Exchange Rate Arrangements
 
Operations management of IKEA
Operations management of IKEAOperations management of IKEA
Operations management of IKEA
 
John F. Kennedy (Leadership style)
John F. Kennedy (Leadership style)John F. Kennedy (Leadership style)
John F. Kennedy (Leadership style)
 

Recently uploaded

Top profile Call Girls In Vadodara [ 7014168258 ] Call Me For Genuine Models ...
Top profile Call Girls In Vadodara [ 7014168258 ] Call Me For Genuine Models ...Top profile Call Girls In Vadodara [ 7014168258 ] Call Me For Genuine Models ...
Top profile Call Girls In Vadodara [ 7014168258 ] Call Me For Genuine Models ...gajnagarg
 
Predicting HDB Resale Prices - Conducting Linear Regression Analysis With Orange
Predicting HDB Resale Prices - Conducting Linear Regression Analysis With OrangePredicting HDB Resale Prices - Conducting Linear Regression Analysis With Orange
Predicting HDB Resale Prices - Conducting Linear Regression Analysis With OrangeThinkInnovation
 
Top profile Call Girls In Begusarai [ 7014168258 ] Call Me For Genuine Models...
Top profile Call Girls In Begusarai [ 7014168258 ] Call Me For Genuine Models...Top profile Call Girls In Begusarai [ 7014168258 ] Call Me For Genuine Models...
Top profile Call Girls In Begusarai [ 7014168258 ] Call Me For Genuine Models...nirzagarg
 
Jodhpur Park | Call Girls in Kolkata Phone No 8005736733 Elite Escort Service...
Jodhpur Park | Call Girls in Kolkata Phone No 8005736733 Elite Escort Service...Jodhpur Park | Call Girls in Kolkata Phone No 8005736733 Elite Escort Service...
Jodhpur Park | Call Girls in Kolkata Phone No 8005736733 Elite Escort Service...HyderabadDolls
 
Nirala Nagar / Cheap Call Girls In Lucknow Phone No 9548273370 Elite Escort S...
Nirala Nagar / Cheap Call Girls In Lucknow Phone No 9548273370 Elite Escort S...Nirala Nagar / Cheap Call Girls In Lucknow Phone No 9548273370 Elite Escort S...
Nirala Nagar / Cheap Call Girls In Lucknow Phone No 9548273370 Elite Escort S...HyderabadDolls
 
Gartner's Data Analytics Maturity Model.pptx
Gartner's Data Analytics Maturity Model.pptxGartner's Data Analytics Maturity Model.pptx
Gartner's Data Analytics Maturity Model.pptxchadhar227
 
Sonagachi * best call girls in Kolkata | ₹,9500 Pay Cash 8005736733 Free Home...
Sonagachi * best call girls in Kolkata | ₹,9500 Pay Cash 8005736733 Free Home...Sonagachi * best call girls in Kolkata | ₹,9500 Pay Cash 8005736733 Free Home...
Sonagachi * best call girls in Kolkata | ₹,9500 Pay Cash 8005736733 Free Home...HyderabadDolls
 
Digital Advertising Lecture for Advanced Digital & Social Media Strategy at U...
Digital Advertising Lecture for Advanced Digital & Social Media Strategy at U...Digital Advertising Lecture for Advanced Digital & Social Media Strategy at U...
Digital Advertising Lecture for Advanced Digital & Social Media Strategy at U...Valters Lauzums
 
Dubai Call Girls Peeing O525547819 Call Girls Dubai
Dubai Call Girls Peeing O525547819 Call Girls DubaiDubai Call Girls Peeing O525547819 Call Girls Dubai
Dubai Call Girls Peeing O525547819 Call Girls Dubaikojalkojal131
 
Top profile Call Girls In Hapur [ 7014168258 ] Call Me For Genuine Models We ...
Top profile Call Girls In Hapur [ 7014168258 ] Call Me For Genuine Models We ...Top profile Call Girls In Hapur [ 7014168258 ] Call Me For Genuine Models We ...
Top profile Call Girls In Hapur [ 7014168258 ] Call Me For Genuine Models We ...nirzagarg
 
Top profile Call Girls In Latur [ 7014168258 ] Call Me For Genuine Models We ...
Top profile Call Girls In Latur [ 7014168258 ] Call Me For Genuine Models We ...Top profile Call Girls In Latur [ 7014168258 ] Call Me For Genuine Models We ...
Top profile Call Girls In Latur [ 7014168258 ] Call Me For Genuine Models We ...gajnagarg
 
Sealdah % High Class Call Girls Kolkata - 450+ Call Girl Cash Payment 8005736...
Sealdah % High Class Call Girls Kolkata - 450+ Call Girl Cash Payment 8005736...Sealdah % High Class Call Girls Kolkata - 450+ Call Girl Cash Payment 8005736...
Sealdah % High Class Call Girls Kolkata - 450+ Call Girl Cash Payment 8005736...HyderabadDolls
 
怎样办理圣地亚哥州立大学毕业证(SDSU毕业证书)成绩单学校原版复制
怎样办理圣地亚哥州立大学毕业证(SDSU毕业证书)成绩单学校原版复制怎样办理圣地亚哥州立大学毕业证(SDSU毕业证书)成绩单学校原版复制
怎样办理圣地亚哥州立大学毕业证(SDSU毕业证书)成绩单学校原版复制vexqp
 
DATA SUMMIT 24 Building Real-Time Pipelines With FLaNK
DATA SUMMIT 24  Building Real-Time Pipelines With FLaNKDATA SUMMIT 24  Building Real-Time Pipelines With FLaNK
DATA SUMMIT 24 Building Real-Time Pipelines With FLaNKTimothy Spann
 
High Profile Call Girls Service in Jalore { 9332606886 } VVIP NISHA Call Girl...
High Profile Call Girls Service in Jalore { 9332606886 } VVIP NISHA Call Girl...High Profile Call Girls Service in Jalore { 9332606886 } VVIP NISHA Call Girl...
High Profile Call Girls Service in Jalore { 9332606886 } VVIP NISHA Call Girl...kumargunjan9515
 
Computer science Sql cheat sheet.pdf.pdf
Computer science Sql cheat sheet.pdf.pdfComputer science Sql cheat sheet.pdf.pdf
Computer science Sql cheat sheet.pdf.pdfSayantanBiswas37
 
7. Epi of Chronic respiratory diseases.ppt
7. Epi of Chronic respiratory diseases.ppt7. Epi of Chronic respiratory diseases.ppt
7. Epi of Chronic respiratory diseases.pptibrahimabdi22
 
Lecture_2_Deep_Learning_Overview-newone1
Lecture_2_Deep_Learning_Overview-newone1Lecture_2_Deep_Learning_Overview-newone1
Lecture_2_Deep_Learning_Overview-newone1ranjankumarbehera14
 
Discover Why Less is More in B2B Research
Discover Why Less is More in B2B ResearchDiscover Why Less is More in B2B Research
Discover Why Less is More in B2B Researchmichael115558
 
TrafficWave Generator Will Instantly drive targeted and engaging traffic back...
TrafficWave Generator Will Instantly drive targeted and engaging traffic back...TrafficWave Generator Will Instantly drive targeted and engaging traffic back...
TrafficWave Generator Will Instantly drive targeted and engaging traffic back...SOFTTECHHUB
 

Recently uploaded (20)

Top profile Call Girls In Vadodara [ 7014168258 ] Call Me For Genuine Models ...
Top profile Call Girls In Vadodara [ 7014168258 ] Call Me For Genuine Models ...Top profile Call Girls In Vadodara [ 7014168258 ] Call Me For Genuine Models ...
Top profile Call Girls In Vadodara [ 7014168258 ] Call Me For Genuine Models ...
 
Predicting HDB Resale Prices - Conducting Linear Regression Analysis With Orange
Predicting HDB Resale Prices - Conducting Linear Regression Analysis With OrangePredicting HDB Resale Prices - Conducting Linear Regression Analysis With Orange
Predicting HDB Resale Prices - Conducting Linear Regression Analysis With Orange
 
Top profile Call Girls In Begusarai [ 7014168258 ] Call Me For Genuine Models...
Top profile Call Girls In Begusarai [ 7014168258 ] Call Me For Genuine Models...Top profile Call Girls In Begusarai [ 7014168258 ] Call Me For Genuine Models...
Top profile Call Girls In Begusarai [ 7014168258 ] Call Me For Genuine Models...
 
Jodhpur Park | Call Girls in Kolkata Phone No 8005736733 Elite Escort Service...
Jodhpur Park | Call Girls in Kolkata Phone No 8005736733 Elite Escort Service...Jodhpur Park | Call Girls in Kolkata Phone No 8005736733 Elite Escort Service...
Jodhpur Park | Call Girls in Kolkata Phone No 8005736733 Elite Escort Service...
 
Nirala Nagar / Cheap Call Girls In Lucknow Phone No 9548273370 Elite Escort S...
Nirala Nagar / Cheap Call Girls In Lucknow Phone No 9548273370 Elite Escort S...Nirala Nagar / Cheap Call Girls In Lucknow Phone No 9548273370 Elite Escort S...
Nirala Nagar / Cheap Call Girls In Lucknow Phone No 9548273370 Elite Escort S...
 
Gartner's Data Analytics Maturity Model.pptx
Gartner's Data Analytics Maturity Model.pptxGartner's Data Analytics Maturity Model.pptx
Gartner's Data Analytics Maturity Model.pptx
 
Sonagachi * best call girls in Kolkata | ₹,9500 Pay Cash 8005736733 Free Home...
Sonagachi * best call girls in Kolkata | ₹,9500 Pay Cash 8005736733 Free Home...Sonagachi * best call girls in Kolkata | ₹,9500 Pay Cash 8005736733 Free Home...
Sonagachi * best call girls in Kolkata | ₹,9500 Pay Cash 8005736733 Free Home...
 
Digital Advertising Lecture for Advanced Digital & Social Media Strategy at U...
Digital Advertising Lecture for Advanced Digital & Social Media Strategy at U...Digital Advertising Lecture for Advanced Digital & Social Media Strategy at U...
Digital Advertising Lecture for Advanced Digital & Social Media Strategy at U...
 
Dubai Call Girls Peeing O525547819 Call Girls Dubai
Dubai Call Girls Peeing O525547819 Call Girls DubaiDubai Call Girls Peeing O525547819 Call Girls Dubai
Dubai Call Girls Peeing O525547819 Call Girls Dubai
 
Top profile Call Girls In Hapur [ 7014168258 ] Call Me For Genuine Models We ...
Top profile Call Girls In Hapur [ 7014168258 ] Call Me For Genuine Models We ...Top profile Call Girls In Hapur [ 7014168258 ] Call Me For Genuine Models We ...
Top profile Call Girls In Hapur [ 7014168258 ] Call Me For Genuine Models We ...
 
Top profile Call Girls In Latur [ 7014168258 ] Call Me For Genuine Models We ...
Top profile Call Girls In Latur [ 7014168258 ] Call Me For Genuine Models We ...Top profile Call Girls In Latur [ 7014168258 ] Call Me For Genuine Models We ...
Top profile Call Girls In Latur [ 7014168258 ] Call Me For Genuine Models We ...
 
Sealdah % High Class Call Girls Kolkata - 450+ Call Girl Cash Payment 8005736...
Sealdah % High Class Call Girls Kolkata - 450+ Call Girl Cash Payment 8005736...Sealdah % High Class Call Girls Kolkata - 450+ Call Girl Cash Payment 8005736...
Sealdah % High Class Call Girls Kolkata - 450+ Call Girl Cash Payment 8005736...
 
怎样办理圣地亚哥州立大学毕业证(SDSU毕业证书)成绩单学校原版复制
怎样办理圣地亚哥州立大学毕业证(SDSU毕业证书)成绩单学校原版复制怎样办理圣地亚哥州立大学毕业证(SDSU毕业证书)成绩单学校原版复制
怎样办理圣地亚哥州立大学毕业证(SDSU毕业证书)成绩单学校原版复制
 
DATA SUMMIT 24 Building Real-Time Pipelines With FLaNK
DATA SUMMIT 24  Building Real-Time Pipelines With FLaNKDATA SUMMIT 24  Building Real-Time Pipelines With FLaNK
DATA SUMMIT 24 Building Real-Time Pipelines With FLaNK
 
High Profile Call Girls Service in Jalore { 9332606886 } VVIP NISHA Call Girl...
High Profile Call Girls Service in Jalore { 9332606886 } VVIP NISHA Call Girl...High Profile Call Girls Service in Jalore { 9332606886 } VVIP NISHA Call Girl...
High Profile Call Girls Service in Jalore { 9332606886 } VVIP NISHA Call Girl...
 
Computer science Sql cheat sheet.pdf.pdf
Computer science Sql cheat sheet.pdf.pdfComputer science Sql cheat sheet.pdf.pdf
Computer science Sql cheat sheet.pdf.pdf
 
7. Epi of Chronic respiratory diseases.ppt
7. Epi of Chronic respiratory diseases.ppt7. Epi of Chronic respiratory diseases.ppt
7. Epi of Chronic respiratory diseases.ppt
 
Lecture_2_Deep_Learning_Overview-newone1
Lecture_2_Deep_Learning_Overview-newone1Lecture_2_Deep_Learning_Overview-newone1
Lecture_2_Deep_Learning_Overview-newone1
 
Discover Why Less is More in B2B Research
Discover Why Less is More in B2B ResearchDiscover Why Less is More in B2B Research
Discover Why Less is More in B2B Research
 
TrafficWave Generator Will Instantly drive targeted and engaging traffic back...
TrafficWave Generator Will Instantly drive targeted and engaging traffic back...TrafficWave Generator Will Instantly drive targeted and engaging traffic back...
TrafficWave Generator Will Instantly drive targeted and engaging traffic back...
 

Introduction to SQL

  • 2. Onboarding SQL (Structured Query Language) is the language for interacting with data stored in relational databases (a collection of tables) and is designed exactly for this purpose. SQL can be used to create and modify databases. Query: A request for data from a database table or a combination of tables. Querying is an essential skill for a data scientist. 2
  • 3. Selecting single columns • In SQL, you can select data from a table using a SELECT statement. For example: The following query selects the NAME column from the PEOPLE table: • In this query, SELECT and FROM are keywords, meaning you can write the same query as: • But it’s good practice to make SQL keywords uppercase to distinguish them. In addition, it’s also good practice to include a ‘;’ at the end of your query. This tells SQL where the end of your query is. SELECT name FROM people; select name from people; 3
  • 4. Selecting multiple columns • In practice, you will often want to select multiple columns. To select multiple columns from a table, simply separate the column names with commas. For example: This query selects two columns, NAME and BIRTHDATE from the PEOPLE table. • Sometimes you may want to select all columns from a table: • If you want only to return a certain number of results, you can use the LIMIT keyword to limit the number of rows returned: SELECT name, birthdate FROM people; SELECT * FROM people; SELECT * FROM people LIMIT 10; 4
  • 5. Selecting distinct • Often your results will include duplicates, so if you want to select unique/distinct values from a column, use the DISTINCT keyword. For example: You want to know which languages are represented in the FILMS table: SELECT DISTINCT language FROM films; 5
  • 6. Learning to count • What if you want to count the number of employees in your EMPLOYEES table? Use the keyword COUNT, which will tell you how many rows are in a table. • If you want to count the number of non-missing values in a particular column, you can call COUNT on just that column. For example: To count the number of BIRTHDATES present in the PEOPLE table: • It is also common to combine COUNT and DISTINCT for counting the number of distinct values in a column. SELECT COUNT(*) FROM employees; SELECT COUNT(birthdate) FROM people; SELECT COUNT(DISTINCT birthdate) FROM people; 6
  • 7. Filtering results (WHERE) • In SQL, the WHERE keyword allows you to filter based on both text and numeric values in a table. There are a few different comparison operators you can use: • For example: You can filter text records such as title. The following code returns all films with the title ‘Metropolis’. • WHERE clause always comes after the FROM statement. = <> < > <= >= SELECT title FROM films WHERE title = ‘Metropolis’; 7
  • 8. Filtering results (cont.) • Often you will want to select data based on multiple conditions. You can build up your WHERE queries by combining multiple conditions with the AND keyword. • This gives you the titles of films released between 1994 and 2000. SELECT title FROM films WHERE release_year > ‘1994’ AND release_year < ‘2000’; 8
  • 9. Filtering results (cont.) • What if you want to select rows based on multiple conditions, where some but not all of the conditions need to be met? For this, SQL has the OR operator. For example: The following returns all films released either in 1994 or 2000: • When combining AND or OR, be sure to enclose the individual clauses in parentheses: SELECT title FROM films WHERE release_year = ‘1994’ OR release_year = ‘2000’; SELECT title FROM films WHERE (release_year = 1994 OR release_year = 2000) AND (certification = ‘PG’ OR certification = ‘R’); 9
  • 10. BETWEEN • BETWEEN keyword provides a useful shorthand for filtering values within a specified range. • It is inclusive which means that the beginning and end values are included in the results. SELECT title FROM films WHERE release_year >= 1994 AND release_year <= 2000; SELECT title FROM films WHERE release_year BETWEEN 1994 AND 2000; 10
  • 11. BETWEEN (cont.) • The BETWEEN clause can be used with multiple AND and OR operators, so you can build up your queries and make them even more powerful! • For example: Suppose you have a table called KIDS, we can get the names of all the kids between the ages of 2 and 12 from the United States. SELECT name FROM kids WHERE age BETWEEN 2 AND 12 AND nationality = ‘USA’; 11
  • 12. WHERE IN • If you want to filter based on many conditions, use the IN operator. • The IN operator allows you to specify multiple values in a WHERE clause, making it easier and quicker to specify multiple OR conditions. SELECT name FROM kids WHERE age = 2 OR age = 4 OR age = 6 OR age = 8; SELECT name FROM kids WHERE age IN (2, 4, 6, 8); 12
  • 13. NULL & IS NULL • In SQL, NULL represents a missing or unknown value. You can check for null values using the expression IS NULL. For example: To count the number of missing birth dates in the PEOPLE table: • IS NULL is useful when combined with WHERE to figure out what data you are missing. Sometimes you will want to filter out missing values, so you get only the results which are not null. To do this, you can use the IS NOT NULL operator. SELECT COUNT (*) FROM people WHERE birthdate IS NULL; SELECT name FROM people WHERE birthdate IS NOT NULL; 13
  • 14. LIKE & NOT LIKE • In practice, you will often want to search for a pattern rather than a specific text-string. In SQL, the LIKE operator can be used in a WHERE clause to search for a pattern in a column. To accomplish this, you use something called a wildcard as a placeholder for some other values. There are two wildcards you can use with LIKE: - ‘%’ This wildcard will match zero, one or many characters in text. For example: The following query matches companies like ‘Data’, ‘DataC’, ‘DataCamp’, ‘DataMind’ and so on: - ‘_’ This wildcard match a single character. For example: The following query matches companies like ‘DataCamp’, ‘DataComp’ and so on: - You can also use the NOT LIKE operator to find records that don’t match the pattern you specify. SELECT name FROM companies WHERE name LIKE ‘Data%’; SELECT name FROM companies WHERE name LIKE ‘DataC_mp’; 14
  • 15. Aggregate functions • Often you will want to perform some calculation on the data in a database. SQL provides a few functions called ‘aggregate functions’ to for calculation: • This gives you the average value from the BUDGET column of the FILMS table. • Similarly, the MAX function returns the highest budget: SELECT AVG(budget) FROM films; SELECT MAX(budget) FROM films; 15
  • 16. Aggregate functions (cont.) • The SUM function returns the result of adding up the numeric values in a column: • Same goes for MIN function: • Combining aggregate functions with WHERE: Aggregate functions can be combined with the WHERE clause to gain insights from the data. For example: To get the total budget of movies made in the year 2000 or later: SELECT SUM(budget) FROM films; SELECT MIN(budget) FROM films; SELECT SUM(budget) FROM films WHERE release_year >= 2000; 16
  • 17. A note on arithmetic & Aliasing • SELECT (4*3); = 12 • SELECT (4/3); = 1 • If you want more precision when dividing, you can add decimal places to your numbers. For example: SELECT (4.0/3.0) AS result; = 1.333 • Aliasing: You assign a temporary name to something. To alias, you use the AS keyword, which makes it readable. For example: SELECT MAX(budget) AS MAX_budget, MAX(duration) AS MAX_duration FROM films; 17
  • 18. Aliasing (cont.) • SQL assumes that if you divide an integer by another integer, you want to get an integer back. This means that the following will erroneously result in 400.0: • This is because 45/10 evaluates to an integer 4, and not a decimal number like we would expect. So, when you are dividing make sure at least one of your numbers has a decimal place: • The above now gives the current answer of 450.0, since the numerator (45*100.0) of the division. SELECT 45/10*100.0; SELECT 45*100.0/10.0; 18
  • 19. ORDER BY • In SQL, the ORDER BY keyword is used to sort results in ascending or descending order according to the values of one of more columns. By default, ORDER BY will sort in ascending order but if you want to sort the results in descending order, you use the DESC keyword. For example: The query gives you the titles of films by release year from newest to oldest. • ORDER BY can also be used to sort on multiple columns. It will sort by the first column specified, then sort by the next and so on. For example: SELECT title FROM films ORDER BY release_year DESC; SELECT birthdate, name FROM people ORDER BY birthdate, name; 19
  • 20. GROUP BY • You might want to count the number of male and female employees in your company. Here, what you want is to group all the males together and count them, and same goes for all the females. • In SQL, GROUP BY allows you to group a result by one or more columns: • Commonly, GROUP BY is used with aggregate functions like COUNT() and MAX(). • Note: GROUP BY always comes after FROM clause. SELECT sex, count(*) FROM employees GROUP BY sex; 20
  • 21. GROUP BY (cont.) • SQL will return an error if you try to SELECT a field that is not in your GROUP BY clause without using it calculate some kind of value about the entire group. • Note: You can combine GROUP BY with ORDER BY to group your results, calculate something about them and then order your results. • ORDER BY always comes after GROUP BY, even after HAVING. SELECT sex, count(*) FROM employees GROUP BY sex ORDER BY count DESC; 21
  • 22. HAVING • In SQL, aggregate functions cannot be used in WHERE clauses. For example: The following query is invalid. • Thus, if you want to filter based on the result of an aggregate function, you need the HAVING clause. • This shows only those years in which more than 10 films were released. SELECT release_year FROM films GROUP BY release_year WHERE COUNT(title) > 10; SELECT release_year FROM films GROUP BY release_year HAVING COUNT(title) > 10; 22
  • 23. JOIN • You want to get the ID of the movie from the FILMS table and then use it to get the IMDB information from the REVIEWS table. In SQL, this concept is known as JOIN. • For example: SELECT title, imdb_score FROM films JOIN reviews ON films.id = reviews.film_id WHERE title = ‘To kill a mockingbird’; 23