Database Access using SQL A basic introduction James Brucker.

114
Database Access using SQL A basic introduction James Brucker

Transcript of Database Access using SQL A basic introduction James Brucker.

Page 1: Database Access using SQL A basic introduction James Brucker.

Database Access using SQL

A basic introduction

James Brucker

Page 2: Database Access using SQL A basic introduction James Brucker.

Database Management System

Database: a structured, self-describing collection of data.

Control access to the database. • authentication• enforce permissions• data integrity• access services

Database

Manager

User Interface & communication protocol

SELECT * FROM city WHERE name LIKE Ban%

Client

Page 3: Database Access using SQL A basic introduction James Brucker.

Client - Server Databases

Database Server is a separate process on a host. Clients can be on any machine. Many programs may be clients using a standard API.

Servermysqld

"mysql" utility

Java App +JDBC client

Excel client

Server sideClient side

server controls access to database

Page 4: Database Access using SQL A basic introduction James Brucker.

Install Client Software

For this lab, you will access MySQL server on the network. All you need is a client application. You don't need to run a MySQL server on your computer.

Client Tools

mysql-workbench-gpl-5.x.y-win32.msi

or use older GUI Tools:

mysql-gui-tools-5.1.7-win32.msi

From: se.cpe.ku.ac.th/download/mysql

Page 5: Database Access using SQL A basic introduction James Brucker.

Add MySQL "bin" to your Path

This is so you can run the "mysql" command line.

On Windows:

1. Right-click My Computer.

2. Choose Properties.

3. Click "Advanced".

4. Click "Environment Variables".

5. Edit PATH variable and add:

C:\Windows\blah;C:\Program Files\MySql\bin

Page 6: Database Access using SQL A basic introduction James Brucker.

Exercise

Use the "mysql" command if machine doesn't have "mysql" then use MySQL

Query Browser GUI. What is the client version number? Use help: how do you connect to a server?

dos> mysql --version

mysql Ver 14.12 Distrib 5.0.16, for Win32

dos> mysql --help

displays a long help message

Page 7: Database Access using SQL A basic introduction James Brucker.

Exercise

Connect to MySQL server on host "se.cpe.ku.ac.th".

user: student password: student

What MySQL version is the server?

dos> mysql -h se.cpe.ku.ac.th -u student -p

Enter password: nisit

mysql> SELECT version();

Page 8: Database Access using SQL A basic introduction James Brucker.

Structure of a Database

A database system may contain many databases. Each database is composed of schema and tables.

sql> USE bank;

sql> SHOW tables;+----------------+| Tables_in_bank |+----------------+| accounts || clients |+----------------+

sql> SHOW databases;+--------------+

| Database |

+--------------+

| mysql |

| test |

| bank |

| world |

+--------------+

MySQL only shows databases that a user has permission to access.

Page 9: Database Access using SQL A basic introduction James Brucker.

A Database Structure

Database

Schema

Tablefield1: t1field2: t2field3: t3

indexes

Schema

Tablefield1: t1field2: t2field3: t3

indexes

Tablefield1: t1field2: t2field3: t3

indexes

Tablefield1: t1field2: t2field3: t3

indexes

A database contains schema, which describe the organization of the database.

A schema can contain:

tables - containing data

index files - for fast lookup of data

stored procedures, constraints, triggers, and more

Page 10: Database Access using SQL A basic introduction James Brucker.

Contents of a Table

A table contains the actual data in records (rows). A record is composed of fields (columns). Each record contains one set of data values.

+------+------------+-------+-------------+---------+

| ID | Name | CCode | District | Populatn

+------+---------------+------------------+---------+| 3320 | Bangkok | THA | Bangkok | 6320174 || 3321 | Nonthaburi | THA | Nonthaburi | 292100 || 3323 | Chiang Mai | THA | Chiang Mai | 171100 |+------+------------+-------+-------------+---------+

records

(rows)

fields (columns)

Page 11: Database Access using SQL A basic introduction James Brucker.

Key field for Identifying Rows

A table contains a primary key that uniquely identifies a row of data.

Each record must have a distinct value of primary key The primary key is used to relate (join) tables.

+------+------------+-------+-------------+---------+

| ID | Name | CCode | District | Populatn

+------+---------------+------------------+---------+| 3320 | Bangkok | THA | Bangkok | 6320174 || 3321 | Nonthaburi | THA | Nonthaburi | 292100 || 3323 | Chiang Mai | THA | Chiang Mai | 171100 |+------+------------+-------+-------------+---------+

