Find the name and role of all employees who have not been assigned to a building
1
SELECT name, role FROM employees WHERE building isnull;
Find the names of the buildings that hold no employees
1 2 3 4 5
SELECTDISTINCT building_name FROM buildings LEFTJOIN employees ON building_name = building WHERE role ISNULL;
SQL Lesson 9: Queries with expressions
1 2
SELECT col_expression AS expr_description, … FROM mytable;
Exercise
Table: Movies
Id
Title
Director
Year
Length_minutes
1
Toy Story
John Lasseter
1995
81
2
A Bug’s Life
John Lasseter
1998
95
3
Toy Story 2
John Lasseter
1999
93
4
Monsters, Inc.
Pete Docter
2001
92
5
Finding Nemo
Andrew Stanton
2003
107
6
The Incredibles
Brad Bird
2004
116
7
Cars
John Lasseter
2006
117
8
Ratatouille
Brad Bird
2007
115
9
WALL-E
Andrew Stanton
2008
104
10
Up
Pete Docter
2009
101
11
Toy Story 3
Lee Unkrich
2010
103
12
Cars 2
John Lasseter
2011
120
13
Brave
Brenda Chapman
2012
102
14
Monsters University
Dan Scanlon
2013
110
Table: Boxoffice
Movie_id
Rating
Domestic_sales
International_sales
5
8.2
380843261
555900000
14
7.4
268492764
475066843
8
8
206445654
417277164
12
6.4
191452396
368400000
3
7.9
245852179
239163000
6
8
261441092
370001000
9
8.5
223808164
297503696
11
8.4
415004880
648167031
1
8.3
191796233
170162503
7
7.2
244082982
217900167
10
8.3
293004164
438338580
4
8.1
289916256
272900000
2
7.2
162798565
200600000
13
7.2
237283207
301700000
List all movies and their combined sales in millions of dollars
1 2 3 4
SELECT title, (domestic_sales + international_sales) /1000000AS gross_sales_millions FROM movies JOIN boxoffice ON movies.id = boxoffice.movie_id;
List all movies and their ratings in percent
1 2 3 4
SELECT title, rating *10AS rate_percent FROM movies INNERJOIN boxoffice ON movies.id = boxoffice.movie_id;
List all movies that were released on even number years
1
SELECT title, yearFROM movies WHEREyear%2=0;
SQL Lesson 10: Queries with aggregates (Pt. 1)
1 2 3 4 5 6 7 8 9 10
# Select query with aggregate functions overallrows SELECT AGG_FUNC(column_or_expression) AS aggregate_description, … FROM<mytable> WHERE constraint_expression;
# Select query with aggregate functions overgroups SELECT AGG_FUNC(column_or_expression) AS aggregate_description, … FROM mytable WHERE constraint_expression GROUPBY<column>;
Common aggregate functions
Function
Description
COUNT(*), COUNT(column)
A common function used to counts the number of rows in the group if no column name is specified. Otherwise, count the number of rows in the group with non-NULL values in the specified column.
MIN(column)
Finds the smallest numerical value in the specified column for all rows in the group.
MAX(column)
Finds the largest numerical value in the specified column for all rows in the group.
AVG(column)
Finds the average numerical value in the specified column for all rows in the group.
SUM(column)
Finds the sum of all numerical values in the specified column for the rows in the group.
Exercise
Table: Employees
Role
Name
Building
Years_employed
Engineer
Becky A.
1e
4
Engineer
Dan B.
1e
2
Engineer
Sharon F.
1e
6
Engineer
Dan M.
1e
4
Engineer
Malcom S.
1e
1
Artist
Tylar S.
2w
2
Artist
Sherman D.
2w
8
Artist
Jakob J.
2w
6
Artist
Lillia A.
2w
7
Artist
Brandon J.
2w
7
Manager
Scott K.
1e
9
Manager
Shirlee M.
1e
3
Manager
Daria O.
2w
6
Find the longest time that an employee has been at the studio
1
SELECT role, name, building, max(Years_employed) FROM employees;
For each role, find the average number of years employed by employees in that role
1
SELECT role, AVG(Years_employed) as avg_emply FROM employees groupby role;
Find the total number of employee years worked in each building
1
SELECT role, name, building, SUM(Years_employed) as sum_employ FROM employees groupby building;
SQL Lesson 11: Queries with aggregates (Pt. 2)
1 2 3 4 5 6
# Select query withHAVINGconstraint SELECT group_by_column, AGG_FUNC(column_expression) AS aggregate_result_alias, … FROM mytable WHEREcondition GROUPBYcolumn HAVING group_condition;
Exercise
Table: Employees
Role
Name
Building
Years_employed
Engineer
Becky A.
1e
4
Engineer
Dan B.
1e
2
Engineer
Sharon F.
1e
6
Engineer
Dan M.
1e
4
Engineer
Malcom S.
1e
1
Artist
Tylar S.
2w
2
Artist
Sherman D.
2w
8
Artist
Jakob J.
2w
6
Artist
Lillia A.
2w
7
Artist
Brandon J.
2w
7
Manager
Scott K.
1e
9
Manager
Shirlee M.
1e
3
Manager
Daria O.
2w
6
Find the number of Artists in the studio (without a HAVING clause)
1 2 3
SELECT role, COUNT(*) as Number_of_artists FROM employees WHERE role = "Artist";
或
1
SELECT role, COUNT(*) as total FROM employees groupby role HAVING role ='Artist';
Find the number of Employees of each role in the studio
1 2
SELECT role, COUNT(*) as Number_of_artists FROM employees groupby role;
Find the total number of years employed by all Engineers
1
SELECT Role, SUM(Years_employed) as sum_year_employed FROM employees where role='Engineer';
SQL Lesson 12: Order of execution of a Query
完整SQL语句:
1 2 3 4 5 6 7 8 9
SELECTDISTINCTcolumn, AGG_FUNC(column_or_expression), … FROM mytable JOIN another_table ON mytable.column = another_table.column WHERE constraint_expression GROUPBYcolumn HAVING constraint_expression ORDERBYcolumnASC/DESC LIMIT count OFFSET COUNT;
Query order of execution(查询执行顺序)
FROM and JOINs
WHERE
GROUP BY
HAVING
SELECT
DISTINCT
ORDER BY
LIMIT / OFFSET
Exercise
Table: Movies
Id
Title
Director
Year
Length_minutes
1
Toy Story
John Lasseter
1995
81
2
A Bug’s Life
John Lasseter
1998
95
3
Toy Story 2
John Lasseter
1999
93
4
Monsters, Inc.
Pete Docter
2001
92
5
Finding Nemo
Andrew Stanton
2003
107
6
The Incredibles
Brad Bird
2004
116
7
Cars
John Lasseter
2006
117
8
Ratatouille
Brad Bird
2007
115
9
WALL-E
Andrew Stanton
2008
104
10
Up
Pete Docter
2009
101
11
Toy Story 3
Lee Unkrich
2010
103
12
Cars 2
John Lasseter
2011
120
13
Brave
Brenda Chapman
2012
102
14
Monsters University
Dan Scanlon
2013
110
Table: Boxoffice
Movie_id
Rating
Domestic_sales
International_sales
5
8.2
380843261
555900000
14
7.4
268492764
475066843
8
8
206445654
417277164
12
6.4
191452396
368400000
3
7.9
245852179
239163000
6
8
261441092
370001000
9
8.5
223808164
297503696
11
8.4
415004880
648167031
1
8.3
191796233
170162503
7
7.2
244082982
217900167
10
8.3
293004164
438338580
4
8.1
289916256
272900000
2
7.2
162798565
200600000
13
7.2
237283207
301700000
Find the number of movies each director has directed
1
SELECT Director, count(*) as numberofmovies FROM movies groupby Director;
Find the total domestic and international sales that can be attributed to each director
1
SELECT Director, count(*) as NumOfMovie, sum(Domestic_sales + International_sales) FROM movies innerjoin Boxoffice on movies.id = Boxoffice.Movie_id groupby Director;
# Example Insert statement with expressions INSERTINTO boxoffice (movie_id, rating, sales_in_millions) VALUES (1, 9.9, 283742034/1000000);
Exercise
Table: Movies
Id
Title
Director
Year
Length_minutes
1
Toy Story
John Lasseter
1995
81
2
A Bug’s Life
John Lasseter
1998
95
3
Toy Story 2
John Lasseter
1999
93
Table: Boxoffice
Movie_id
Rating
Domestic_sales
International_sales
3
7.9
245852179
239163000
1
8.3
191796233
170162503
2
7.2
162798565
200600000
Add the studio’s new production, Toy Story 4 to the list of movies (you can use any director)
1
INSERTINTO movies VALUES (4, 'Toy Story 4', 'Jhon Lasseter', 1998, 89);
Toy Story 4 has been released to critical acclaim! It had a rating of 8.7, and made 340 million domestically and 270 million internationally. Add the record to the BoxOffice table
The integer datatypes can store whole integer values like the count of a number or an age. In some implementations, the boolean value is just represented as an integer value of just 0 or 1.
FLOAT, DOUBLE, REAL
The floating point datatypes can store more precise numerical data like measurements or fractional values. Different types can be used depending on the floating point precision required for that value.
CHARACTER(num_chars), VARCHAR(num_chars), TEXT
The text based datatypes can store strings and text in all sorts of locales. The distinction between the various types generally amount to underlaying efficiency of the database when working with these columns.Both the CHARACTER and VARCHAR (variable character) types are specified with the max number of characters that they can store (longer values may be truncated), so can be more efficient to store and query with big tables.
DATE, DATETIME
SQL can also store date and time stamps to keep track of time series and event data. They can be tricky to work with especially when manipulating data across timezones.
BLOB
Finally, SQL can store binary data in blobs right in the database. These values are often opaque to the database, so you usually have to store them with the right metadata to requery them.
Exercise
Create a new table named Database with the following columns:
Name A string (text) describing the name of the database
Version A number (floating point) of the latest version of this database
Download_count An integer count of the number of times this database was downloaded
This table has no constraints.
1 2 3 4 5
createtable if notexists database ( name TEXT, version FLOAT, download_count, INTEGER )
SQL Lesson 17: Altering tables
As your data changes over time, SQL provides a way for you to update your corresponding tables and database schemas by using the ALTER TABLE statement to add, remove, or modify columns and table constraints.
# Altering table name ALTERTABLE<mytable> RENAME TO<new_table_name>;
Exercise
Table: Movies
Id
Title
Director
Year
Length_minutes
1
Toy Story
John Lasseter
1995
81
2
A Bug’s Life
John Lasseter
1998
95
3
Toy Story 2
John Lasseter
1999
93
4
Monsters, Inc.
Pete Docter
2001
92
5
Finding Nemo
Andrew Stanton
2003
107
6
The Incredibles
Brad Bird
2004
116
7
Cars
John Lasseter
2006
117
8
Ratatouille
Brad Bird
2007
115
9
WALL-E
Andrew Stanton
2008
104
10
Up
Pete Docter
2009
101
11
Toy Story 3
Lee Unkrich
2010
103
12
Cars 2
John Lasseter
2011
120
13
Brave
Brenda Chapman
2012
102
14
Monsters University
Dan Scanlon
2013
110
Add a column named Aspect_ratio with a FLOAT data type to store the aspect-ratio each movie was released in.
1
ALTERTABLE movies ADD Aspect_ratio floatDEFAULT8.5;
Add another column named Language with a TEXT data type to store the language that the movie was released in. Ensure that the default for this language is English.
1
ALTERTABLE movies ADDLanguage TEXT DEFAULT'English';
SQL Lesson 18: Dropping tables
1 2
# Droptable statement DROPTABLE IF EXISTS<mytable>;
Exercise
Table: Movies
Id
Title
Director
Year
Length_minutes
1
Toy Story
John Lasseter
1995
81
2
A Bug’s Life
John Lasseter
1998
95
3
Toy Story 2
John Lasseter
1999
93
4
Monsters, Inc.
Pete Docter
2001
92
5
Finding Nemo
Andrew Stanton
2003
107
6
The Incredibles
Brad Bird
2004
116
7
Cars
John Lasseter
2006
117
8
Ratatouille
Brad Bird
2007
115
9
WALL-E
Andrew Stanton
2008
104
10
Up
Pete Docter
2009
101
11
Toy Story 3
Lee Unkrich
2010
103
12
Cars 2
John Lasseter
2011
120
13
Brave
Brenda Chapman
2012
102
14
Monsters University
Dan Scanlon
2013
110
Table: Boxoffice (Read-Only)
Movie_id
Rating
Domestic_sales
International_sales
5
8.2
380843261
555900000
14
7.4
268492764
475066843
8
8
206445654
417277164
12
6.4
191452396
368400000
3
7.9
245852179
239163000
6
8
261441092
370001000
9
8.5
223808164
297503696
11
8.4
415004880
648167031
1
8.3
191796233
170162503
7
7.2
244082982
217900167
10
8.3
293004164
438338580
4
8.1
289916256
272900000
2
7.2
162798565
200600000
13
7.2
237283207
301700000
We’ve sadly reached the end of our lessons, lets clean up by removing the Movies table