Coder Social home page Coder Social logo

sqlzoo's Introduction

SQLZoo

SQL exercises from sqlzoo.net.

Index

  1. SELECT Basics
  2. SELECT Name
  3. SELECT From World
  4. SELECT From Nobel
  5. SELECT Within SELECT
  6. SUM and COUNT
  7. JOIN
  8. More JOIN Operations
  9. Using NULL
  10. Numeric Examples (08+)
  11. Self JOIN

00. SELECT Basics

  1. Show the population of Germany.
SELECT population
  FROM world
 WHERE name = 'Germany';
  1. Show the name and the population for 'Sweden', 'Norway' and 'Denmark'.
SELECT name, population
  FROM world
 WHERE name IN ('Sweden', 'Norway', 'Denmark');
  1. 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;

01. SELECT Name

  1. Find the country that start with Y.
SELECT name
  FROM world
 WHERE name LIKE 'Y%';
  1. Find the countries that end with y.
SELECT name
  FROM world
 WHERE name LIKE '%y';
  1. Find the countries that contain the letter x.
SELECT name
  FROM world
 WHERE name LIKE '%x%';
  1. Find the countries that end with land.
SELECT name
  FROM world
 WHERE name LIKE '%land';
  1. Find the countries that start with C and end with ia.
SELECT name
  FROM world
 WHERE name LIKE 'C%'
   AND name LIKE '%ia';
  1. Find the country that has oo in the name.
SELECT name
  FROM world
 WHERE name LIKE '%oo%';
  1. Find the countries that have three or more a in the name.
SELECT name
  FROM world
 WHERE name LIKE '%a%a%a%';
  1. Find the countries that have "t" as the second character.
  SELECT name
    FROM world
   WHERE name LIKE '_t%'
ORDER BY name;
  1. Find the countries that have two "o" characters separated by two others.
SELECT name
  FROM world
 WHERE name LIKE '%o__o%';
  1. Find the countries that have exactly four characters.
SELECT name
  FROM world
 WHERE name LIKE '____';
  1. Find the country where the name is the capital city.
SELECT name
  FROM world
 WHERE name = capital;
  1. Find the country where the capital is the country plus "City".
SELECT name
  FROM world
 WHERE capital = CONCAT(name, ' City');
  1. 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, '%');
  1. Find the capital and the name where the capital is an extension of name of the country.
SELECT capital, name
  FROM world
 WHERE capital LIKE CONCAT(name, '_%');
  1. Show the name and the extension where the capital is an extension of name of the country.
SELECT name, REPLACE(capital, name, '') as extension
  FROM world
 WHERE capital LIKE CONCAT(name, '_%');

02. SELECT From World

  1. Introduction.
SELECT name, continent, population
  FROM world;
  1. 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;
  1. Give the name and the per capita GDP for those countries with a population of at least 200 million.
SELECT name, gdp/population
  FROM world
 WHERE population > 200000000;
  1. Show the name and population in millions for the countries of the continent 'South America'. Divide the population by 1000000 to get population in millions.
SELECT name, population/1000000
  FROM world
 WHERE continent = 'South America';
  1. Show the name and population for France, Germany, Italy.
SELECT name, population
  FROM world
 WHERE name IN ('France', 'Germany', 'Italy');
  1. Show the countries which have a name that includes the word 'United'.
SELECT name
  FROM world
 WHERE name LIKE 'United%';
  1. 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;
  1. Show the countries that are big by area or big by population but not both. Show name, population and area.
SELECT name, population, area
  FROM world
 WHERE area > 3000000
   XOR population > 250000000;
  1. 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';
  1. Show per-capita GDP for the trillion dollar countries to the nearest $1000.
SELECT name, ROUND(gdp/population, -3)
  FROM world
 WHERE gdp > 1000000000000;
  1. Show the name and capital where the name and the capital have the same number of characters.
SELECT name, capital
  FROM world
 WHERE LENGTH(name) = LENGTH(capital);
  1. 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.
SELECT name, capital
  FROM world
 WHERE LEFT(name, 1) = LEFT(capital, 1)
   AND name <> capital;
  1. Find the country that has all the vowels and no spaces in its name.
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 '% %';

03. SELECT From Nobel

  1. Change the query shown so that it displays Nobel prizes for 1950.
SELECT yr, subject, winner
  FROM nobel
 WHERE yr = 1950;
  1. Show who won the 1962 prize for Literature.
SELECT winner
  FROM nobel
 WHERE subject = 'Literature'
   AND yr = 1962;
  1. Show the year and subject that won 'Albert Einstein' his prize.
SELECT yr, subject
  FROM nobel
 WHERE winner = 'Albert Einstein';
  1. Give the name of the 'Peace' winners since the year 2000, including 2000.