ID is the primary key in City table.

Page 12: Database Access using SQL A basic introduction James Brucker.

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 | |+-------------+-----------+-----+-----+---------+----------------+

Page 13: Database Access using SQL A basic introduction James Brucker.

Structure of a Table

"SHOW columns FROM tablename"

shows the same information.

sql> SHOW columns FROM 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 | |+-------------+-----------+-----+-----+---------+----------------+

Fields may have a default value to use if a value is not assigned explicitly.

Page 14: Database Access using SQL A basic introduction James Brucker.

Structured Query Language

Structured Query Language (SQL) is the standard language for accessing information a database.

SQL is case-insensitive and free format. Enter commands interactively or in a script file. SQL statements can use multiple lines

end each statement with a semi-colon ;

sql> USE world;

database changed.

sql> SHOW tables;

sql> SHOW columns FROM city;

sql> DECRIBE country;

SQL statements end with semi-colon.

Page 15: Database Access using SQL A basic introduction James Brucker.

Exercise

1. Connect to MySQL server on host "se.cpe.ku.ac.th".

user: student password: nisit

2. What databases are on the server?

3. What tables are in the world database?

dos> mysql -h se.cpe.ku.ac.th -u student -p

Enter password: nisit

mysql> SHOW databases;

mysql> USE world;

mysql> SHOW tables;

Page 16: Database Access using SQL A basic introduction James Brucker.

mysql> SHOW tables

FROM

world

;

Exercise

No semi-colon.

Omit the semi-colon. What happens? Enter a command on several lines

Page 17: Database Access using SQL A basic introduction James Brucker.

DESCRIBE

DESCRIBE shows the structure of a table. same as "SHOW columns FROM 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 | |+-------------+-----------+-----+-----+---------+----------------+

Page 18: Database Access using SQL A basic introduction James Brucker.

Exercise

For the world database:

what fields does the Country table have?

what information is in the fields?

which fields contain strings? (char or varchar)

which fields contain floating point values?

what is the primary key of the Country table?

Page 19: Database Access using SQL A basic introduction James Brucker.

Exercise: Case Sensitivity

Is SQL case sensitive?

Are names of databases and tables case sensitive?

mysql> DESCRIBE city;

mysql> describe city;

mysql> use world;

mysql> use WORLD;

mysql> describe city;

mysql> describe City;

Page 20: Database Access using SQL A basic introduction James Brucker.

Exercise: O-O Analogy of a Table?

Database Object Oriented

table __________________

record (row) __________________

fields (columns) __________________

+------+------------+--------------+---------+

| ID | Name | District | Popula..}

+------+------------+--------------+---------+| 3320 | Bangkok | Bangkok | 6320174 || 3321 | Nonthaburi | Nonthaburi | 292100 || 3323 | Chiang Mai | Chiang Mai | 171100 |+------+------------+--------------+---------+

fields (columns)

records

(rows)

Page 21: Database Access using SQL A basic introduction James Brucker.

Qualifying Names

SQL uses "." to qualify elements of a hierarchy

just like most O-O languages

World.city "city" table in World db

city.name name field in city table

World.city.name fully qualified name

sql> DESCRIBE World.country;...sql> SELECT country.name from country;

Page 22: Database Access using SQL A basic introduction James Brucker.

4 Basic Database Operations

The 4 most common operations:

SELECT query (search) the data

INSERT add new records to a table(s)

UPDATE modify existing record(s)

DELETE delete record(s) from a table

What is CRUD?

Programmers call these operations "CRUD".

What does CRUD stand for?

Page 23: Database Access using SQL A basic introduction James Brucker.

Querying Data in a Table

SELECT displays field values from a table:

SELECT field1, field2, field3 FROM table ;

displays ALL rows from the table.

use LIMIT number to limit how many results.

sql> SELECT accountNumber, balance FROM accounts;+---------------+---------------+----------+---------+

| accountNumber | accountName | clientID | balance |

+---------------+---------------+----------+---------+

| 11111113 | P.Watanapong | 00001001 | 300000 |

| 11111114 | CPE Fund | 00001002 | 1840000 |

+---------------+---------------+----------+---------+

Page 24: Database Access using SQL A basic introduction James Brucker.

SELECT statement with *

Display values for all fields in table:

SELECT * FROM tablename ;

sql> SELECT * from accounts;+---------------+---------------+----------+---------+

