sql ex1

36
The Table Tennis Olympics Database The table ttms shows the Olympic medal winners for Table Tennis (Men's Sin country of each winner is given by a three letter code. To get the actual name you must JOIN this table to the country table. The two tables country and ttms are ONE TO MANY. One country has many winners, each winner has only one country. How to do joins. The phrase FROM ttms JOIN country ON ttms.country=country.id represents the join country. This JOIN has one row for every medal winner. In addition to the t who and country) it includes the details of the corresponding country (id, na 1a. Show the athelete (who) and the country name for medal winners in 2000. ttms(games, color, who, country) country(id, name) Results ttms games colo r who countr y 1988 gold Yoo Nam- Kyu KOR 1988 silv er Kim Ki Taik KOR .. .. .. ..

Upload: kochappen-ipe-kumar

Post on 20-Nov-2014

147 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: sql ex1

The Table Tennis Olympics Database

The table ttms shows the Olympic medal winners for Table Tennis (Men's Singles). The country of each winner is given by a three letter code. To get the actual country name you must JOIN this table to the country table.The two tables country and ttms are ONE TO MANY. One country has many winners, each winner has only one country.

How to do joins.

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

1a. Show the athelete (who) and the country name for medal winners in 2000. ttms(games, color, who, country)country(id, name)

Results

1b. Show the who and the color of the medal for the medal winners from 'Sweden'. ttms(games, color, who, country)country(id, name)

Results

ttms

games color who country

1988gold Yoo Nam-Kyu KOR

1988silver Kim Ki Taik KOR

.. .. .. ..

Page 2: sql ex1

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

Results

Women's Singles Table Tennis Olympics Database

The Summer Olympic games are held every four years in a different city. The table games shows which city the games were held in. The Women's Single's winners are in the table ttws.

ttws

games color who country

1988gold Jing Chen

CHN

1988silver Li Hui-Fen

CHN

.. .. .. ..

Page 3: sql ex1

2a. Show who won medals in the 'Barcelona' games. ttws(games, color, who, country)games(yr, city, country)

Results

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

Results

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

Results

Page 4: sql ex1

Table Tennis Mens Doubles

The Table Tennis Mens Double teams are stored in the table team. Each team has an arbitrary number that is referenced from the table ttmd.

ttmd

games color

1988gold

1988silver

.. ..

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

Results

3b. Show the 'gold' medal winners in 2004. ttmd(games, color, team, country)

Results

Page 5: sql ex1

team(id, name)

3c. Show the name of each medal winner country 'FRA'. ttmd(games, color, team, country)team(id, name)

Results

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 consists of three tables movie , actor and casting .

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

Page 6: sql ex1

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] movie(id, title, yr, score, votes, director)

Results

1b. Give year of 'Citizen Kane'. movie(id, title, yr, score, votes, director)

Results

Page 7: sql ex1

1c. 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.) movie(id, title, yr, score, votes, director)

Results

Looking at the id field.

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

Results

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

Results

Page 8: sql ex1

2c. What is the id of the film 'Casablanca' movie(id, title, yr, score, votes, director)

Results

Get to the point.

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

Results

Page 9: sql ex1

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

Results

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

Results

Page 10: sql ex1

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

Results

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

Results

Page 11: sql ex1

That's plenty joins for now. Students with an unhealthy interest in databases or movies may try the following harder questions; although they might be better advised to go out and get some fresh air.

4a. Which were the busiest years for 'John Travolta'. Show the number of movies he made for each year. movie(id, title, yr, score, votes, director)actor(id, name)casting(movieid, actorid, ord)

Results

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

Results

Page 12: sql ex1

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

Results

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

Results

Page 13: sql ex1

casting(movieid, actorid, ord)

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

Results

That is definitely enough. Students should, under no circumstances look at the next tutorial, concerning outer joins. Teachers and Departments

Page 14: sql ex1

The school includes many departments. Most teachers work exclusively for a single department. Some teachers have no department.

teacher

id dept name phone mobile

101 1Shrivell 275307986 555 1234

102 1Throd 275407122 555 1920

103 1Splint 2293

104 Spiregrain 3287

105 2Cutflower 321207996 555 6574

106 Deadyawn 3345

dept

id name

1Computing

2Design

3Engineering

Selecting NULL values

NULL, INNER JOIN, LEFT JOIN, RIGHT JOIN

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

Results

1b. Note the INNER JOIN misses the teacher with no department and the department with no teacher.

Results

Page 15: sql ex1

1c. Use a different JOIN so that all teachers are listed. Results

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

Using the COALESCE function

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

Results

Page 16: sql ex1

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

2b. Use the COALESCE function and a LEFT JOIN to print the name and department name. Use the string 'None' where there is no department.

Results

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

Results

Page 17: sql ex1

2d. 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..

Results

Using CASE

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

Results

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

Results

Page 18: sql ex1

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

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

Page 19: sql ex1

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

Routes and stops

2a. 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.

Results

2b. Execute the self join shown and observe that b.stop gives all the places you can get to from Craiglockhart. Change the query so that it shows the services from Craiglockhart to London Road.

Results

Page 20: sql ex1

2c. 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'

Results

Using a self join

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

Results

Page 21: sql ex1

3b. Give a list of the services which connect the stops 'Craiglockhart' and 'Tollcross'

Results

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

Edinburgh Buses

Details of the database. Looking at the data.

Results

Page 22: sql ex1

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

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

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

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

Page 23: sql ex1

Routes and stops

2a. 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.

Results

2b. Execute the self join shown and observe that b.stop gives all the places you can get to from Craiglockhart. Change the query so that it shows the services from Craiglockhart to London Road.

Results

Page 24: sql ex1

2c. 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'

Results

Using a self join

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

Results

Page 25: sql ex1

3b. Give a list of the services which connect the stops 'Craiglockhart' and 'Tollcross'

Results

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

Results

Page 26: sql ex1

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

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

Page 27: sql ex1

CREATE, DROP and ALTERHow 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 DELETEHow 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

Page 28: sql ex1

FUNCTIONSHow to use string functions, logical functions and mathematical functions.

Concatenate strings.

You can put two or more strings together using the concatentate operator. The SQL standard says you should use || but there are many differences between the main vendors. Specific to Oraclenone

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 in each of the SELECT statements.

SELECT name FROM customerUNIONSELECT name FROM employeeUNION SELECT name FROM artist

Specific to Oraclenone

Page 29: sql ex1

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 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 because ambia matches with the %.Specific to Oraclenone

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

Page 30: sql ex1

Get the date and time right now. Format dates.

USERSHow 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 DATAInformation 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 MessagesError 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

Page 31: sql ex1

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

Page 32: sql ex1

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