Here are my solutions to SQL tutorials from SQLZoo
- SELECT basics - Some simple queries to get you started
- SELECT name - Some pattern matching queries
- SELECT from World - In which we query the World country profile table.
- SELECT from Nobel - Additional practice of the basic features using a table of Nobel Prize winners.
- SELECT within SELECT - In which we form queries using other queries.
- SUM and COUNT - In which we apply aggregate functions.
- JOIN - In which we join two tables; game and goals.
- More JOIN operations - In which we join actors to movies in the Movie Database.
- using NULL - In which we look at teachers in departments. 8+. Numeric Examples - In which we look at a survey and deal with some more complex calculations. 9-. Window function - In which we examine UK general election results. 9+. COVID 19 - In which we measure the impact of COVID 19
- Self join - In which we join Edinburgh bus routes to Edinburgh bus routes.
-
The example uses a WHERE clause to show the population of 'France'. Note that strings (pieces of text that are data) should be in 'single quotes';
Modify it to show the population of Germany
SELECT population
FROM world
WHERE NAME = 'Germany'
-
Checking a list The word IN allows us to check if an item is in a list. The example shows the name and population for the countries 'Brazil', 'Russia', 'India' and 'China'.
Show the name and the population for 'Sweden', 'Norway' and 'Denmark'.
SELECT NAME,
population
FROM world
WHERE NAME IN ( 'Sweden', 'Norway', 'Denmark' );
- Which countries are not too small and not too big?
BETWEEN
allows range checking (range specified is inclusive of boundary values). The example below shows countries with an area of 250,000-300,000 sq. km. Modify it to show the country and the area for countries with an area between 200,000 and 250,000.
SELECT NAME,
area
FROM world
WHERE area BETWEEN 200000 AND 250000
-
You can use
WHERE name LIKE 'B%'
to find the countries that start with "B".- The % is a wild-card it can match any characters
Find the country that start with Y
SELECT NAME
FROM world
WHERE NAME LIKE 'Y%'
- Find the countries that end with y
SELECT NAME
FROM world
WHERE NAME LIKE '%y'
-
Luxembourg has an x - so does one other country. List them both.
Find the countries that contain the letter x
SELECT NAME
FROM world
WHERE NAME LIKE '%x%'
-
Iceland, Switzerland end with land - but are there others?
Find the countries that end with land
SELECT NAME
FROM world
WHERE NAME LIKE '%land'
-
Columbia starts with a C and ends with ia - there are two more like this.
Find the countries that start with C and end with ia
SELECT NAME
FROM world
WHERE NAME LIKE 'C%'
AND NAME LIKE '%ia'
-
Greece has a double e - who has a double o?
Find the country that has oo in the name
SELECT NAME
FROM world
WHERE NAME LIKE '%oo%'
-
Bahamas has three a - who else?
Find the countries that have three or more a in the name
SELECT NAME
FROM world
WHERE NAME LIKE '%a%a%a%'
-
India and Angola have an n as the second character. You can use the underscore as a single character wildcard.
SELECT name FROM world WHERE name LIKE '_n%' ORDER BY name
SELECT NAME
FROM world
WHERE NAME LIKE '_t%'
ORDER BY NAME
-
Lesotho and Moldova both have two o characters separated by two other characters.
Find the countries that have two "o" characters separated by two others.
SELECT NAME
FROM world
WHERE NAME LIKE '%o__o%'
-
Cuba and Togo have four characters names.
Find the countries that have exactly four characters.
SELECT NAME
FROM world
WHERE Length(NAME) = 4
-
The capital of Luxembourg is Luxembourg. Show all the countries where the capital is the same as the name of the country
Find the country where the name is the capital city.
SELECT NAME
FROM world
WHERE NAME = capital
-
The capital of Mexico is Mexico City. Show all the countries where the capital has the country together with the word "City".
Find the country where the capital is the country plus "City".
SELECT NAME
FROM world
WHERE capital = Concat(NAME, ' City')
- Find the capital and the name where the capital includes the name of the country.
SELECT capital,
NAME
FROM world
WHERE capital LIKE Concat('%', NAME, '%')
-
Find the capital and the name where the capital is an extension of name of the country.
You should include Mexico City as it is longer than Mexico. You should not include Luxembourg as the capital is the same as the country.
SELECT capital,
NAME
FROM world
WHERE capital LIKE Concat('%', NAME, '%')
AND Length(capital) > Length(NAME)
-
For Monaco-Ville the name is Monaco and the extension is -Ville.
Show the name and the extension where the capital is an extension of name of the country.
SELECT NAME,
Replace(capital, NAME, '') ext
FROM world
WHERE capital LIKE Concat(NAME, '_%')
- Observe the result of running this SQL command to show the name, continent and population of all countries.
SELECT NAME,
continent,
population
FROM world
- Show the name for the countries that have a population of at least 200 million. 200 million is 200000000, there are eight zeros.
SELECT NAME
FROM world
WHERE population >= 200000000
- Give the
name
and the per capita GDP for those countries with apopulation
of at least 200 million.
SELECT NAME,
gdp / population
FROM world
WHERE population >= 200000000
- Show the
name
andpopulation
in millions for the countries of thecontinent
'South America'. Divide the population by 1000000 to get population in millions.
SELECT NAME,
population / 1000000
FROM world
WHERE continent = 'South America'
- Show the
name
andpopulation
for France, Germany, Italy
SELECT NAME,
population
FROM world
WHERE NAME IN ( 'France', 'Germany', 'Italy' )
- Show the countries which have a name that includes the word 'United'
SELECT NAME
FROM world
WHERE NAME LIKE 'United%'
-
Two ways to be big: A country is big if it has an area of more than 3 million sq km or it has a population of more than 250 million.
Show the countries that are big by area or big by population. Show name, population and area.
SELECT NAME,
population,
area
FROM world
WHERE area > 3000000
OR population > 250000000
-
Exclusive OR (XOR). Show the countries that are big by area (more than 3 million) or big by population (more than 250 million) but not both. Show name, population and area.
- Australia has a big area but a small population, it should be included.
- Indonesia has a big population but a small area, it should be included.
- China has a big population and big area, it should be excluded.
- United Kingdom has a small population and a small area, it should be excluded.
SELECT name,
population,
area
FROM world
WHERE area > 3000000 XOR population > 250000000
-
Show the
name
andpopulation
in millions and the GDP in billions for the countries of thecontinent
'South America'. Use the ROUND function to show the values to two decimal places.For South America show population in millions and GDP in billions both to 2 decimal places.
SELECT NAME,
Round(population / 1000000, 2),
Round(gdp / 1000000000, 2)
FROM world
WHERE continent = 'South America'
-
Show the
name
and per-capita GDP for those countries with a GDP of at least one trillion (1000000000000; that is 12 zeros). Round this value to the nearest 1000.Show per-capita GDP for the trillion dollar countries to the nearest $1000.
SELECT NAME,
Round(gdp / population, -3)
FROM world
WHERE gdp >= 1000000000000
-
Greece has capital Athens.
Each of the strings 'Greece', and 'Athens' has 6 characters.
Show the name and capital where the name and the capital have the same number of characters.
- You can use the LENGTH function to find the number of characters in a string
SELECT NAME,
capital
FROM world
WHERE Length(NAME) = Length(capital)
-
The capital of Sweden is Stockholm. Both words start with the letter 'S'.
Show the name and the capital where the first letters of each match. Don't include countries where the name and the capital are the same word.
- You can use the function LEFT to isolate the first character.
- You can use <> as the NOT EQUALS operator.
SELECT NAME,
capital
FROM world
WHERE LEFT(NAME, 1) = LEFT(capital, 1)
AND ( capital <> NAME )
-
Equatorial Guinea and Dominican Republic have all of the vowels (a e i o u) in the name. They don't count because they have more than one word in the name.
Find the country that has all the vowels and no spaces in its name.
- You can use the phrase
name NOT LIKE '%a%'
to exclude characters from your results. - The query shown misses countries like Bahamas and Belarus because they contain at least one 'a'
- You can use the phrase
SELECT NAME
FROM world
WHERE NAME LIKE '%a%'
AND NAME LIKE '%e%'
AND NAME LIKE '%i%'
AND NAME LIKE '%o%'
AND NAME LIKE '%u%'
AND NAME NOT LIKE '% %'
- Change the query shown so that it displays Nobel prizes for 1950.
SELECT yr,
subject,
winner
FROM nobel
WHERE yr = 1950
- Show who won the 1962 prize for Literature.
SELECT winner
FROM nobel
WHERE yr = 1962
AND subject = 'Literature'
- Show the year and subject that won 'Albert Einstein' his prize.
SELECT yr,
subject
FROM nobel
WHERE winner = 'Albert Einstein'
- Give the name of the 'Peace' winners since the year 2000, including 2000.
SELECT winner
FROM nobel
WHERE subject = 'Peace'
AND yr >= 2000
- Show all details (yr, subject, winner) of the Literature prize winners for 1980 to 1989 inclusive.
SELECT *
FROM nobel
WHERE subject = 'Literature'
AND yr >= 1980
AND yr <= 1989
-
Show all details of the presidential winners:
- Theodore Roosevelt
- Woodrow Wilson
- Jimmy Carter
- Barack Obama
SELECT *
FROM nobel
WHERE winner IN ( 'Theodore Roosevelt', 'Woodrow Wilson', 'Jimmy Carter',
'Barack Obama' )
- Show the winners with first name John
SELECT winner
FROM nobel
WHERE winner LIKE 'John%'
- Show the year, subject, and name of Physics winners for 1980 together with the Chemistry winners for 1984.
SELECT *
FROM nobel
WHERE ( subject = 'Chemistry'
AND yr = 1984 )
OR ( subject = 'Physics'
AND yr = 1980 )
- Show the year, subject, and name of winners for 1980 excluding Chemistry and Medicine
SELECT *
FROM nobel
WHERE yr = 1980
AND subject NOT IN ( 'Chemistry', 'Medicine' )
- Show year, subject, and name of people who won a 'Medicine' prize in an early year (before 1910, not including 1910) together with winners of a 'Literature' prize in a later year (after 2004, including 2004).
SELECT *
FROM nobel
WHERE ( subject = 'Medicine'
AND yr < 1910 )
OR ( subject = 'Literature'
AND yr >= 2004 )
- Find all details of the prize won by PETER GRÜNBERG
SELECT *
FROM nobel
WHERE winner = 'Peter Grünberg'
- Find all details of the prize won by EUGENE O'NEILL
SELECT *
FROM nobel
WHERE winner = 'Eugene O''Neill'
-
Knights in order
List the winners, year and subject where the winner starts with Sir. Show the the most recent first, then by name order.
SELECT winner,
yr,
subject
FROM nobel
WHERE winner LIKE 'Sir%'
ORDER BY yr DESC,
winner
-
The expression subject IN ('Chemistry','Physics') can be used as a value - it will be 0 or 1.
Show the 1984 winners and subject ordered by subject and winner name; but list Chemistry and Physics last.
SELECT winner,
subject
FROM nobel
WHERE yr = 1984
ORDER BY subject IN ( 'Physics', 'Chemistry' ),
subject,
winner
- List each country name where the population is larger than that of 'Russia'.
SELECT NAME
FROM world
WHERE population > (SELECT population
FROM world
WHERE NAME = 'Russia')
- Show the countries in Europe with a per capita GDP greater than 'United Kingdom'.
SELECT NAME
FROM world
WHERE gdp / population > (SELECT gdp / population
FROM world
WHERE NAME = 'United Kingdom')
AND continent = 'Europe'
- List the name and continent of countries in the continents containing either Argentina or Australia. Order by name of the country.
SELECT NAME,
continent
FROM world
WHERE continent IN ( (SELECT continent
FROM world
WHERE NAME = 'Argentina'), (SELECT continent
FROM world
WHERE NAME = 'Australia') )
ORDER BY NAME
- Which country has a population that is more than Canada but less than Poland? Show the name and the population.
SELECT NAME,
population
FROM world
WHERE population > (SELECT population
FROM world
WHERE NAME = 'Canada')
AND population < (SELECT population
FROM world
WHERE NAME = 'Poland')
- Germany (population 80 million) has the largest population of the countries in Europe. Austria (population 8.5 million) has 11% of the population of Germany. Show the name and the population of each country in Europe. Show the population as a percentage of the population of Germany.
SELECT NAME,
Concat(Round(population / (SELECT population
FROM world
WHERE NAME = 'Germany') * 100), '%')
FROM world
WHERE continent = 'Europe'
- Which countries have a GDP greater than every country in Europe? [Give the name only.] (Some countries may have NULL gdp values)
SELECT NAME
FROM world
WHERE gdp > ALL (SELECT gdp
FROM world
WHERE continent = 'Europe'
AND gdp > 0)
- Find the largest country (by area) in each continent, show the continent, the name and the area:
SELECT continent,
NAME,
area
FROM world x
WHERE area >= ALL (SELECT area
FROM world y
WHERE y.continent = x.continent
AND area > 0)
- List each continent and the name of the country that comes first alphabetically.
SELECT continent,
NAME
FROM world x
WHERE x.NAME <= ALL (SELECT NAME
FROM world y
WHERE x.continent = y.continent)
- Find the continents where all countries have a population <= 25000000. Then find the names of the countries associated with these continents. Show name, continent and population.
SELECT NAME,
continent,
population
FROM world x
WHERE 25000000 >= ALL (SELECT population
FROM world y
WHERE x.continent = y.continent
AND y.population > 0)
- Some countries have populations more than three times that of all of their neighbours (in the same continent). Give the countries and continents.
SELECT NAME,
continent
FROM world x
WHERE population > ALL (SELECT population * 3
FROM world y
WHERE x.continent = y.continent
AND x.NAME != y.NAME)
- Show the total population of the world.
SELECT Sum(population)
FROM world
- List all the continents - just once each.
SELECT DISTINCT continent
FROM world
- Give the total GDP of Africa
SELECT Sum (gdp)
FROM world
WHERE continent = 'Africa'
- How many countries have an area of at least 1000000
SELECT Count(NAME)
FROM world
WHERE area > '1000000'
- What is the total population of ('Estonia', 'Latvia', 'Lithuania')
SELECT Sum (population)
FROM world
WHERE NAME IN ( 'Estonia', 'Latvia', 'Lithuania' )
- For each continent show the continent and number of countries.
SELECT continent,
Count(NAME)
FROM world
GROUP BY continent
- For each continent show the continent and number of countries with populations of at least 10 million.
SELECT continent,
Count(NAME)
FROM world
WHERE population >= 10000000
GROUP BY continent
- List the continents that have a total population of at least 100 million.
SELECT continent
FROM world
GROUP BY continent
HAVING Sum(population) >= 100000000
- The first example shows the goal scored by a player with the last name 'Bender'. The
*
says to list all the columns in the table - a shorter way of sayingmatchid, teamid, player, gtime
Modify it to show the matchid and player name for all goals scored by Germany. To identify German players, check for:teamid = 'GER'
SELECT matchid,
player
FROM goal
WHERE teamid = 'GER'
- From the previous query you can see that Lars Bender's scored a goal in game 1012. Now we want to know what teams were playing in that match.
Notice in the that the column
matchid
in thegoal
table corresponds to theid
column in thegame
table. We can look up information about game 1012 by finding that row in the game table. Show id, stadium, team1, team2 for just game 1012
SELECT id,
stadium,
team1,
team2
FROM game
WHERE id = 1012
- You can combine the two steps into a single query with a JOIN.
SELECT *
FROM game JOIN goal ON (id=matchid)
The FROM clause says to merge data from the goal table with that from the game table. The ON says how to figure out which rows in game go with which rows in goal - the matchid from goal must match id from game. (If we wanted to be more clear/specific we could say
ON (game.id=goal.matchid)
The code below shows the player (from the goal) and stadium name (from the game table) for every goal scored.
Modify it to show the player, teamid, stadium and mdate for every German goal.
SELECT player,
teamid,
stadium,
mdate
FROM game
JOIN goal
ON ( id = matchid )
WHERE teamid = 'GER'
- Use the same
JOIN
as in the previous question.
Show the team1, team2 and player for every goal scored by a player called
Mario player LIKE 'Mario%'
SELECT team1,
team2,
player
FROM game
JOIN goal
ON ( id = matchid )
WHERE player LIKE 'Mario%'
- The table
eteam
gives details of every national team including the coach. You canJOIN
goal
toeteam
using the phrasegoal JOIN eteam on teamid=id
Show player
, teamid
, coach
, gtime
for all goals scored in the first 10
minutes gtime<=10
SELECT player,
teamid,
coach,
gtime
FROM goal
JOIN eteam
ON teamid = id
WHERE gtime <= 10
- To
JOIN
game
witheteam
you could use eithergame JOIN eteam ON (team1=eteam.id)
orgame JOIN eteam ON (team2=eteam.id)
Notice that because id
is a column name in both game
and eteam
you must specify eteam.id
instead of just id
List the dates of the matches and the name of the team in which 'Fernando Santos' was the team1 coach.
SELECT mdate,
teamname
FROM game
JOIN eteam
ON ( team1 = eteam.id )
WHERE coach = 'Fernando Santos'
- List the player for every goal scored in a game where the stadium was 'National Stadium, Warsaw'
SELECT player
FROM game
JOIN goal
ON ( id = matchid )
WHERE stadium = 'National Stadium, Warsaw'
- The example query shows all goals scored in the Germany-Greece quarterfinal.
Instead show the name of all players who scored a goal against Germany.
SELECT DISTINCT player
FROM game
JOIN goal
ON matchid = id
WHERE ( team1 = 'GER'
OR team2 = 'GER' )
AND teamid != 'GER'
- Show teamname and the total number of goals scored.
SELECT teamname,
Count(teamname)
FROM eteam
JOIN goal
ON id = teamid
GROUP BY teamname
- Show the stadium and the number of goals scored in each stadium.
SELECT stadium,
Count(stadium)
FROM game
JOIN goal
ON id = matchid
GROUP BY stadium
- For every match involving 'POL', show the matchid, date and the number of goals scored.
SELECT matchid,
mdate,
Count(teamid)
FROM game
JOIN goal
ON matchid = id
WHERE ( team1 = 'POL'
OR team2 = 'POL' )
GROUP BY matchid,
mdate
- For every match where 'GER' scored, show matchid, match date and the number of goals scored by 'GER'
SELECT matchid,
mdate,
Count(teamid)
FROM game
JOIN goal
ON id = matchid
WHERE ( teamid = 'GER' )
GROUP BY matchid,
mdate
- List every match with the goals scored by each team as shown. This will use "CASE WHEN" which has not been explained in any previous exercises.
SELECT mdate,
team1,
Sum(CASE
WHEN teamid = team1 THEN 1
ELSE 0
END) score1,
team2,
Sum(CASE
WHEN teamid = team2 THEN 1
ELSE 0
END) score2
FROM game
LEFT JOIN goal
ON matchid = id
GROUP BY mdate,
matchid,
team1,
team2
- Lead actor in Julie Andrews movies
SELECT title,
NAME
FROM movie
JOIN casting
ON ( id = casting.movieid )
JOIN actor
ON ( actor.id = actorid )
WHERE movieid IN (SELECT movieid
FROM actor
JOIN casting
ON ( actor.id = actorid )
WHERE NAME = 'Julie Andrews')
AND ord = '1'
- Actors with 15 leading roles
SELECT NAME
FROM actor
JOIN casting
ON ( id = actorid
AND ord = '1' )
GROUP BY NAME
HAVING ( Count(movieid) >= 15 )
ORDER BY NAME
- List the films released in the year 1978 ordered by the number of actors in the cast, then by title.
SELECT title,
Count(actorid)
FROM movie
JOIN casting
ON ( movie.id = movieid )
WHERE yr = 1978
GROUP BY title
ORDER BY Count(actorid) DESC
- List all the people who have worked with 'Art Garfunkel'.
SELECT DISTINCT( NAME )
FROM casting
JOIN actor
ON ( actorid = actor.id )
WHERE NAME != 'Art Garfunkel'
AND movieid IN (SELECT movieid
FROM movie
JOIN casting
ON ( movie.id = movieid )
JOIN actor
ON ( actorid = actor.id )
WHERE NAME = 'Art Garfunkel')
- List the teachers who have NULL for their department.
SELECT NAME
FROM teacher
WHERE dept IS NULL
- Note the INNER JOIN misses the teachers with no department and the departments with no teacher.
SELECT teacher.NAME,
dept.NAME
FROM teacher
INNER JOIN dept
ON ( teacher.dept = dept.id )
- Use a different JOIN so that all teachers are listed.
SELECT teacher.NAME,
dept.NAME
FROM teacher
LEFT JOIN dept
ON ( teacher.dept = dept.id )
- Use a different JOIN so that all departments are listed.
SELECT teacher.NAME,
dept.NAME
FROM teacher
RIGHT JOIN dept
ON ( teacher.dept = dept.id )
- Use COALESCE to print the mobile number. Use the number '07986 444 2266' if there is no number given. Show teacher name and mobile number or '07986 444 2266'
SELECT NAME,
COALESCE(mobile, '07986 444 2266')
FROM teacher
- Use the COALESCE function and a LEFT JOIN to print the teacher name and department name. Use the string 'None' where there is no department.
SELECT teacher.NAME,
COALESCE(dept.NAME, 'None')
FROM teacher
LEFT JOIN dept
ON ( teacher.dept = dept.id )
- Use COUNT to show the number of teachers and the number of mobile phones.
SELECT Count(teacher.NAME),
Count(mobile)
FROM teacher
LEFT JOIN dept
ON ( teacher.dept = dept.id )
- Use COUNT and GROUP BY dept.name to show each department and the number of staff. Use a RIGHT JOIN to ensure that the Engineering department is listed.
SELECT dept.NAME,
Count(teacher.NAME)
FROM teacher
RIGHT JOIN dept
ON ( teacher.dept = dept.id )
GROUP BY dept.NAME
- Use CASE to show the name of each teacher followed by 'Sci' if the teacher is in dept 1 or 2 and 'Art' otherwise.
SELECT teacher.NAME,
( CASE
WHEN teacher.dept IN ( 1, 2 ) THEN 'Sci'
ELSE 'Art'
END )
FROM teacher
- Use CASE to show the name of each teacher followed by 'Sci' if the teacher is in dept 1 or 2, show 'Art' if the teacher's dept is 3 and 'None' otherwise.
SELECT teacher.NAME,
( CASE
WHEN teacher.dept IN ( 1, 2 ) THEN 'Sci'
WHEN teacher.dept = 3 THEN 'Art'
ELSE 'None'
END )
FROM teacher
-
The example shows the number who responded for:
- question 1
- at 'Edinburgh Napier University'
- studying '(8) Computer Science'
Show the the percentage who STRONGLY AGREE
SELECT a_strongly_agree
FROM nss
WHERE question = 'Q01'
AND institution = 'Edinburgh Napier University'
AND subject = '(8) Computer Science'
- Show the institution and subject where the score is at least 100 for question 15.
SELECT institution,
subject
FROM nss
WHERE question = 'Q15'
AND score >= 100
- Show the institution and score where the score for '(8) Computer Science' is less than 50 for question 'Q15'
SELECT institution,
score
FROM nss
WHERE question = 'Q15'
AND score < 50
AND subject = '(8) Computer Science'
- Show the subject and total number of students who responded to question 22 for each of the subjects '(8) Computer Science' and '(H) Creative Arts and Design'.
SELECT subject,
Sum(response)
FROM nss
WHERE question = 'Q22'
AND subject IN ( '(8) Computer Science', '(H) Creative Arts and Design' )
GROUP BY subject
- Show the subject and total number of students who A_STRONGLY_AGREE to question 22 for each of the subjects '(8) Computer Science' and '(H) Creative Arts and Design'.
SELECT subject,
Sum(response * a_strongly_agree / 100)
FROM nss
WHERE question = 'Q22'
AND subject IN ( '(8) Computer Science', '(H) Creative Arts and Design' )
GROUP BY subject
-
Show the percentage of students who A_STRONGLY_AGREE to question 22 for the subject '(8) Computer Science' show the same figure for the subject '(H) Creative Arts and Design'.
Use the ROUND function to show the percentage without decimal places.
SELECT subject,
Round(Sum(response * a_strongly_agree) / Sum(response), 0)
FROM nss
WHERE question = 'Q22'
AND subject IN ( '(8) Computer Science', '(H) Creative Arts and Design' )
GROUP BY subject
-
Show the average scores for question 'Q22' for each institution that include 'Manchester' in the name.
The column score is a percentage - you must use the method outlined above to multiply the percentage by the response and divide by the total response. Give your answer rounded to the nearest whole number.
SELECT institution,
Round(Sum(response * score) / Sum(response), 0) score
FROM nss
WHERE question = 'Q22'
AND ( institution LIKE '%Manchester%' )
GROUP BY institution
- Show the institution, the total sample size and the number of computing students for institutions in Manchester for 'Q01'.
SELECT institution,
Sum(sample),
Sum(CASE
WHEN subject = '(8) Computer Science' THEN sample
END) computing_students
FROM nss
WHERE question = 'Q01'
AND ( institution LIKE '%Manchester%' )
GROUP BY institution
- Show the lastName, party and votes for the constituency 'S14000024' in 2017.
SELECT lastname,
party,
votes
FROM ge
WHERE constituency = 'S14000024'
AND yr = 2017
ORDER BY votes DESC
-
You can use the RANK function to see the order of the candidates. If you RANK using (ORDER BY votes DESC) then the candidate with the most votes has rank 1.
Show the party and RANK for constituency S14000024 in 2017. List the output by party
SELECT party,
votes,
Rank()
OVER (
ORDER BY votes DESC) AS posn
FROM ge
WHERE constituency = 'S14000024'
AND yr = 2017
ORDER BY party
-
The 2015 election is a different PARTITION to the 2017 election. We only care about the order of votes for each year.
Use PARTITION to show the ranking of each party in S14000021 in each year. Include yr, party, votes and ranking (the party with the most votes is 1).
SELECT yr,
party,
votes,
Rank()
OVER (
partition BY yr
ORDER BY votes DESC) AS posn
FROM ge
WHERE constituency = 'S14000021'
ORDER BY party,
yr
-
Edinburgh constituencies are numbered S14000021 to S14000026.
*Use PARTITION BY constituency to show the ranking of each party in Edinburgh in 2017. Order your results so the winners are shown first, then ordered by constituency.
SELECT constituency,
party,
votes,
Rank()
OVER (
partition BY constituency
ORDER BY votes DESC) AS posn
FROM ge
WHERE constituency BETWEEN 'S14000021' AND 'S14000026'
AND yr = 2017
ORDER BY posn,
constituency,
votes DESC
-
You can use SELECT within SELECT to pick out only the winners in Edinburgh.
Show the parties that won for each Edinburgh constituency in 2017.
SELECT constituency,
party
FROM (SELECT constituency,
party,
Rank()
OVER (
partition BY constituency
ORDER BY votes DESC) AS posn
FROM ge
WHERE constituency BETWEEN 'S14000021' AND 'S14000026'
AND yr = 2017) AS ed
WHERE posn = 1
-
You can use COUNT and GROUP BY to see how each party did in Scotland. Scottish constituencies start with 'S'
Show how many seats for each party in Scotland in 2017.
SELECT party,
Count(1)
FROM (SELECT constituency,
party,
Rank()
OVER (
partition BY constituency
ORDER BY votes DESC) AS posn
FROM ge
WHERE constituency LIKE 'S%'
AND yr = 2017) AS ed
WHERE posn = 1
GROUP BY party
-
The example uses a WHERE clause to show the cases in 'Italy' in March 2020.
Modify the query to show data from Spain
SELECT NAME,
Day(whn),
confirmed,
deaths,
recovered
FROM covid
WHERE NAME = 'Spain'
AND Month(whn) = 3
AND Year(whn) = 2020
ORDER BY whn
- How many stops are in the database.
SELECT Count (DISTINCT id)
FROM stops
- Find the id value for the stop 'Craiglockhart'
SELECT id
FROM stops
WHERE NAME = 'Craiglockhart'
- Give the id and the name for the stops on the '4' 'LRT' service.
SELECT id,
NAME
FROM stops
JOIN route
ON ( stops.id = route.stop )
WHERE company = 'LRT'
AND num = '4'
- The query shown gives the number of routes that visit either London Road (149) or Craiglockhart (53). Run the query and notice the two services that link these stops have a count of 2. Add a HAVING clause to restrict the output to these two routes.
SELECT company,
num,
Count(*)
FROM route
WHERE stop = 149
OR stop = 53
GROUP BY company,
num
HAVING Count(*) = 2
- Execute the self join shown and observe that b.stop gives all the places you can get to from Craiglockhart, without changing routes. Change the query so that it shows the services from Craiglockhart to London Road.
SELECT a.company,
a.num,
a.stop,
b.stop
FROM route a
JOIN route b
ON ( a.company = b.company
AND a.num = b.num )
WHERE a.stop = 53
AND b.stop = 149
- The query shown is similar to the previous one, however by joining two copies of the stops table we can refer to stops by name rather than by number. Change the query so that the services between 'Craiglockhart' and 'London Road' are shown. If you are tired of these places try 'Fairmilehead' against 'Tollcross'
SELECT a.company,
a.num,
stopa.NAME,
stopb.NAME
FROM route a
JOIN route b
ON ( a.company = b.company
AND a.num = b.num )
JOIN stops stopa
ON ( a.stop = stopa.id )
JOIN stops stopb
ON ( b.stop = stopb.id )
WHERE stopa.NAME = 'Craiglockhart'
AND stopb.NAME = 'London Road'
- Give a list of all the services which connect stops 115 and 137 ('Haymarket' and 'Leith')
SELECT DISTINCT r1.company,
r1.num
FROM route r1,
route r2
WHERE r1.num = r2.num
AND r1.company = r2.company
AND r1.stop = 115
AND r2.stop = 137
- Give a list of the services which connect the stops 'Craiglockhart' and 'Tollcross'
SELECT DISTINCT r1.company,
r1.num
FROM route r1,
route r2,
stops s1,
stops s2
WHERE r1.num = r2.num
AND r1.company = r2.company
AND r1.stop = s1.id
AND r2.stop = s2.id
AND s1.NAME = 'Craiglockhart'
AND s2.NAME = 'Tollcross'
- Give a distinct list of the stops which may be reached from 'Craiglockhart' by taking one bus, including 'Craiglockhart' itself, offered by the LRT company. Include the company and bus no. of the relevant services.
SELECT DISTINCT s2.NAME,
r2.company,
r2.num
FROM route r1,
route r2,
stops s1,
stops s2
WHERE r1.num = r2.num
AND r1.company = r2.company
AND r1.stop = s1.id
AND r2.stop = s2.id
AND s1.NAME = 'Craiglockhart'