SQL Labsheet
SQL Labsheet
Required Software
1. mysql command line client. This is included in the mysql-essentials package or MySQL
Community Edition from www.mysql.com.
2. (Optional) Visual query tool for MySQL. The free MySQL Workbench (requires Visual C++
redistribution pack and .Net 4.0) or MySQL GUI Tools (does not require C++) are GUI tools for
accessing MySQL.
2. World database. You will use the database on se.cpe.ku.ac.th (nothing to install.) But,
if you want your own World database, see separate instructions for how to install.
Format of Exercises
Write the SQL command you use to get the data. If the result is requested, write that, too.
Table: Country
Field Name Type Can be Null? Key? Default
Code char(3) NO
Name char(52) NO
Continent enum NO 'Asia'
Region char(26) NO
SurfaceArea float NO
IndepYear smallint YES
Population integer NO
LifeExpectancy float YES
GNP float YES
LocalName char(45) NO
GovernmentForm char(45) NO
Capital integer YES
Code2 char(2) NO
Table: CountryLanguage
Field Name Type Can be Null? Key? Default
CountryCode NO
Language NO
IsOfficial NO 'F'
Percentage NO 0.0
3 Querying Data
The SELECT command returns data from tables.
SELECT * FROM tablename
SELECT * FROM tablename LIMIT n (only return n results)
SELECT field1, field2, field3 FROM tablename WHERE condition [ LIMIT n ]
SELECT fields FROM tablename WHERE condition ORDER BY field [ASC|DESC]
Answer:
Answer:
4.4 What is the total GNP of the world (in millions USD)?
sql>
Answer:
Answer:
Answer:
6 Modifying a Record
To change some values, use:
UPDATE tablename SET field1=value1, field2=value2 WHERE condition
Example: The "head of state" in the U.S.A. is now Barrack Obama.
UPDATE Country SET HeadOfState='Barrack Obama' WHERE code='USA';
6.2 What is the SQL to change the population of your City, using the City primary key?
sql>
SQL Database Lab Page 7
7 Deleting Data
DELETE FROM tablename WHERE condition
Example: delete all cities in Thailand named "Bangsaen":
DELETE FROM City WHERE name='Bangsaen' AND countrycode='THA';
7.1 What is the command to delete the City that you added to the database?
sql>
9 JOIN Tables
A more semantic way of combining tables is to use JOIN
SELECT field1, field2, ...
FROM table1
JOIN table2
ON table1.field = table2.field
SQL Database Lab Page 8
WHERE ... ORDER BY ...
You can assign an alias to table names to reduce typing. You can assign an alias to fields or
expressions, too.
Example: Print the capital city of the countries in Europe:
SELECT c.Name, co.Name AS CountryName, co.Region
FROM Country co
JOIN City c
ON co.Capital = c.ID
WHERE co.Continent = 'Europe'