| accountNumber | accountName | clientID | balance |

+---------------+---------------+----------+---------+

| 11111113 | P.Watanapong | 00001001 | 300000 |

| 11111114 | CPE Fund | 00001002 | 1840000 |

+---------------+---------------+----------+---------+

Page 25: Database Access using SQL A basic introduction James Brucker.

Qualifying SELECT

Select columns from a table that match some criteria:

SELECT field1, field2, field3

FROM table

WHERE condition

ORDER BY field1,... [ASC|DESC];

Example: cities with population > 5 M

sql> SELECT * FROM City WHERE population > 5000000

ORDER BY population DESC;

Page 26: Database Access using SQL A basic introduction James Brucker.

Strings in SQL

Use single quote mark around String constants.

SELECT * FROM Country

WHERE name = 'Thailand';

SELECT * FROM City

WHERE Name = 'Los Angeles';

Page 27: Database Access using SQL A basic introduction James Brucker.

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?

Page 28: Database Access using SQL A basic introduction James Brucker.

Exercises for Thailand

1. What is the country code for Thailand?

SELECT * from ... WHERE name = 'Thailand'

2. List the cities in Thailand, sorted by largest population to smallest. Use "ORDER BY ..."

3. What languages are spoken in Thailand?

4. What countries speak Thai?

Page 29: Database Access using SQL A basic introduction James Brucker.

WHERE conditions

name = 'Bangkok' equality test

name LIKE 'Bang%' pattern match

population >= 100000

population < 500000

gnp <> 0

relations

<> is not equals

grade IN ('A','B','C','D','F')

contained in set

Page 30: Database Access using SQL A basic introduction James Brucker.

Exercise with WHERE & ORDER

1. What is the most populous country in Europe?

use WHERE continent = ...

2. What countries have name beginning with 'Z'?

3. In Thailand what cities have names like Ban______

Page 31: Database Access using SQL A basic introduction James Brucker.

Count Function

Select can be used with functions, such as COUNT:

SELECT COUNT(*) FROM accounts WHERE balance=0;

sql> SELECT COUNT(*) from accounts;+----------+

| count(*) |

+----------+

| 4 |

+----------+

sql> SELECT COUNT(*) from accounts

WHERE balance > 1000000;

Page 32: Database Access using SQL A basic introduction James Brucker.

Exercise

1. How many countries are in the database?

2. How many cities are in China?

3. How many countries are in Europe?

Page 33: Database Access using SQL A basic introduction James Brucker.

Other Functions in SQL

Functions can have arguments, just like C, Java, etc.

SUM( expression )

MAX( expression )

MIN( expression )

COUNT( expression )

sql> SELECT MAX(SurfaceArea) FROM country;1075400.00 (sq.km.)

WRONG: This will NOT find the largest country!

sql> SELECT MAX(SurfaceArea), Name FROM country;1075400.00 Afghanistan

Page 34: Database Access using SQL A basic introduction James Brucker.

SELECT functions

How many people are in the world?

SELECT SUM(Population) FROM Country;

How big is the largest country in Asia?

SELECT MAX(SurfaceArea)

FROM Country WHERE continent='Asia';

What is the version of MySQL?

SELECT version();

Page 35: Database Access using SQL A basic introduction James Brucker.

Exercise

1. What is the total GNP of the entire world?

sql> SELECT sum(GNP) FROM country

1. What are the richest countries (GNP per person) in the 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?

Page 36: Database Access using SQL A basic introduction James Brucker.

Exercise for Functions

Harder:

What are total population and total GNP of each continent?

Hint: use GROUP BY continent

Page 37: Database Access using SQL A basic introduction James Brucker.

Expressions and Arithmetic

You can use expressions in SQL.

Arithmetic: + - * / % sqrt()

Grouping: ( )

String ops: substring( ), upper(), length( )

Example: display GNP per person for each country

sql> SELECT name, gnp/population AS capita_gnp

FROM country

ORDER BY capita_gnp DESC;

Value of GNP is in millions of US Dollars. How can you show per capita GNP in dollars???

alias

Page 38: Database Access using SQL A basic introduction James Brucker.

Exercise

1. What countries are the richest? Poorest?

Show the GNP per capita (in US dollars).

Order the results by GNP per capita.

2. What countries are the most crowded?

Crowding refers to population per surface area.

Page 39: Database Access using SQL A basic introduction James Brucker.

Wildcards to match patterns

Pattern matches: field LIKE 'pattern'

