Comp1121 Lec 05
Comp1121 Lec 05
Databases
1
Our journey so far ...
Database
Environment Relational Relational
Introduction & Algebra
Model
Architecture
SQL
Entity
Normalisation Relationship
Modelling
Database
Designs
Ethics of
Security & Transaction Using
Administration Management Databases
2
Relational Data Model
• Components of a data model
– A structural part – set of rules
• Relations SQL CREATE TABLE
– A manipulative part – operations allowed on data
• Relational Algebra SQL SELECT
– A set of integrity constraints SQL CREATE TABLE
(PRIMARY KEY, FOREIGN KEY, CHECK, …)
3
Learning objectives
• To write SQL queries to create, alter, and
delete tables in database.
• To write SQL queries to manipulate data in
database.
4
Structured Query Language (SQL)
• “ess-que-ell” or “sequel”? – a matter of
preference.
• Two parts: DDL and DML
• Consists of standard English words such as
CREATE TABLE, INSERT INTO, SELECT .. FROM
..WHERE.
• Most components of an SQL statement are
case insensitive, except for literal character
data.
5
DDL
• Main SQL DDL statements are:
6
CREATE TABLE
7
SQL Data Types
8
ALTER/DROP TABLE
• ALTER TABLE Staff ALTER position DROP DEFAULT;
• ALTER TABLE Client
ADD prefNoRooms SMALLINT;
• DROP TABLE PropertyForRent;
9
DML
• INSERT INTO TableName [ (columnList) ]
VALUES (dataValueList)
• UPDATE TableName
SET columnName1 = dataValue1
[, columnName2 = dataValue2...]
[WHERE searchCondition]
10
DML: SELECT statement
11
SELECT statements
• Specific columns, specific rows (eg SELECT
staffNo, fName,lName, salary FROM Staff;)
13
SELECT statements
• ORDER BY(eg SELECT staffNo, fName, lName,
salary FROM Staff ORDER BY salary DESC)
14
SELECT statements
• GROUP BY to get sub-totals
– All column names in SELECT list must
appear in GROUP BY clause unless name is
used only in an aggregate function
– SELECT branchNo, COUNT(staffNo) as
myCount FROM Staff GROUP BY branchNo;
– SELECT branchNo, COUNT(staffNo) AS
myCount, SUM(salary) AS mySum FROM Staff
GROUP BY branchNo ORDER BY branchNo;
15
SELECT statements
• HAVING to use with GROUP BY
– SELECT branchNo, COUNT(staffNo) AS
myCount, SUM(salary) AS mySum FROM Staff
GROUP BY branchNo HAVING COUNT(staffNo)
> 1 ORDER BY branchNo;
16
Summary
• SQL queries to create, alter, and delete
tables in database.
• SQL queries to manipulate data in
database.
17
Follow-up work
• Complete required reading:
– Connolly & Begg: Chapter 6:6.1-6.3.4, Chapter
7:7.1-7.3
18