Introduction to SQL

Derek Bridge

Department of Computer Science,
University College Cork

Introduction to SQL

Aims:

Relational databases

An example database

Sudbury Bird Sanctuary operates a Fund-A-Fowl scheme whereby members of the public can help pay for the birds' upkeep.

birds
numnamespecies
1Stevieswan
2Mandymoorhen
3Derekduck
4Dervladuck
sponsors
numnameaddress
1Hugh JeegohDublin
2Donna KebabCork
3Ann O DominiDublin
donations
snumbnumdonation
11256
14123
34562

Data definition: databases

Data definition: creating and deleting tables

Data definition: example

CREATE TABLE birds (
 num int AUTO_INCREMENT,
 name varchar(30),
 species varchar(25),
 PRIMARY KEY (num)
);

CREATE TABLE donations (
 snum int,
 bnum int,
 donation int,
 PRIMARY KEY(snum, bnum)
);

Data manipulation: insertion and deletion

Data manipulation: example

INSERT INTO birds (name, species)
 VALUES ('Stevie', 'swan');

INSERT INTO birds (name, species)
 VALUES ('Mandy', 'moorhen');

INSERT INTO donations (snum, bnum, donation)
 VALUES (100, 1, 256);

Data manipulation: retrieval

Data manipulation: exercises

Paraphrase into English the following SQL queries:

SELECT * FROM sponsors 
 WHERE address = 'Dublin';

SELECT snum FROM donations 
 WHERE donation < 300;

SELECT bnum FOM donations
 WHERE donation < 300;

Data manipulation: exercises

Write SQL queries to retrieve the following:

  1. the identification numbers of all the ducks
  2. the names of all the ducks
  3. the identification numbers of all birds where the sponsor is number 100 and the sponsorship amount exceeds 200
  4. the names of all ducks and swans (Warning! English can mislead!)

Data manipulation: retrieval

Data manipulation: exercises

Paraphrase into English the following SQL queries:

SELECT name FROM sponsors, donations 
 WHERE sponsors.num = donations.snum;

SELECT DISTINCT name FROM sponsors, donations 
 WHERE sponsors.num = donations.snum 
   AND bnum = 5;

SELECT sponsors.name, birds.name FROM sponsors, donations, birds
 WHERE sponsors.num = donations.snum  
   AND donations.bnum = birds.num;

Data manipulation: exercises

Write SQL queries to retrieve the following: