❖ Constraints |
So far, we have considered several kinds of constraints:
create table Employee ( id integer primary key, name varchar(40), salary real, age integer check (age > 15), worksIn integer references Department(id), constraint PayOk check (salary > age*1000) );
❖ Constraints (cont) |
Column and table constraints ensure validity of one table.
Ref. integrity constraints ensure connections between tables are valid.
However, specifying validity of entire database often requires constraints involving multiple tables.
Simple example (from banking domain):
for all Branches b b.assets == (select sum(acct.balance) from Accounts acct where acct.branch = b.location)
i.e. assets of a branch is sum of balances of accounts held at that branch
❖ Assertions |
Assertions are schema-level constraints
CREATE ASSERTION name CHECK (condition)
The condition is expressed as "there are no violations in the database"
Implementation: ask a query to find all the violations; check for empty result
❖ Assertions (cont) |
Example: #students in any UNSW course must be < 10000
create assertion ClassSizeConstraint check ( not exists ( select c.id from Courses c join Enrolments e on (c.id = e.course) group by c.id having count(e.student) > 9999 ) );
Needs to be checked after every change to either
Courses
Enrolments
❖ Assertions (cont) |
Example: assets of branch = sum of its account balances
create assertion AssetsCheck check ( not exists ( select branchName from Branches b where b.assets <> (select sum(a.balance) from Accounts a where a.branch = b.location) ) );
Needs to be checked after every change to either
Branches
Accounts
❖ Assertions (cont) |
On each update, it is expensive
So, most RDBMSs do not implement general assertions.
Typically, triggers are provided as
Produced: 12 Oct 2020