SELECT winner
  FROM nobel
 WHERE subject = 'Peace'
   AND yr >= 2000;
  1. Show all details (yr, subject, winner) of the Literature prize winners for 1980 to 1989 inclusive.
SELECT yr, subject, winner
  FROM nobel
 WHERE subject = 'Literature'
   AND yr BETWEEN 1980 AND 1989;
  1. 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');
  1. Show the winners with first name John.
SELECT winner
  FROM nobel
 WHERE winner LIKE 'John%';
  1. Show the Physics winners for 1980 together with the Chemistry winners for 1984.
SELECT yr, subject, winner
  FROM nobel
 WHERE subject = 'Physics'   AND yr = 1980
    OR subject = 'Chemistry' AND yr = 1984;
  1. Show the winners for 1980 excluding the Chemistry and Medicine.
SELECT yr, subject, winner
  FROM nobel
 WHERE yr = 1980
   AND subject NOT IN ('Chemistry', 'Medicine');
  1. Show 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;
  1. Find all details of the prize won by PETER GRÜNBERG.
SELECT *
  FROM nobel
 WHERE winner = 'Peter Grünberg';
  1. Find all details of the prize won by EUGENE O'NEILL.
SELECT *
  FROM nobel
 WHERE winner = 'Eugene O\'neill';
  1. 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;
  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 ('Chemistry', 'Physics'), subject, winner;

04. SELECT Within SELECT

  1. 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');
  1. Show the countries in Europe with a per capita GDP greater than 'United Kingdom'.
SELECT name
  FROM world
 WHERE continent = 'Europe'
   AND gdp/population > (SELECT gdp/population
                           FROM world
                          WHERE name = 'United Kingdom');
  1. 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 IN ('Argentina', 'Australia'))
ORDER BY name;
  1. 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');
  1. 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';
  1. 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);
  1. 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);
  1. List each continent and the name of the country that comes first alphabetically.
SELECT continent, name
  FROM world x
 WHERE name <= ALL(SELECT name
                    FROM world y
                   WHERE y.continent = x.continent);
  1. 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 y.continent = x.continent
                          AND y.population > 0);
  1. Some countries have populations more than three times that of any 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 y.continent = x.continent
                           AND y.name <> x.name);

05. SUM and COUNT

  1. Show the total population of the world.
SELECT SUM(population)
  FROM world;
  1. List all the continents - just once each.
SELECT DISTINCT continent
           FROM world;
  1. Give the total GDP of Africa.
SELECT SUM(gdp)
  FROM world
 WHERE continent = 'Africa';
  1. How many countries have an area of at least 1000000.
SELECT COUNT(name)
  FROM world
 WHERE area > 1000000;
  1. What is the total population of ('Estonia', 'Latvia', 'Lithuania').
SELECT SUM(population)
  FROM world
 WHERE name IN ('Estonia', 'Latvia', 'Lithuania');
  1. For each continent show the continent and number of countries.
  SELECT continent, COUNT(name)
    FROM world
GROUP BY continent;
  1. 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;
  1. List the continents that have a total population of at least 100 million.
  SELECT continent
    FROM world
GROUP BY continent
  HAVING SUM(population) > 100000000;

06. JOIN

  1. Modify the example 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';
  1. Show id, stadium, team1, team2 for just game 1012.
SELECT id, stadium, team1, team2
  FROM game
 WHERE id = 1012;
  1. Modify the code to show the player, teamid, stadium and mdate and for every German goal.
SELECT player, teamid, stadium, mdate
  FROM game JOIN goal ON id = matchid
 WHERE teamid = 'GER';
  1. 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%';
  1. 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;
  1. List the 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';
  1. List the player for every goal scored in a game where the stadium was 'National Stadium, Warsaw'.
SELECT player
  FROM goal JOIN game ON matchid = id
 WHERE stadium = 'National Stadium, Warsaw';
  1. 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 goal JOIN game ON matchid = id
 WHERE (team1 = 'GER' OR team2 = 'GER')
   AND teamid != 'GER';
  1. Show teamname and the total number of goals scored.
  SELECT teamname, COUNT(teamid)
    FROM eteam JOIN goal ON eteam.id = teamid
GROUP BY teamname;
  1. 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;
  1. For every match involving 'POL', show the matchid, date and the number of goals scored.
  SELECT matchid, mdate, COUNT(*)
    FROM game JOIN goal ON id = matchid
   WHERE (team1 = 'POL' OR team2 = 'POL')
GROUP BY matchid, mdate;
  1. For every match where 'GER' scored, show matchid, match date and the number of goals scored by 'GER'.
  SELECT matchid, mdate, COUNT(*)
    FROM game JOIN goal ON id = matchid
   WHERE (team1 = 'GER' OR team2 = 'GER')
     AND teamid = 'GER'