SELECT * FROM city

WHERE name LIKE 'Ban%';

% means "match anything"

Page 40: Database Access using SQL A basic introduction James Brucker.

Adding New Records

INSERT adds a new record to a table

INSERT INTO table

VALUES ( data1, data2, ...);

sql> INSERT INTO Accounts VALUES

('22222222', 'Ample Rich', '00000001' 10000000);Query OK, 1 row affected.

+---------------+---------------+----------+---------+

| accountNumber | accountName | clientID | balance |

+---------------+---------------+----------+---------+

| 22222222 | Ample Rich | 00000001 |10000000 |

+---------------+---------------+----------+---------+

Page 41: Database Access using SQL A basic introduction James Brucker.

INSERT into columns by name

INSERT INTO table (field1, field2, ...)

VALUES ( data1, data2, ...);

sql> INSERT INTO Accounts

(accountNumber, balance, accountName)

VALUES

('22222222', 10000000, 'Ample Rich'); Query OK, 1 row affected.

+---------------+---------------+----------+---------+

| accountNumber | accountName | clientID | balance |

+---------------+---------------+----------+---------+

| 20000000 | Ample Rich | |10000000 |

+---------------+---------------+----------+---------+

Page 42: Database Access using SQL A basic introduction James Brucker.

Exercise

Add your home town to the City table

or, add another city to the City table.

sql> INSERT INTO city

(name, countryCode, district, population)

VALUES

('Bangsaen', 'THA', 'Chonburi', 30000); Query OK, 1 row affected.

The ID field has a qualifier "AUTO_INCREMENT".

(see: "DESCRIBE City")

This means MySQL will assign the ID value itself.

Page 43: Database Access using SQL A basic introduction James Brucker.

Exercise

View the City data that you just added!

Correct any errors using UPDATE

sql> SELECT * FROM City

WHERE City.name = 'Bangsaen';

sql> UPDATE City SET population = 33000

WHERE City.name = 'Bangsaen';

Query OK, 1 row affected.

Page 44: Database Access using SQL A basic introduction James Brucker.

Warning: INSERT is immediate

Change occurs immediately.

unless you are using transactions

Duplicate data is possible.

Page 45: Database Access using SQL A basic introduction James Brucker.

3 ways to add data to a table

1. INSERT command (boring).

2. Write INSERT commands in a text file and "source" the file (better).

sql> SOURCE mydata.sql

3. IMPORT command (syntax depends on DBMS):

sql> LOAD DATA INFILE 'filename' INTO table ...

Page 46: Database Access using SQL A basic introduction James Brucker.

Copying Data Between Tables

Suppose we have another table named NewAccts

NewAccts has accountNumber, accountName, ...

INSERT INTO table (field1, field2, ...)

SELECT field1, field2, field3

FROM other_table

WHERE condition;

sql> INSERT INTO Accounts

SELECT * FROM NewAccounts

WHERE accountNumber NOT NULL;

Page 47: Database Access using SQL A basic introduction James Brucker.

UPDATE statement

Change values in one or more records:

UPDATE table

SET field1=value1, field2=value2WHERE condition;

sql> UPDATE city SET population=40000 WHERE name='Bangsaen' AND countrycode='THA';

Query OK, 1 row affected (0.09 sec)

| name | countrycode | district | population |+----------+-------------+----------+------------------+| 11111111 | THA | Chonburi | 40000 |

Page 48: Database Access using SQL A basic introduction James Brucker.

UPDATE multiple columns

You can change multiple columns:

UPDATE table

SET field1=value1, field2=value2WHERE condition;

sql> UPDATE country SET population=68100000, gnp=345600 WHERE code='THA';

Query OK, 1 row affected (0.09 sec)

Example: Update population and GNP of Thailand

Source: CIA World Factbook (on the web)

Page 49: Database Access using SQL A basic introduction James Brucker.

Warning: don't forget WHERE

UPDATE can change every row in a database

Make sure that your WHERE clause selects only records you want to change!

sql> UPDATE country

SET population=68100000, gnp=345600 ;

Query OK, 240 rows affected (0.14 sec)

Changed every country in the database!!

Oops! I forgot "WHERE ..."

Page 50: Database Access using SQL A basic introduction James Brucker.

Warning: UPDATE is immediate!

