DBMS
Database Management System (DBMS)
Database Language (SQL)
SQL
Main SQL DML statements are:
SELECT
INSERT
UPDATE
DELETE
Main SQL DDL statements are:
CREATE SCHEMA DROP SCHEMA
CREATE/ALTER DOMAIN DROP DOMAIN
CREATE/ALTER TABLE DROP TABLE
CREATE VIEW DROP VIEW
CREATE INDEX DROP INDEX
DCL
GRANT, REVOKE etc.
INSERT
INSERT INTO TableName [(columnList)]
VALUES (dataValueList)
columnList is optional; if omitted, SQL assumes a list of
all columns in their original CREATE TABLE order.
Any columns omitted must have been declared as NULL
when table was created, unless DEFAULT was specified
when creating column.
3
INSERT
dataValueList must match columnList as
follows:
number of items in each list must be same;
must be direct correspondence in position of items in
two lists;
data type of each item in dataValueList must be
compatible with data type of corresponding column.
4
Example 5.35 INSERT … VALUES
Insert a new row into Staff table supplying
data for all columns.
INSERT INTO Staff
VALUES (‘SG16’, ‘Alan’, ‘Brown’, ‘Assistant’, ‘M’,
Date‘1957-05-25’, 8300, ‘B003’);
5
Example 5.36 INSERT using Defaults
Insert a new row into Staff table supplying data
for all mandatory columns.
INSERT INTO Staff (staffNo, fName, lName,
position, salary, branchNo)
VALUES (‘SG44’, ‘Anne’, ‘Jones’,
‘Assistant’, 8100, ‘B003’);
Or
INSERT INTO Staff
VALUES (‘SG44’, ‘Anne’, ‘Jones’, ‘Assistant’, NULL,
NULL, 8100, ‘B003’);
7
INSERT … SELECT
Second form of INSERT allows multiple rows
to be copied from one or more tables to
another:
INSERT INTO TableName [ (columnList) ]
SELECT ...
9
Example 5.37 INSERT … SELECT
Assume there is a table StaffPropCount that
contains names of staff and number of properties
they manage:
StaffPropCount(staffNo, fName, lName, propCnt)
Populate StaffPropCount using Staff and
PropertyForRent tables.
10
Example 5.37 INSERT … SELECT
INSERT INTO StaffPropCount
(SELECT s.staffNo, fName, lName, COUNT(*)
FROM Staff s, PropertyForRent p
WHERE s.staffNo = p.staffNo
GROUP BY s.staffNo)
UNION
(SELECT staffNo, fName, lName, 0
FROM Staff
WHERE staffNo NOT IN
(SELECT DISTINCT staffNo
FROM PropertyForRent));
11
Example 5.37 INSERT … SELECT
If second part of UNION is omitted, excludes those staff
who currently do not manage any properties.
14
UPDATE
UPDATE TableName
SET columnName1 = dataValue1
[, columnName2 = dataValue2...]
[WHERE searchCondition]
TableName can be name of a base table or an
updatable view.
SET clause specifies names of one or more
columns that are to be updated.
15
UPDATE
WHERE clause is optional:
if omitted, named columns are updated for all rows in
table;
if specified, only those rows that satisfy
searchCondition are updated.
New dataValue(s) must be compatible with data
type for corresponding column.
16
Example 5.38/39 UPDATE All Rows
Give all staff a 3% pay increase.
UPDATE Staff
SET salary = salary*1.03;
Give all Managers a 5% pay increase.
UPDATE Staff
SET salary = salary*1.05
WHERE position = ‘Manager’;
17
Example 5.40 UPDATE Multiple Columns
Promote David Ford (staffNo=‘SG14’) to
Manager and change his salary to
£18,000.
UPDATE Staff
SET position = ‘Manager’, salary = 18000
WHERE staffNo = ‘SG14’;
18
DELETE
DELETE FROM TableName
[WHERE searchCondition]
TableName can be name of a base table or an
updatable view.
searchCondition is optional; if omitted, all rows are
deleted from the table. This does not delete table. If
search_condition is specified, only those rows that
satisfy the condition are deleted.
19
Example 5.41/42 DELETE Specific Rows
Delete all viewings that relate to property PG4.
DELETE FROM Viewing
WHERE propertyNo = ‘PG4’;
Delete all records from the Viewing table.
DELETE FROM Viewing;
20
SQL: Data Definition
Transparencies
Objectives
Data types supported by SQL standard.
Purpose of integrity enhancement feature of SQL.
How to define integrity constraints using SQL.
How to use the integrity enhancement feature in
the CREATE and ALTER TABLE statements.
22
Objectives
Purpose of views.
How to create and delete views using SQL.
How the DBMS performs operations on views.
Under what conditions views are updatable.
Advantages and disadvantages of views.
How the ISO transaction model works.
How to use the GRANT and REVOKE statements as
a level of security.
23
ISO SQL Data Types
24
Data Definition
SQL DDL allows database objects such as schemas, domains,
tables, views, and indexes to be created and destroyed.
Main SQL DDL statements are:
CREATE SCHEMA DROP SCHEMA
CREATE/ALTER DOMAIN DROP DOMAIN
CREATE/ALTER TABLE DROP TABLE
CREATE VIEW DROP VIEW
Many DBMSs also provide:
CREATE INDEX DROP INDEX
25
Data Definition
Relations and other database objects exist in an
environment.
Each environment contains one or more catalogs, and
each catalog consists of set of schemas.
Schema is named collection of related database
objects.
Objects in a schema can be tables, views, domains,
assertions, collations, translations, and character sets.
All have same owner.
ENVIRONMENT->CATALOG->SCHEMA->(tables, views
…)
26
Өгөгдлийн сангийн үндэс
Өгөгдлийн сан үүсгэх
CREATE DATABASE database_name
DROP DATABASE database_name
SCHEMA = a named collection of database objects that
are in some way related to one another. (tables, views,
domains, assertions, etc)
Өгөгдлийн сангийн үндэс
Хүснэгт үүсгэх
CREATE TABLE
Creates a table with one or more columns of the
specified dataType.
With NOT NULL, system rejects any attempt to insert a
null in the column.
Can specify a DEFAULT value for the column.
Primary keys should always be specified as NOT NULL.
FOREIGN KEY clause specifies FK along with the
referential action
31
Example 6.1 - CREATE TABLE
CREATE DOMAIN OwnerNumber AS VARCHAR(5)
CHECK (VALUE IN (SELECT ownerNo FROM PrivateOwner));
CREATE DOMAIN StaffNumber AS VARCHAR(5)
CHECK (VALUE IN (SELECT staffNo FROM Staff));
CREATE DOMAIN PNumber AS VARCHAR(5);
CREATE DOMAIN PRooms AS SMALLINT;
CHECK(VALUE BETWEEN 1 AND 15);
CREATE DOMAIN PRent AS DECIMAL(6,2)
CHECK(VALUE BETWEEN 0 AND 9999.99);
32
Example 6.1 - CREATE TABLE
33
Өгөгдлийн сангийн үндэс
CREATE DATABASE databasename;
ХҮСНЭГТ ҮҮСГЭХ
CREATE TABLE table_name (
column1 datatype,
column2 datatype,
column3 datatype,
.... )
Create Table Using Another Table
CREATE TABLE new_table_name AS
SELECT column1, column2,...
FROM existing_table_name
WHERE ....;
Өгөгдлийн сангийн үндэс
Өгөгдлийн сангийн үндэс
Өгөгдлийн сангийн үндэс
Өгөгдлийн сангийн үндэс
ALTER TABLE
Add a new column to a table.
Drop a column from a table.
Add a new table constraint.
Drop a table constraint.
Set a default for a column.
Drop a default for a column.
39
Example 6.2(a) - ALTER TABLE
Change Staff table by removing default of
‘Assistant’ for position column and setting
default for sex column to female (‘F’).
ALTER TABLE Staff
ALTER position DROP DEFAULT;
ALTER TABLE Staff
ALTER sex SET DEFAULT ‘F’;
40
Example 6.2(a) - ALTER TABLE
41
Example 6.2(b) - ALTER TABLE
Remove constraint from PropertyForRent that staff
not allowed to handle more than 100 properties at
time. Add new column to Client table.
ALTER TABLE PropertyForRent
DROP CONSTRAINT StaffNotHandlingTooMuch;
ALTER TABLE Client
ADD prefNoRooms PRooms;
42
DROP TABLE
DROP TABLE TableName [RESTRICT | CASCADE]
e.g. DROP TABLE PropertyForRent;
Removes named table and all rows within it.
With RESTRICT, if any other objects depend for their
existence on continued existence of this table, SQL does
not allow request.
With CASCADE, SQL drops all dependent objects (and
objects dependent on these objects).
43
Integrity Enhancement Feature
Consider five types of integrity constraints:
Required data.
Domain constraints.
Entity integrity.
Referential integrity.
Enterprise constraints.
44
Integrity Enhancement Feature
Required Data
position VARCHAR(10) NOT NULL
Domain Constraints
(a) CHECK
sex CHAR NOT NULL
CHECK (sex IN (‘M’, ‘F’))
45
Integrity Enhancement Feature
(b) CREATE DOMAIN
CREATE DOMAIN DomainName [AS] dataType
[DEFAULT defaultOption]
[CHECK (searchCondition)]
For example:
CREATE DOMAIN SexType AS CHAR
CHECK (VALUE IN (‘M’, ‘F’));
sex SexType NOT NULL
46
Integrity Enhancement Feature
searchCondition can involve a table lookup:
CREATE DOMAIN BranchNo AS CHAR(4)
CHECK (VALUE IN (SELECT branchNo
FROM Branch));
Domains can be removed using DROP DOMAIN:
DROP DOMAIN DomainName
[RESTRICT | CASCADE]
47
IEF - Entity Integrity
Primary key of a table must contain a unique, non-null
value for each row.
ISO standard supports FOREIGN KEY clause in CREATE and
ALTER TABLE statements:
PRIMARY KEY(staffNo)
PRIMARY KEY(clientNo, propertyNo)
Can only have one PRIMARY KEY clause per table. Can still
ensure uniqueness for alternate keys using UNIQUE:
UNIQUE(telNo)
48
IEF - Referential Integrity
FK is column or set of columns that links each row in child
table containing foreign FK to row of parent table
containing matching PK.
Referential integrity means that, if FK contains a value,
that value must refer to existing row in parent table.
ISO standard supports definition of FKs with FOREIGN KEY
clause in CREATE and ALTER TABLE:
FOREIGN KEY(branchNo) REFERENCES Branch
49
IEF - Referential Integrity
Any INSERT/UPDATE that attempts to create FK
value in child table without matching candidate
key value in parent is rejected.
Action taken that attempts to update/delete a
candidate key value in parent table with
matching rows in child is dependent on
referential action specified using ON UPDATE and
ON DELETE subclauses:
CASCADE - SET NULL
SET DEFAULT - NO ACTION
50
IEF - Referential Integrity
CASCADE: Delete row from parent and delete
matching rows in child, and so on in cascading
manner.
SET NULL: Delete row from parent and set FK
column(s) in child to NULL. Only valid if FK columns
are NOT NULL.
SET DEFAULT: Delete row from parent and set each
component of FK in child to specified default. Only
valid if DEFAULT specified for FK columns
NO ACTION: Reject delete from parent. Default.
51
IEF - Referential Integrity
FOREIGN KEY (staffNo) REFERENCES Staff
ON DELETE SET NULL
FOREIGN KEY (ownerNo) REFERENCES Owner
ON UPDATE CASCADE
52
IEF - Enterprise Constraints
Could use CHECK/UNIQUE in CREATE and ALTER
TABLE.
Also have:
CREATE ASSERTION AssertionName
CHECK (searchCondition)
which is very similar to the CHECK clause.
53
IEF - Enterprise Constraints
CREATE ASSERTION StaffNotHandlingTooMuch
CHECK (NOT EXISTS (SELECT staffNo
FROM PropertyForRent
GROUP BY staffNo
HAVING COUNT(*) > 100))
54