GROUP BY matchid, mdate;
  1. List every match with the goals scored by each team as shown. Sort your result by mdate, matchid, team1 and team2.
   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 id = matchid

 GROUP BY mdate, team1, team2
 ORDER BY mdate, team1, team2;

07. More JOIN Operations

  1. List the films where the yr is 1962. Show id, title.
SELECT id, title
  FROM movie
 WHERE yr = 1962;
  1. Give year of 'Citizen Kane'.
SELECT yr
  FROM movie
 WHERE title = 'Citizen Kane';
  1. List all of the Star Trek movies, include the id, title and yr (all of these movies include the words Star Trek in the title). Order results by year.
  SELECT id, title, yr
    FROM movie
   WHERE title LIKE 'Star Trek%'
ORDER BY yr;
  1. What id number does the actor 'Glenn Close' have?
SELECT id
  FROM actor
 WHERE name = 'Glenn Close';
  1. What is the id of the film 'Casablanca'?
SELECT id
  FROM movie
 WHERE title = 'Casablanca';
  1. Obtain the cast list for 'Casablanca'.
SELECT name
  FROM movie
  JOIN casting ON movie.id = casting.movieid
  JOIN actor   ON actor.id = casting.actorid
 WHERE movieid = 11768;
  1. Obtain the cast list for the film 'Alien'.
SELECT name
  FROM movie
  JOIN casting ON movie.id = casting.movieid
  JOIN actor   ON actor.id = casting.actorid
 WHERE title = 'Alien';
  1. List the films in which 'Harrison Ford' has appeared.
SELECT title
  FROM movie
  JOIN casting ON movie.id = casting.movieid
  JOIN actor   ON actor.id = casting.actorid
 WHERE actor.name = 'Harrison Ford';
  1. List the films where 'Harrison Ford' has appeared - but not in the starring role. Note: the 'ord' field of casting gives the position of the actor. If 'ord=1' then this actor is in the starring role.
SELECT title
  FROM movie
  JOIN casting ON movie.id = casting.movieid
  JOIN actor   ON actor.id = casting.actorid
 WHERE actor.name = 'Harrison Ford'
   AND ord != 1;
  1. List the films together with the leading star for all 1962 films.
SELECT title, name
  FROM movie
  JOIN casting ON movie.id = casting.movieid
  JOIN actor   ON actor.id = casting.actorid
 WHERE yr = 1962
   AND ord = 1;
  1. Which were the busiest years for 'John Travolta', show the year and the number of movies he made each year for any year in which he made more than 2 movies.
  SELECT yr, COUNT(title)
    FROM movie
    JOIN casting ON movie.id = movieid
    JOIN actor   ON actorid = actor.id
   WHERE name = 'John Travolta'
GROUP BY yr
  HAVING COUNT(title) =
         (SELECT MAX(c)
            FROM (SELECT yr, COUNT(title) AS c
                    FROM movie
                    JOIN casting ON movie.id=movieid
                    JOIN actor   ON actorid=actor.id
                   WHERE name = 'John Travolta'
                GROUP BY yr) AS t);
  1. List the film title and the leading actor for all of the films 'Julie Andrews' played in.
SELECT title, name
  FROM casting
  JOIN movie ON casting.movieid = movie.id AND ord = 1
  JOIN actor ON casting.actorid = actor.id
 WHERE movie.id IN
       (SELECT movieid
          FROM casting
         WHERE actorid IN
         (SELECT id FROM actor
           WHERE name = 'Julie Andrews'));
  1. Obtain a list, in alphabetical order, of actors who've had at least 30 starring roles.
  SELECT name
    FROM actor
    JOIN casting ON casting.actorid = actor.id
    JOIN movie   ON casting.movieid = movie.id
   WHERE actorid IN
         (SELECT actorid
            FROM casting
           WHERE ord = 1
        GROUP BY actorid
          HAVING COUNT(actorid) >= 30)
GROUP BY name;
  1. 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 casting.movieid = movie.id
    JOIN actor   ON casting.actorid = actor.id
   WHERE yr = 1978
GROUP BY title
ORDER BY COUNT(actorid) DESC, title;
  1. List all the people who have worked with 'Art Garfunkel'.
SELECT DISTINCT name
  FROM actor
  JOIN casting ON casting.actorid = actor.id
  JOIN movie   ON casting.movieid = movie.id
 WHERE name != 'Art Garfunkel'
   AND movieid IN
       (SELECT movieid
          FROM casting
          JOIN actor ON casting.actorid = actor.id
          JOIN movie ON casting.movieid = movie.id
         WHERE name = 'Art Garfunkel');

08. Using NULL

  1. List the teachers who have NULL for their department.
SELECT name
  FROM teacher
 WHERE dept IS NULL;
  1. 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;
  1. 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;
  1. 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;
  1. 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;
  1. 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') AS deptartment
     FROM teacher