Changes occur immediately. (Can't undo w/o trans.)

Be Careful! If you forget the WHERE clause it will change all the rows in the table!

sql> UPDATE country SET HeadOfState='Obama';

/* Oops! I forgot "WHERE ..." */+------+----------------+-------------+--------------+| Code | Name | Continent | HeadOfState |+------+----------------+-------------+--------------+| AFG | Afghanistan | Asia | Obama || NLD | Netherlands | Europe | Obama || ALB | Albania | Europe | Obama || DZA | Algeria | Africa | Obama || ASM | American Samoa | Oceania | Obama || AND | Andorra | Europe | Obama || AGO | Angola | Africa | Obama |

Obama rules!

Page 51: Database Access using SQL A basic introduction James Brucker.

Exercise

Update the City you added to the database. Change its population.

Page 52: Database Access using SQL A basic introduction James Brucker.

Deleting Records

DELETE one or more records

DELETE FROM tablename WHERE condition;

Example: Delete all cities with zero population

sql> DELETE FROM City WHERE population <= 0;

Query OK, 5 rows deleted.

Page 53: Database Access using SQL A basic introduction James Brucker.

Warning: DELETE can delete all

DELETE affects all rows that match.

DELETE FROM tablename WHERE condition;

Example: Delete all cities with zero population

sql> DELETE FROM City

WHERE population <= 0; Query OK, 5 rows deleted.

Page 54: Database Access using SQL A basic introduction James Brucker.

Safer Delete

First SELECT the key of the row you want

sql> SELECT id FROM City WHERE name='Bangsaen';

6402

If only one match, then delete using primary key

sql> DELETE FROM City WHERE id=6402;

Page 55: Database Access using SQL A basic introduction James Brucker.

Relating Tables

The power of a relational database is the ability to selectively combine data from many tables.

select data from multiple tables by matching values

Relationship can be:

1-to-1 student -> photograph

1-to-many country -> city

many-to-1 city -> country

many-to-many language -> country

Page 56: Database Access using SQL A basic introduction James Brucker.

Keys

Every table should have a primary key that uniquely identifies each row.

CityID (PK)NameCountryCode (FK)PopulationDistrict

CountryCode (PK)NameContinentCapital...

CountryCode

sql> DESCRIBE Country;+-------------+-----------+-----+-----+---------+----------------+| Field | Type | Null| Key | Default | Extra |+-------------+-----------+-----+-----+---------+----------------+| Code | char(3) | NO | PRI | | || Name | char(52) | NO | | | || ... | | | | | |

Page 57: Database Access using SQL A basic introduction James Brucker.

Joining Tables

Relate or "join" tables using a condition.

Use "table.field" to qualify a field name:

Country.code Country.name

City.countrycode = Country.code

1*

CityID (PK)NameCountryCode (FK)PopulationDistrict

CountryCode (PK)NameContinentCapital...

Page 58: Database Access using SQL A basic introduction James Brucker.

Example: Join Country and City

SELECT Country.Name, City.Name FROM Country, CityWHERE Country.Code = City.CountryCodeAND Continent = 'South America';

CountryCodeNameContinentRegionSurfaceAreaPopulationGNPLocalNameCapital

CityIDNameCountryCodeDistrictPopulation

Country.Code = City.CountryCode

Page 59: Database Access using SQL A basic introduction James Brucker.

Use Aliases to Reduce Typing

c is alias for Cityco is alias for Country

SELECT co.Name, c.Name FROM Country co, City cWHERE co.Code = c.CountryCodeAND co.Continent = 'South America';

Page 60: Database Access using SQL A basic introduction James Brucker.

Exercise: Cities in Laos

SELECT co.Name, c.Name, c.Population FROM Country co, City cWHERE ...AND ...;

List the city names and city populations in Laos.

Page 61: Database Access using SQL A basic introduction James Brucker.

Exercise

1. How can we find the name of the capital city for each country?

CountryCode (PK)NameContinentRegionSurfaceAreaPopulationGNPLocalNameCapital

CityID (PK)NameCountryCodeDistrictPopulation

Page 62: Database Access using SQL A basic introduction James Brucker.

Exercise Solution

List the country name and capital city name, for all countries in Asia.

SELECT co.name, c.name AS CapitalCity FROM Country co, City c

WHERE ...

AND ... ;

Page 63: Database Access using SQL A basic introduction James Brucker.

Exercise

1. How can we join the CountryLanguage table with the County table?

CountryCode (PK)NameContinentRegionSurfaceAreaPopulationGNPLocalNameCapital

CountryLanguageCountryCodeLanguageisOfficialPercentage

FROM Country CO, CountryLanguage L

WHERE ...

Page 64: Database Access using SQL A basic introduction James Brucker.

Exercise

1. In what countries is the Thai language spoken?

2. By what percentage of the people?

Example:

SELECT CO.name, L.language, L.percentage

FROM Country CO, CountryLanguage L

WHERE ...

AND ... ;

Page 65: Database Access using SQL A basic introduction James Brucker.

Answer using Aliases

In what countries is Chinese the official language?

SELECT C.name, L.language, L.percentage

FROM Country C, CountryLanguage L

WHERE C.code = L.countrycode

AND L.language LIKE '%Chinese'

AND isOfficial = 'T';

alias for CountryLanguageyou can omit table name

when there is no ambiguity

Page 66: Database Access using SQL A basic introduction James Brucker.

Exercise

1. What countries use English?

ORDER the results by percentage spoken, from largest to smallest %.

2. In how many countries is English the official language?

Harder

3. In the world, approximately how many people speak English?

sum( C.population * L.percentage / 100 )

Page 67: Database Access using SQL A basic introduction James Brucker.

JOIN

Joins tables

Many forms:

INNER JOIN (include only matching columns)

OUTER JOIN (include all columns)

LEFT OUTER JOIN

NATURAL JOIN

CONDITION JOIN

"JOIN" means "INNER JOIN" in MySql.

Page 68: Database Access using SQL A basic introduction James Brucker.

Example of a Condition Join

JOIN the CountryLanguage and Language tables using the country code:

SELECT CO.Name, L.language, L.percentage

FROM Country CO

JOIN CountryLanguage L

ON CO.code = L.countrycode

WHERE ...;

Page 69: Database Access using SQL A basic introduction James Brucker.

Exercise

JOIN the Country and Language tables.

View Country name and language with "SELECT ..."

How many times is Thailand listed in the results?

How can you order the results by language ?

Page 70: Database Access using SQL A basic introduction James Brucker.

Multiple Table Join

You can join many tables at one time:

SELECT CO.name, C.*, L.language

FROM Country CO

JOIN CountryLanguage L

ON CO.code = L.countrycode

JOIN City C

ON CO.code = C.countrycode

WHERE ...; /* more conditions */

Page 71: Database Access using SQL A basic introduction James Brucker.

More SELECT Syntax

Page 72: Database Access using SQL A basic introduction James Brucker.

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

Page 73: Database Access using SQL A basic introduction James Brucker.

GROUP BY Exercise

What is the total population of each continent? use sum(population) and GROUP BY

SELECT continent, SUM(population)

FROM ...

GROUP BY ...

Page 74: Database Access using SQL A basic introduction James Brucker.

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;

Page 75: Database Access using SQL A basic introduction James Brucker.

Set operations

IN

SELECT * FROM City WHERE District IN ('Songkhla', 'Bangkok');

Page 76: Database Access using SQL A basic introduction James Brucker.

Exercise for matching

1. How many countries have a government that is any form of monarchy?

match any government containing 'Monarchy'

How many are some form of monarchy, but not a Constitutional Monarchy (like Thailand)?

Page 77: Database Access using SQL A basic introduction James Brucker.

GROUP BY ... HAVING ...

GROUP BY ... used to apply a function to a group of rows having a characteristic.

HAVING ... is used to put a condition on the groups.

Example: What countries have more than one official lanaguage???

SELECT countrycode, count(language)

FROM countrylanguage

???

Page 78: Database Access using SQL A basic introduction James Brucker.

GROUP BY ... HAVING ...

(1) First, how to count official languages in each country?

SELECT countrycode, count(language)

FROM countrylanguage

WHERE isOfficial='T'

GROUP BY countrycode

Page 79: Database Access using SQL A basic introduction James Brucker.

GROUP BY ... HAVING ...

(2) add HAVING to restrict results to count( ) > 1

SELECT countrycode, count(language)

FROM countrylanguage

WHERE isOfficial='T'

GROUP BY countrycode

HAVING count(language) > 1

Page 80: Database Access using SQL A basic introduction James Brucker.

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.

Page 81: Database Access using SQL A basic introduction James Brucker.

Subqueries

Use the result of one query as part of another query.

Example: Which country has the largest population?

SELECT Name, PopulationFROM countryWHERE Population = ( SELECT max(population) FROM country);

To use subqueries in MySQL you need version 4.1 or newer.

Subquery

Page 82: Database Access using SQL A basic introduction James Brucker.

Exercise

In which country do people live the longest? How long to they live?

SELECT Name, LifeExpectancy

FROM country

WHERE LifeExpectancy =( insert subquery here )

;

Page 83: Database Access using SQL A basic introduction James Brucker.

LIMIT instead of subquery

Another way to get a "most" or "least" result:

ORDER results by what you want. Use ASC or DESC

use LIMIT 1 to limit number of results.

SELECT Name, Population

FROM country

ORDER BY Population DESC

LIMIT 1;

Page 84: Database Access using SQL A basic introduction James Brucker.

Exercise

Which nation is the most crowded?

Find the country with maximum population density (population per sq. km.)

Show the name and the population density

Hint: create an alias for a computed field:

sql> SELECT name,population/surfaceArea AS densityWHERE ...

Alias: density := population/surfaceArea

Page 85: Database Access using SQL A basic introduction James Brucker.

Exercise

Is Thailand richer than other countries in Southest Asia?

List the name and GNP/population (=wealth) of countries in the same region as Thailand.

use a subquery for "the region of Thailand":

SELECT ...

FROM Country

WHERE region = (SELECT region WHERE ...)

ORDER BY ...;

order the results by wealth

Page 86: Database Access using SQL A basic introduction James Brucker.

Exercise: increasing wealth

Thailand has decided to annex (invade) either Cambodia, Laus, Vietnam, or Malaysia.

The invaded country will become part of the new Thailand.

The government wants the combined country to be wealthier than Thailand is now. "wealth" means GNP/population.

What country should Thailand invade?

Page 87: Database Access using SQL A basic introduction James Brucker.

Data Definition Commands

These commands alter the structure of a database

CREATE create a Table, Index, or Database

ALTER modify structure of a Database or Table

DROP delete an entire Table, Index, or Database

RENAME rename a Table

Page 88: Database Access using SQL A basic introduction James Brucker.

Creating a Table

To add a new table to a database:

CREATE TABLE tablename

(field1, field2, ... )

options ;

sql> CREATE TABLE CUSTOMER (

accountNumber VARCHAR(8) NOT NULL,

clientID VARCHAR(40) NOT NULL,

balance DOUBLE DEFAULT '0',

availableBalance DOUBLE DEFAULT '0'

) ;

Query OK, 0 rows affected.

Page 89: Database Access using SQL A basic introduction James Brucker.

Productivity Hint

Type the "CREATE TABLE" statement into a file. "source" the file in mysql: source filename;

CREATE TABLE CUSTOMER (accountNumber CHAR(10) NOT NULL,clientID VARCHAR(40) NOT NULL,balance DOUBLE DEFAULT '0',availableBalance DOUBLE DEFAULT '0',PRIMARY KEY( clientID )

) ;

File: /temp/create-table.sql

sql> SOURCE /temp/create-table.sql;

Query OK, 0 rows affected.

Page 90: Database Access using SQL A basic introduction James Brucker.

Deleting Records a Table

You must specify a "WHERE" clause for rows to delete.

If there is no "WHERE", it deletes all rows !!

DELETE FROM tablename

WHERE condition ;

-- first use SELECT to verify condition

sql> SELECT * FROM city

WHERE name="Bangsaen";

sql> DELETE FROM city

WHERE name="Bangsaen";

Query OK, 1 row affected.

Page 91: Database Access using SQL A basic introduction James Brucker.

Exercise

Delete the city you added to the City table.

On a friend's machine, is it deleted immediately?

Page 92: Database Access using SQL A basic introduction James Brucker.

Deleting a Table

Remove a table from the database

DROP TABLE tablename ;

sql> DROP TABLE CUSTOMER ;

Page 93: Database Access using SQL A basic introduction James Brucker.

Views

A View is like a "virtual table" containing selected data from one or more real tables.

CountryNameContinentCode...

CountryLanguage

LanguagePercentageisOfficial...

MyViewNameLanguagePercentage

CREATE VIEW MyView AS ...

Page 94: Database Access using SQL A basic introduction James Brucker.

View Example

Create a view for country name, languages, and percentage.

sql> CREATE VIEW lang AS

SELECT name, language, percentageFROM Country C, CountryLanguage LWHERE C.code = L.countrycodeORDER BY language ASC;

Query OK, 0 rows affected.

sql> SELECT * FROM lang WHERE language='Thai';

Use the view to browse data:

Page 95: Database Access using SQL A basic introduction James Brucker.

Productivity Hint

Type the "CREATE VIEW" statement into a file. Read the file into mysql: source filename;

CREATE VIEW lang AS

SELECT name, language, percentage

FROM Country C, CountryLanguage L

WHERE C.code = L.countrycode;

File: langview.sql

sql> SOURCE langview.sql;

Query OK, 0 rows affected.

Page 96: Database Access using SQL A basic introduction James Brucker.

Exercise

Create a view that shows these fields:

City.name as name

Country.name as country

Region

Population of the city

Official language

id of the city

Each person should use a different name for his view, to avoid interfering with each other.

List the tables in world ( show tables ).

Page 97: Database Access using SQL A basic introduction James Brucker.

Exercise

List the cities in Southest Asia where English is the official language and population is over 100,000.

Page 98: Database Access using SQL A basic introduction James Brucker.

Exercise

Ask MySQL to "describe" your view.

Delete your view:

DROP VIEW viewname ;

Page 99: Database Access using SQL A basic introduction James Brucker.

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?

Page 100: Database Access using SQL A basic introduction James Brucker.

SQL Quiz

Database Game

Page 101: Database Access using SQL A basic introduction James Brucker.

Vocabulary

"largest" and "smallest" refer to size (surfaceArea).

"most populous", "least populous" refer to populationand population > 0. (exclude unpopulated nations)

"richest", "poorest" means GNP per capita not total GNP, and GNP > 0 (GNP = 0 means no data).

"most crowded" refers to population/surfaceArea

Page 102: Database Access using SQL A basic introduction James Brucker.

Language Hints

"Fortran is an official language" means its an official language of the country

"Pascal is spoken unofficially" means it is spoken, but not an official language

"COBOL is spoken" means COBOL is a language and percentage > 0

Page 103: Database Access using SQL A basic introduction James Brucker.

What is the World's Smallest Nation?

How big is it?

Page 104: Database Access using SQL A basic introduction James Brucker.

What is the Largest Country in Africa?

Show the SQL How big is it?

Page 105: Database Access using SQL A basic introduction James Brucker.

What are the Poorest Countries in Asia?

must have GNP data (GNP > 0)

List 3 poorest nations.

What is the GNP per person?

NOTE: GNP is measured in $1,000,000. Multiply your answer by 1,000,000 to get US$.

Page 106: Database Access using SQL A basic introduction James Brucker.

What is the Richest Country in the Middle East (region)?

What is the GNP per person? Show result is US$ (not million). Round the income to nearest dollar!

WRONG: 12345.6789

NOTE: GNP is database is measured in $1,000,000. Multiply your answer by 1,000,000 to get US$.

Page 107: Database Access using SQL A basic introduction James Brucker.

In what countries is Thai spoken?

SELECT ...

FROM Country C

JOIN CountryLanguage L

ON C.code = L.countrycode

WHERE ...

Page 108: Database Access using SQL A basic introduction James Brucker.

How many people speak English?

2 queries: how many in each country total for world

SELECT ...

FROM Country C

JOIN CountryLanguage L

ON C.code = L.countrycode

WHERE ...

Page 109: Database Access using SQL A basic introduction James Brucker.

History of Empires through Language

Empires are cultures that spread over many countries.

We can detect past Empires by the spread of language.

What languages are spoken in greatest number of countries?

Can you name the Empire?

Page 110: Database Access using SQL A basic introduction James Brucker.

History of Empires through Language

We can detect past Empires by the spread of language.

What languages are spoken in greatest number of countries?

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

Page 111: Database Access using SQL A basic introduction James Brucker.

What cities have a population > 6M ?

Print city name, population, and country name Sort by population -- largest first

+-----------------+------------+-------------------------+

| name | population | country_name |

+-----------------+------------+-------------------------+

...

| Bangkok | 6320174 | Thailand |

...

Page 112: Database Access using SQL A basic introduction James Brucker.

Where is Dari the Official Language?

In what country is Dari the official language?

Page 113: Database Access using SQL A basic introduction James Brucker.

4 official languages?

What country in Europe has 4 official languages?

SELECT ...

FROM Country C

JOIN CountryLanguage L

ON C.code = L.countrycode

WHERE ...

GROUP BY C.code -- group by country

HAVING ...

Page 114: Database Access using SQL A basic introduction James Brucker.

Resources

MySQL

http://dev.mysql.com/tech-resources/articles/

Learning SQL

http://www.w3schools.com/sql/ nice tutorial and command reference