0% found this document useful (0 votes)
1K views27 pages

The Table Tennis Olympics Database: Ttms Games Color Who Country

This document provides examples of using SQL queries to join data from multiple tables in a movie database. It includes tables for movies, actors, and a casting table to link movies and actors. The examples show how to: 1) Find movie information like year and title using the movie ID or title from another query. 2) Look up actor IDs from their names and movie IDs from titles. 3) Retrieve cast lists for movies by joining the casting and actor tables on movie and actor IDs. 4) Find all movies that an actor appeared in, with options to filter for lead roles only.
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1K views27 pages

The Table Tennis Olympics Database: Ttms Games Color Who Country

This document provides examples of using SQL queries to join data from multiple tables in a movie database. It includes tables for movies, actors, and a casting table to link movies and actors. The examples show how to: 1) Find movie information like year and title using the movie ID or title from another query. 2) Look up actor IDs from their names and movie IDs from titles. 3) Retrieve cast lists for movies by joining the casting and actor tables on movie and actor IDs. 4) Find all movies that an actor appeared in, with options to filter for lead roles only.
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 27

The Table Tennis Olympics Database

The table ttms shows the Olympic medal winners for Table Tennis (Men's Singles). The country of
given by a three letter code. To get the actual country name you must JOIN this table to the countr
The two tables country and ttms are
ONE TO MANY. One country has
many winners, each winner has only
one country.
ttms
games color who country
1988 gold Yoo Nam-Kyu KOR
1988 silver Kim Ki Taik KOR
.. .. .. ..

How to do joins.
The phrase FROM ttms JOIN country ON ttms.country=country.id represents the join of the tables
one row for every medal winner. In addition to the ttms fields (games, color, who and country) it inclu
corresponding country (id, name ).

1a. Show the athelete (who) and the country name for medal winners in 2000. Results
ttms(games, color, who, country)
country(id, name)
SELECT w ho, country.name
FROM ttms JOIN country
ON (ttms.country=country.id)
WHERE games = 2000

1b. Show the who and the color of the medal for the medal winners from Results
'Sweden'.
ttms(games, color, who, country)
country(id, name)
SELECT w ho, color
FROM ttms JOIN country
ON (ttms.country=country
WHERE country.name = 'Sw ed

1c. Show the years in which 'China' won a 'gold' medal. Results
ttms(games, color, who, country)
country(id, name)

SELECT games
FROM ttms JOIN country
ON (ttms.country=country
WHERE name='China' AND color

Women's Singles Table Tennis Olympics Database


The Summer ttws
Olympic games games color who c
are held every four
years in a different 1988 gold Jing CH
city. The table Chen
games shows which 1988 silver Li CH
city the games Hui-
were held in. The Fen
Women's Single's .. .. .. ..
winners are in the
table ttws.
2a. Show who won medals in the 'Barcelona' games. Results
ttws(games, color, who, country)
games(yr, city, country)
SELECT w ho, city
FROM ttw s JOIN games
ON (ttw s.games=games.yr)
WHERE city = 'Seoul'

SELECT w ho
FROM ttw s JOIN games
ON (ttw s.games=games
WHERE city = 'Barcelona'

2b. Show which city 'Jing Chen' won medals. Show the city and the medal Results
color.
ttws(games, color, who, country)
games(yr, city, country)

SELECT city, color


FROM ttw s JOIN games
ON (ttw s.games=games
WHERE w ho = 'Jing Chen'

2c. Show who won the gold medal and the city. Results
ttws(games, color, who, country)
games(yr, city, country)

SELECT w ho, city


FROM ttw s JOIN games
ON (ttw s.games=games
WHERE color = 'gold'

Table Tennis Mens Doubles


The Table Tennis Mens t
Double teams are stored in games colo
the table team. Each team
1988 gold
has an arbitrary number that
is referenced from the table 1988 silver
ttmd. .. ..

3a. Show the games and color of the medal won by the team that includes Results
'Yan Sen'.
ttmd(games, color, team, country)
team(id, name)

SELECT games, color


FROM ttmd JOIN team ON team
WHERE name = 'Yan Sen'

3b. Show the 'gold' medal winners in 2004. Results


ttmd(games, color, team, country)
team(id, name)

SELECT name
FROM ttmd JOIN team ON team
WHERE color='gold' AND games
3c. Show the name of each medal winner country 'FRA'. Results
ttmd(games, color, team, country)
team(id, name)

SELECT name
FROM ttmd JOIN team ON team
WHERE country = 'FRA'

The next tutorial about the Movie database involves some slightly more complicated joins.
Movie Database
This tutorial introduces the notion of a join. The database con
movie , actor and casting .

movie(id, title, yr, score, votes, director)


actor(id, name)
casting(movieid, actorid, ord)
More details about the database.
Let's go to work.
Limbering up
1a. List the films where the yr is 1962 [Show id, title] Results
movie(id, title, yr, score, votes, director)
SELECT id, title
FROM movie
WHERE yr=1962
1b. Give year of 'Citizen Kane'. Results
movie(id, title, yr, score, votes, director)

SELECT yr FROM movie WHERE

1c. List all of the Star Trek movies, include the id title and yr. (All of these Results
movies include the words Star Trek in the title.)
movie(id, title, yr, score, votes, director)

SELECT id,title, yr FROM movie


WHERE title LIKE 'Star Trek%'
ORDER BY yr

Looking at the id field.


2a. What are the titles of the films with id 1, 2, 3 Results
movie(id, title, yr, score, votes, director)
SELECT title FROM movie WHER

2b. What id number does the actor 'Glenn Close' have? Results
movie(id, title, yr, score, votes, director)
actor(id, name)
casting(movieid, actorid, ord)

SELECT id FROM actor


WHERE name= 'Glenn Close'

2c. What is the id of the film 'Casablanca' Results


movie(id, title, yr, score, votes, director)

SELECT id FROM movie WHERE

Get to the point.


3a. Obtain the cast list for 'Casablanca'. Use the id value that you obtained in Results
the previous question.
actor(id, name)
casting(movieid, actorid, ord)
SELECT name
FROM casting, actor
WHERE movieid=(SELECT id FR
AND actorid=actor.id

3b. Obtain the cast list for the film 'Alien' Results
movie(id, title, yr, score, votes, director)
actor(id, name)
casting(movieid, actorid, ord)

SELECT name
FROM movie, casting, actor
WHERE title='Alien'
AND movieid=movie.id

3c. List the films in which 'Harrison Ford' has appeared Results
movie(id, title, yr, score, votes, director)
actor(id, name)
casting(movieid, actorid, ord)

SELECT title
FROM movie, casting, actor
WHERE name='Harrison Ford'
AND movieid=movie.id
3d. List the films where 'Harrison Ford' has appeared - but not in the star role. Results
movie(id, title, yr, score, votes, director)
actor(id, name)
casting(movieid, actorid, ord)

SELECT title
FROM movie, casting, actor
WHERE name='Harrison Ford'
AND movieid=movie.id

3e. List the films together with the leading star for all 1962 films. Results
movie(id, title, yr, score, votes, director)
actor(id, name)
casting(movieid, actorid, ord)

SELECT title, name


FROM movie, casting, actor
WHERE yr=1962
AND movieid=movie.id

That's plenty joins for now. Students with an unhealthy intere


movies may try the following harder questions; although t
advised to go out and get some fresh air.
4a. Which were the busiest years for 'John Travolta'. Show the number of Results
movies he made for each year.
movie(id, title, yr, score, votes, director)
actor(id, name)
casting(movieid, actorid, ord)

SELECT yr,COUNT(title) FROM


movie JOIN casting ON movie.i
JOIN actor ON actorid=ac
w here name='John Travolta'

4b. List the film title and the leading actor for all of 'Julie Andrews' films. Results
movie(id, title, yr, score, votes, director)
actor(id, name)
casting(movieid, actorid, ord)

SELECT title, name


FROM movie, casting, actor
WHERE movieid=movie.id
AND actorid=actor.id

4c. Obtain a list of actors in who have had at least 10 starring roles. Results
movie(id, title, yr, score, votes, director)
actor(id, name)
casting(movieid, actorid, ord)
SELECT name
FROM casting JOIN actor
ON actorid = actor.id
WHERE ord=1

4d. List the 1978 films by order of cast list size. Results
movie(id, title, yr, score, votes, director)
actor(id, name)
casting(movieid, actorid, ord)

SELECT title, COUNT(actorid)


FROM casting, movie
WHERE yr=1978
AND movieid=movie.id

4e. List all the people who have worked with 'Art Garfunkel'. Results
movie(id, title, yr, score, votes, director)
actor(id, name)
casting(movieid, actorid, ord)

SELECT DISTINCT name


FROM actor, casting
WHERE actorid=actor.id
AND movieid IN (

That is definitely enough. Students should, under no circums


next tutorial, concerning outer joins.
Teachers and Departments
The school includes many departments. Most teachers work exclusively for a single department. So
department.

teacher dept
id dept name phone mobile id name
101 1 Shrivell 2753 07986 555 1234 1 Computing
102 1 Throd 2754 07122 555 1920 2 Design
103 1 Splint 2293 3 Engineering
104 Spiregrain 3287
105 2 Cutflower 3212 07996 555 6574
106 Deadyawn 3345

Selecting NULL values

NULL, INNER JOIN, LEFT JOIN, RIGHT JOIN


1a. List the teachers who have NULL for their department. Results
Why we cannot use =

SELECT name FROM teacher W

1b. Note the INNER JOIN misses the teacher with no department and the Results
department with no teacher.
SELECT teacher.name, dept.name
FROM teacher INNER JOIN dept
ON (teacher.dept=dept.id)

SELECT teacher.name, dept.nam


FROM teacher INNER JOIN dept
ON (teacher.dept=dept.id
1c. Use a different JOIN so that all teachers are listed. Results

SELECT teacher.name, dept.nam


FROM teacher LEFT JOIN dept

1d. Use a different JOIN so that all departments are listed. Results

SELECT teacher.name, dept.nam


FROM teacher RIGHT JOIN dep

Using the COALESCE function

2a. Use COALESCE to print the mobile number. Use the number '0131 444 Results
2266' there is no number given.

Show teacher name and mobile number or '07986 444 2266'

SELECT name, COALESCE(mob

2b. Use the COALESCE function and a LEFT JOIN to print the name and Results
department name. Use the string 'None' where there is no department.
SELECT teacher.name, COALES
FROM teacher LEFT JOIN dept
ON teacher.dept=dept.

2c. Use COUNT to show the number of teachers and the number of mobile Results
phones.

SELECT COUNT(teacher.name),
FROM teacher

2d. Use COUNT and GROUP BY dept.name to show each department and Results
the number of staff. Use a RIGHT JOIN to ensure that the Engineering
department is listed..

SELECT dept.name, COUNT(tea


FROM teacher RIGHT JOIN dep
ON teacher.dept=dept.
GROUP BY dept.name

Using CASE

3a. Use CASE to show the name of each teacher followed by 'Sci' if the the Results
teacher is in dept 1 or 2 and 'Art' otherwise.
SELECT name, CASE WHEN dep
ELSE 'Art' END
FROM teacher

3b. Use CASE to show the name of each teacher followed by 'Sci' if the the Results
teacher is in dept 1 or 2 show 'Art' if the dept is 3 and 'None' otherwise.

SELECT name, CASE WHEN dep


WHEN dept = 3 THEN
ELSE 'None' END
FROM teacher

Edinburgh Buses
Details of the database. Looking at the data.

stops(id, name)
route(num,company,pos, stop)

1a. How many stops are in the database. Results

SELECT COUNT(*) FROM stops

1b. Find the id value for the stop 'Craiglockhart' Results

SELECT id FROM stops WHERE

1c. Give the id and the name for the stops on the '4' 'LRT' service. Results
SELECT id, name FROM stops, r
WHERE id=stop
AND company='LRT'
AND num='4'

Routes and stops

2a. The query shown gives the number of routes that visit either London Results
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

SELECT company, num, COUNT


FROM route WHERE stop=149 O
GROUP BY company, num
HAVING COUNT(*)=2

2b. Execute the self join shown and observe that b.stop gives all the places Results
you can get to from Craiglockhart.
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

SELECT a.company, a.num, a.st


FROM route a JOIN route b ON
(a.company=b.company AND a
WHERE a.stop = 149 AND b.sto

2c. The query shown is similar to the previous one, however by joining two Results
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'

SELECT a.company, a.num, stop


FROM route a JOIN route b ON
(a.company=b.company AND a
JOIN stops stopa ON (a.stop=s

Using a self join

3a. Give a list of all the services which connect stops 115 and 137 Results
('Haymarket' and 'Leith')

SELECT R1.company, R1.num


FROM route R1, route R2
WHERE R1.num=R2.num AND
AND R1.stop=115 AND R2.st

3b. Give a list of the services which connect the stops 'Craiglockhart' and Results
'Tollcross'
SELECT R1.company, R1.num
FROM route R1, route R2, stop
WHERE R1.num=R2.num AND
AND R1.stop=S1.id AND R2.s

3c. Give a list of the stops which may be reached from 'Craiglockhart' by taking one Results
bus. Include the details of the appropriate service.
Edinburgh Buses
Details of the database. Looking at the data.

stops(id, name)
route(num,company,pos, stop)

1a. How many stops are in the database. Results

SELECT COUNT(*) FROM stops

1b. Find the id value for the stop 'Craiglockhart' Results

SELECT id FROM stops WHERE

1c. Give the id and the name for the stops on the '4' 'LRT' service. Results

SELECT id, name FROM stops, r


WHERE id=stop
AND company='LRT'
AND num='4'
Routes and stops

2a. The query shown gives the number of routes that visit either London Results
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

SELECT company, num, COUNT


FROM route WHERE stop=149 O
GROUP BY company, num
HAVING COUNT(*)=2

2b. Execute the self join shown and observe that b.stop gives all the places Results
you can get to from Craiglockhart.
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

SELECT a.company, a.num, a.st


FROM route a JOIN route b ON
(a.company=b.company AND a
WHERE a.stop = 149 AND b.sto

2c. The query shown is similar to the previous one, however by joining two Results
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'

SELECT a.company, a.num, stop


FROM route a JOIN route b ON
(a.company=b.company AND a
JOIN stops stopa ON (a.stop=s

Using a self join

3a. Give a list of all the services which connect stops 115 and 137 Results
('Haymarket' and 'Leith')

SELECT R1.company, R1.num


FROM route R1, route R2
WHERE R1.num=R2.num AND
AND R1.stop=115 AND R2.st

3b. Give a list of the services which connect the stops 'Craiglockhart' and Results
'Tollcross'
SELECT R1.company, R1.num
FROM route R1, route R2, stop
WHERE R1.num=R2.num AND
AND R1.stop=S1.id AND R2.s

3c. Give a list of the stops which may be reached from 'Craiglockhart' by Results
taking one bus. Include the details of the appropriate service.

SELECT S2.id, S2.name, R2.com


FROM stops S1, stops S2, rou
WHERE S1.name='Craiglockha
AND S1.id=R1.stop

3d. Show how it possible to get from Sighthill to Craiglockhart. Results

SELECT a.name Start_At, b.num


e.name Change_At, f.num S
f.company SBC,
g.name Arrive_At

SELECT S2.id, S2.name, R2.com


FROM stops S1, stops S2, rou
WHERE S1.name='Craiglockha
AND S1.id=R1.stop

3d. Show how it possible to get from Sighthill to Craiglockhart. Results


SELECT a.name Start_At, b.num
e.name Change_At, f.num S
f.company SBC,
g.name Arrive_At

CREATE, DROP and ALTER


How to create tables, indexes, views and other things. How to get rid of them.
How to change them.

• CREATE a new table


• DROP an unwanted table
• Composite primary key
• Composite foreign key
• CREATE a VIEW.
• Create a table with an autonumber field (also known as sequence,
identity)
• ALTER TABLE ... ADD COLUMN
• ALTER TABLE ... DROP COLUMN
• ALTER TABLE ... ADD constraint
• CREATE TABLE problems: Invalid column name.
• CREATE TABLE problems: Insufficient privileges.
• CREATE TABLE problems: Table already exists.
• DROP TABLE problems: Foreign key references.
• CREATE TABLE problems: Foreign key references.
• rename column

INSERT, UPDATE and DELETE


How to put records into a table, change them and how to take them out again.

• INSERT is used to add records.


• UPDATE can change an existing record.
• DELETE removes records.
• 'INSERT..SELECT' copies data from a SELECT into a table.
• INSERT: Not all fields need be specified. Default values may be specified
in the CREATE TABLE clause - otherwise NULL is used.
• Insert a date.
• Explicitly enter a NULL.
• Can't INSERT because of reference.
• Cannot DELETE because of reference.
• Can't insert data because of incompatable formats.
• String contains a quote '
• to select the data from 20 different columns into one changing the values
according to one other column consisting the positions of the 20 columns

FUNCTIONS
How to use string functions, logical functions and mathematical functions.

• Concatenate strings.

You can put two or more strings SELECT region || name


FROM bbc
together using the concatentate
operator. The SQL standard says you
should use || but there are many
differences between the main vendors.
Submit Query Reset
Specific to Oracle
none
Related links:
• SELECT
o Concatenate two or more fields.
o Make union between different tables to build one single view or
request?
o Use 'like' in a sql select statement
o How to build a statement on a word with an Apostrophe such as
WHERE name='Tom's Book'
o Full text search
o Display a column name for an aggregate function.
o How do you use Equi Join to join two tables with the same name.
o Use SELECT for a column whose name contains spaces.
o use NULL

• Substring: Extracting part of a string.

List a number of SELECT


statements separated by the
UNION key word. Be sure that you
have the same number of columns SELECT name FROM actor WHERE name LIKE 'Z%'
UNION
in each of the SELECT statements. SELECT title FROM movie WHERE title LIKE 'Z%'

SELECT name FROM customer


UNION
SELECT name FROM employee Submit Query Reset
UNION
SELECT name FROM artist

Specific to Oracle
none
Related links:
• SELECT
o Concatenate two or more fields.
o Make union between different tables to build one single view or
request?
o Use 'like' in a sql select statement
o How to build a statement on a word with an Apostrophe such as
WHERE name='Tom's Book'
o Full text search
o Display a column name for an aggregate function.
o How do you use Equi Join to join two tables with the same name.
o Use SELECT for a column whose name contains spaces.
o use NULL

The LIKE command allows "Wild SELECT name FROM bbc


WHERE name LIKE 'Z%'
cards". A % may be used to match and
string, _ will match any single character.

The example shows countries begining


with Z. The country Zambia matches Submit Query Reset

because ambia matches with the %.


Specific to Oracle
none
Related links:
• SELECT
o Concatenate two or more fields.
o Make union between different tables to build one single view or
request?
o Use 'like' in a sql select statement
o How to build a statement on a word with an Apostrophe such as
WHERE name='Tom's Book'
o Full text search
o Display a column name for an aggregate function.
o How do you use Equi Join to join two tables with the same name.
o Use SELECT for a column whose name contains spaces.
o use NULL

• lower case
• Finding a substring in a string
• Formatting numbers to two decimal places.
• Replace a NULL with a specific value
• Conditional values
• Get the date and time right now.
• Format dates.

USERS
How to create users, give them access, get at other peoples tables. How to find
processes and kill them.

• Create a new user.


• Read tables from another schema/database
• Change the default schema/database.
• Find another process and kill it.
• Set a timeout.
• Change my own password
• Who am I?

META DATA
Information about the database: what tables exist, what are the column headings,
what database is in use.

• What are my tables?


• What are the columns of the cia table?
• Get the first 10 rows of the gisq.cia table.
• Get the 11th to the 20th rows of the cia table - by population.
• What version of the software am I using?
• What is the syntax to view structure of table?
• How can you determine the primary key using SQL?
• Return a sequential record count for all records returned

Error Messages
Error messages, how they are caused and what can be done about them.
MySQL
• Error 1052 Column 'name' in field list is ambiguous

• Error 1111 Invalid use of group function

• Error 1140 Mixing of GROUP columns (MIN(),MAX(),COUNT(),...) with no


GROUP columns is illegal if there is no GROUP BY clause

• Error 1146 Table 'gisq.Bbc' doesn't exist

SQL Server
• Msg 1013, Ambiguous column name 'name'.

• Msg 147 An aggregate may not appear in the WHERE clause unless it is
in a subquery contained in a HAVING clause or a select list, and the
column being aggregated is an outer reference.

• Msg 208 Invalid object name 'noSuchTable'

• Msg 8120 Column 'xxx' is invalid in the select list because it is not
contained in either an aggregate function or the GROUP BY clause. (SQL-
42000)

Oracle
• ORA-00918: column ambiguously defined

• ORA-00934: group function is not allowed here

• ORA-00937: not a single-group group function

• ORA-00942: table or view does not exist

• ORA-00979: not a GROUP BY expression

DB2
• SQL0203N A reference to column "NAME" is ambiguous.
SQLSTATE=42702

• SQL0120N A WHERE clause, GROUP BY clause, SET clause, or SET


transition-variable statement contains a column function.
• SQL0204N "GISQ.NOSUCHTABLE" is an undefined name

• SQL0119N An expression starting with "xxx" specified in a SELECT


clause, HAVING clause, or ORDER BY clause is not specified in the
GROUP BY clause or it is in a SELECT clause, HAVING clause, or
ORDER BY clause with a column function and no GROUP BY clause is
specified. SQLSTATE=42803

Postgres
• Error 7 ERROR: Column reference "name" is ambiguous

• ERROR: Aggregates not allowed in WHERE clause

• ERROR: Relation "nosuchtable" does not exist

• Error 7 ERROR: Attribute xxx.xxx must be GROUPed or used in an


aggregate function

You might also like