LEFT JOIN dept ON teacher.dept = dept.id;
  1. Use COUNT to show the number of teachers and the number of mobile phones.
SELECT COUNT(name)   AS teachers,
       COUNT(mobile) AS mobiles
  FROM teacher;
  1. 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.dept) AS staff
      FROM teacher
RIGHT JOIN dept ON teacher.dept = dept.id
  GROUP BY dept.name;
  1. 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 name,
       CASE WHEN dept = 1 OR dept = 2
            THEN 'Sci'
            ELSE 'Art'
        END AS dept
  FROM teacher;
  1. 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 name,
       CASE WHEN dept = 1 OR dept = 2
            THEN 'Sci'
            WHEN dept = 3
            THEN 'Art'
            ELSE 'None'
        END AS dept
  FROM teacher;

08+. Numeric Examples

  1. 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';
  1. 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;
  1. 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 subject = '(8) Computer Science'
   AND question = 'Q15'
   AND score < 50;
  1. 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)
         AS students
    FROM nss
   WHERE question = 'Q22'
     AND subject IN ('(8) Computer Science', '(H) Creative Arts and Design')
GROUP BY subject;
  1. 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)
         AS 'strongly agree'
    FROM nss
   WHERE question = 'Q22'
     AND subject IN ('(8) Computer Science', '(H) Creative Arts and Design')
GROUP BY subject;
  1. 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'.
  SELECT subject,
         ROUND(SUM(response * A_STRONGLY_AGREE) / SUM(response))
         AS 'strongly agree %'
    FROM nss
   WHERE question = 'Q22'
     AND subject IN ('(8) Computer Science', '(H) Creative Arts and Design')
GROUP BY subject;
  1. Show the average scores for question 'Q22' for each institution that include 'Manchester' in the name.
  SELECT DISTINCT institution,
         ROUND(SUM(response * score) / SUM(response))
         AS 'average scores'
    FROM nss
   WHERE question = 'Q22'
     AND institution LIKE '%Manchester%'
GROUP BY institution;
  1. 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 LIKE '(8)%'
                  THEN sample  END)
         AS 'computing students'
    FROM nss
   WHERE question = 'Q01'
     AND institution LIKE '%Manchester%'
GROUP BY institution;

09. Self JOIN

  1. How many stops are in the database.
SELECT COUNT(DISTINCT stop)
  FROM route
  JOIN stops ON route.stop = stops.id;
  1. Find the id value for the stop 'Craiglockhart'.
SELECT id
  FROM stops
 WHERE name = 'Craiglockhart';
  1. 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 num = '4'
   AND company = 'LRT';
  1. 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;
  1. 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;
  1. 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';
  1. Give a list of all the services which connect stops 115 and 137 ('Haymarket' and 'Leith').
SELECT DISTINCT a.company, a.num
  FROM route a, route b
 WHERE a.company = b.company AND a.num = b.num
   AND a.stop = 115
   AND b.stop = 137;
  1. 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.company = R2.company
   AND R1.num = R2.num
   AND R1.stop = S1.id
   AND R2.stop = S2.id
   AND S1.name = 'Craiglockhart'
   AND S2.name = 'Tollcross';
  1. 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.company = R2.company
   AND R1.num = R2.num
   AND R1.stop = S1.id
   AND R2.stop = S2.id
   AND S1.name = 'Craiglockhart';
  1. Find the routes involving two buses that can go from Craiglockhart to Sighthill. Show the bus no. and company for the first bus, the name of the stop for the transfer, and the bus no. and company for the second bus.
SELECT first_ride.start_num,
       first_ride.start_company,
       first_ride.transfer_stop,
       second_ride.end_num,
       second_ride.end_company

  FROM (SELECT DISTINCT R1.num AS start_num,
                        R1.company AS start_company,
                        S2.name AS transfer_stop

          FROM route R1, route R2,
               stops S1, stops S2

         WHERE R1.company = R2.company
           AND R1.num = R2.num
           AND R1.stop = S1.id
           AND R2.stop = S2.id
           AND S1.name = 'Craiglockhart') AS first_ride

  JOIN (SELECT DISTINCT S3.name AS transfer_stop,
                        R4.num AS end_num,
                        R4.company AS end_company

          FROM route R3, route R4,
               stops S3, stops S4

         WHERE R3.company = R4.company
           AND R3.num = R4.num
           AND R3.stop = S3.id
           AND R4.stop = S4.id
           AND S4.name = 'Sighthill') AS second_ride

 WHERE first_ride.transfer_stop = second_ride.transfer_stop;

Note: The order of the 'end_num' column in the result is not exactly the same.

sqlzoo's People

Contributors

lujanfernaud avatar

Watchers

James Cloos avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.