A basic introduction
James Brucker
Client
User
Interface &
communicati
on protocol
Databas
e
Manage
r
Control access to
the database.
authentication
enforce
permissions
data integrity
access services
Database: a
structured, selfdescribing collection
of data.
Server
mysqld
Java App
+JDBC client
Excel client
Client side
server controls
access to
database
Server side
Exercise
Exercise
Structure of a Database
USE bank;
sql> SHOW tables;
sql>
+----------------+
| Tables_in_bank |
+----------------+
| accounts
|
| clients
|
+----------------+
A Database Structure
Database
Schema
Schema
Table
Table
Table
Table
field1: t1
field2: t2
field3: t3
field1: t1
field2: t2
field3: t3
field1: t1
field2: t2
field3: t3
field1: t1
field2: t2
field3: t3
indexes
indexes
indexes
indexes
Contents of a Table
records
(rows)
+------+------------+-------+-------------+---------+
| ID
| Name
| CCode | District
| Populatn
+------+---------------+------------------+--------+
| 3320 | Bangkok
| THA
| Bangkok
| 6320174 |
| 3321 | Nonthaburi | THA
| Nonthaburi | 292100 |
| 3323 | Chiang Mai | THA
| Chiang Mai | 171100 |
+------+------------+-------+-------------+---------+
fields (columns)
Structure of a Table
Every field has:
a name
a data type and length
To view the structure of a table use:
DESCRIBE tablename
sql>
DESCRIBE City;
+-------------+-----------+-----+-----+---------+----------------+
| Field
| Type
| Null| Key | Default | Extra
|
+-------------+-----------+-----+-----+---------+----------------+
| ID
| int(11)
| NO | PRI |
| auto_increment |
| Name
| char(35) | NO |
|
|
|
| CountryCode | char(3)
| NO |
|
|
|
| District
| char(20) | NO |
|
|
|
| Population | int(11)
| NO |
| 0
|
|
+-------------+-----------+-----+-----+---------+----------------+
Structure of a Table
"SHOW columns FROM tablename"
shows the same information.
sql>
+-------------+-----------+-----+-----+---------+----------------+
| Field
| Type
| Null| Key | Default | Extra
|
+-------------+-----------+-----+-----+---------+----------------+
| ID
| int(11)
| NO | PRI |
| auto_increment |
| Name
| char(35) | NO |
|
|
|
| CountryCode | char(3)
| NO |
|
|
|
| District
| char(20) | NO |
|
|
|
| Population | int(11)
| NO |
| 0
|
|
+-------------+-----------+-----+-----+---------+----------------+
Exercise
1. Connect to MySQL server on host "se.cpe.ku.ac.th".
Exercise
Omit the semi-colon. What happens?
No semi-colon.
DESCRIBE
DESCRIBE shows the structure of a table.
Exercise
For the world database:
DESCRIBE city;
mysql> describe city;
mysql>
use world;
mysql> use WORLD;
mysql> describe city;
mysql> describe City;
mysql>
records
(rows)
Object Oriented
__________________
__________________
__________________
+------+------------+--------------+---------+
| ID
| Name
| District
| Popula..}
+------+------------+--------------+---------+
| 3320 | Bangkok
| Bangkok
| 6320174 |
| 3321 | Nonthaburi | Nonthaburi
| 292100 |
| 3323 | Chiang Mai | Chiang Mai
| 171100 |
+------+------------+--------------+---------+
fields (columns)
Qualifying Names
World.city
city.name
World.city.name
INSERT
UPDATE
DELETE
What is CRUD?
Programmers call these operations "CRUD".
What does CRUD stand for?
Qualifying SELECT
Strings in SQL
Exercises
1. What are the first 3 cities in the database?
2. What are the 3 most populous countries in the world?
3. What is the smallest country in the world? How big?
WHERE conditions
name = 'Bangkok'
equality test
pattern match
relations
grade IN
('A','B','C','D','F')
contained in set
Count Function
Select can be used with functions, such as COUNT:
SELECT COUNT(*) FROM accounts
WHERE balance=0;
sql>
+----------+
| count(*) |
+----------+
|
4 |
+----------+
sql>
Exercise
1. How many countries are in the database?
2. How many cities are in China?
3. How many countries are in Europe?
SELECT functions
Exercise
1. What is the total GNP of the entire world?
world?
sql> SELECT name, GNP/population
FROM country
ORDER BY GNP/population DESC
LIMIT 20;
What are the most crowded countries (people per surface
area) in Asia?
AS capita_gnp
alias
Exercise
1. What countries are the richest? Poorest?
Exercise
sql>
Exercise
UPDATE statement
Change values in one or more records:
UPDATE table
SET field1=value1, field2=value2
WHERE condition;
sql>
UPDATE city
SET population=40000
WHERE name='Bangsaen' AND countrycode='THA';
sql>
UPDATE country
SET population=68100000, gnp=345600
WHERE code='THA';
Oops!
I forgot "WHERE ..."
Exercise
Deleting Records
sql>
Safer Delete
Relating Tables
The power of a relational database is the
ability to selectively combine data from
many tables.
Keys
Every table should have a primary key that uniquely identifies each row.
City
ID (PK)
Name
CountryCode (FK)
Population
District
CountryCode
Country
Code (PK)
Name
Continent
Capital
...
Joining Tables
Country.name
1
Country
Code (PK)
Name
Continent
Capital
...
City.countrycode = Country.code
City
Country.Code = City.CountryCode
ID
Name
CountryCode
District
Population
Exercise
1. How can we find the name of the capital city for each
country?
Country
Code (PK)
Name
Continent
Region
SurfaceArea
Population
GNP
LocalName
Capital
City
ID (PK)
Name
CountryCode
District
Population
Exercise Solution
List the country name and capital city name, for all
countries in Asia.
Exercise
1. How can we join the CountryLanguage table with the
County table?
Country
Code (PK)
Name
Continent
Region
SurfaceArea
Population
GNP
LocalName
Capital
CountryLanguage
CountryCode
Language
isOfficial
Percentage
Exercise
1. In what countries is the Thai language spoken?
2. By what percentage of the people?
Example:
SELECT
alias for
CountryLanguage
Exercise
1. What countries use English?
language?
Harder
3. In the world, approximately how many people speak
English?
JOIN
Joins tables
Many forms:
NATURAL JOIN
CONDITION JOIN
Exercise
GROUP BY ...
GROUP BY ... is used when you want to apply a
function (count, sum, avg) to a group of rows having a
common characteristic.
Example: How many countries are in each continent?
SELECT continent, count(*) FROM country
GROUP BY continent
GROUP BY Exercise
What is the total population of each continent?
use sum(population) and GROUP BY
Logical operations
OR
SELECT * FROM City WHERE
District='Songkhla' OR District='Bangkok';
AND
SELECT Name, SurfaceArea FROM Country WHERE
Continent = 'Africa' AND SurfaceArea > 1000000;
NOT
SELECT * FROM Accounts WHERE
NOT AvailableBalance = 0;
Set operations
IN
SELECT * FROM City WHERE
District IN ('Songkhla', 'Bangkok');
form of monarchy?
???
Getting Help
Online help for
HELP for the mysql command
HELP for SQL statements
mysql> HELP
mysql> HELP SELECT
If MySql doesn't have help on SQL commands, then load the "help
tables" data onto your server. Download help table data from:
http://dev.mysql.com/downloads in the "Documentation" section.
Subqueries
Subquery
To use subqueries in MySQL you need version 4.1 or newer.
Exercise
Exercise
Exercise
Is Thailand richer than other countries in Southest Asia?
SELECT ...
FROM Country
WHERE region = (SELECT region WHERE ...)
ORDER BY ...;
order the results by wealth
CREATE
ALTER
DROP
RENAME
rename a Table
Creating a Table
To add a new table to a database:
CREATE TABLE tablename
(field1, field2, ... )
options ;
Productivity Hint
Exercise
Deleting a Table
Remove a table from the database
Views
MyView
Name
Language
Percentage
View Example
Create a view for country name, languages, and
percentage.
sql> CREATE VIEW lang
AS
SELECT name, language, percentage
FROM Country C, CountryLanguage L
WHERE C.code = L.countrycode
ORDER BY language ASC;
Query OK, 0 rows affected.
Productivity Hint
Exercise
Exercise
Exercise
Review
What is the command to ...
1. list all the databases that you have access to?
2. use the Bank database?
3. view a list of tables in Bank?
4. view the structure of the Accounts table?
SQL Quiz
Database Game
Vocabulary
Language Hints
WRONG: 12345.6789
SELECT ...
FROM Country C
JOIN CountryLanguage L
ON C.code = L.countrycode
WHERE ...
SELECT
FROM
JOIN
ON
WHERE
...
Country C
CountryLanguage L
C.code = L.countrycode
...
SELECT L.language,
sum(L.percentage*C.population) AS sum
FROM Country C
JOIN CountryLanguage L
ON C.code = L.countrycode
GROUP BY L.language
ORDER BY sum DESC
+-----------------+------------+-------------------------+
| name
| population | country_name
|
+-----------------+------------+-------------------------+
...
| Bangkok
|
6320174 | Thailand
|
...
4 official languages?
What country in Europe has 4 official languages?
SELECT
FROM
JOIN
ON
WHERE
GROUP
HAVING
...
Country C
CountryLanguage L
C.code = L.countrycode
...
BY C.code -- group by country
...
Resources
MySQL
http://dev.mysql.com/tech-resources/articles/
Learning SQL
http://www.w3schools.com/sql/
nice tutorial and command reference