0% found this document useful (0 votes)
8 views

6.SQL Intermediate

Uploaded by

arun vilwanathan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

6.SQL Intermediate

Uploaded by

arun vilwanathan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

CS2855 Databases

6. SQL: Integrity
Constraints
Department Of Computer Science

Mostly adapted from Database System Concepts, 6th Ed. Silberschatz et. al
Overview of (most of ) the Course

Text description ER diagram

SQL Relational Model

Normalisation theory

Relational Algebra
Content

SQL allows to control:

• The domain of values associated with


each attribute
• Type definitions
• Integrity constraints: restrictions on
what information can populate our tables
(e.g., some attribute cannot be null)
Type & Domain
Definitions
Built-in Data Types in SQL
char(n): A fixed-length character string with user-
specified length n.
varchar(n): A variable-length character string with user-
specified maximum
int, smallint
numeric(p, d): A fixed-point number with user-specified
precision. Consists of p digits (plus a sign), and d of
the p digits are to the right of the decimal point.
Example: numeric(3,1) allows 44.5 to be stored exactly.
real, double precision, float(n):

5
Built-in Data Types in SQL
date: Dates, containing a (4 digit) year, month
and day
• Example: date ‘2005-7-27’
time: Time of day, in hours, minutes and
seconds.
• Example: time ‘09:00:30’ time ‘09:00:30.75’
timestamp: date plus time of day
• Example: timestamp ‘2005-7-27 09:00:30.75’
interval: period of time
• Subtracting a date/time/timestamp value from another gives
an interval value
• Interval values can be added to date/time/timestamp values
6
Built-in Data Types in SQL
• Can extract values of individual fields from
date/time/timestamp
• Example: extract (year from r.starttime)

• Can cast string types to date/time/timestamp


• Example: cast <string-valued-expression> as date
• Example: cast <string-valued-expression> as time

• SQL allows comparisons on all these types

7
User-Defined Types
• The CREATE TYPE statement allows you to create a
composite type or enumeration

CREATE TYPE assignment AS ENUM (


‘assginemnt1’, ‘assignment2’, ‘miniProject’);

• Now it will function as an integrity constraint:


create table student_submission
(st_id int primary key,
submitted assignment);

INSERT INTO student_submission VALUES (102,


‘assignment3’)
• Outputs an error

8
User-Defined Types
• The CREATE TYPE statement allows you also to
create a composite type
CREATE TYPE film_summary AS (
film_id INT,
title VARCHAR,
release_year YEAR
);

• Useful for function that returns several values:


film_id, title, and release_year.

9
cont.
CREATE OR REPLACE FUNCTION get_film_summary (f_id INT)
RETURNS film_summary AS
$$
SELECT
film_id, title, release_year
FROM
film
WHERE
film_id = f_id ;
$$
LANGUAGE SQL;

SELECT
*
FROM get_film_summary (40);
10
User Defined Domains
• A domain is a data type + optional constraints
(restrictions on the allowed set of values).
• Domain constraints are the most elementary
form of integrity constraint: they test values
inserted in the database.

11
User Defined Domains
• Creates a user-defined data type with constraints such
as NOT NULL, CHECK, etc.

• In this table, both first_name and last_name columns are not null and should
not contain spaces. To make it easier for management, you can create a
contact_name domain as follows:
12
Cont.

And use the contact_name as the data type of the first_name and
last_name columns:

13
User Defined Domains
• New domains can be created from existing data
types
• Example:
create domain Dollars numeric(12, 2)
create domain Pounds numeric(12,2)
• An attempt to assign a value of type Dollars to a
variable of type Pounds results in syntax error
Application: branch_name and customer_name are
both of type strings. How would you forbid queries
comparing branch_name to customer_name?

14
(Explicit)
Integrity Constrains

15
Integrity constraints guard against accidental
damage to the database, by ensuring that
authorized changes to the database do not
result in a loss of data consistency.

• A checking account must have a balance


greater than $10,000.00
• A salary of a bank employee must be at
least $4.00 an hour
• A customer must have a (non-null) phone
number
16
Constraints on a Single Relation
1. not null
2. unique
3. check (P), where P is a predicate
(i.e. a propositional formula)
4. Referential integrity (foreign
Keys)

These integrity-constraints statements can


be included in the create table (and some in
the create domain) commands.
17
1. not null Constraint
• The null value is a member of all domains
• Thus (by default) it is a legal value for any attribute
in SQL.

• Declare in create table branch that branch_name


attribute is not null:
create table account
(branch_name char(15) not null,
…)
• Declare the domain Dollars to be not null:
create domain Dollars numeric(12,2) not null
18
2. The Unique Constraint

• The unique specification states that the


attributes
A1, A2, … Am
form de-facto a candidate key: no two
tuples in the relation can be equal on all
of them (but they can be null; in
contrast to primary keys).

19
Unique (examples)

Examples:

the name of this


constraint

20
3. The check clause
When applied to a table creation, the check(P) clause
specifies a predicate P (a propositional formula) that
must be satisfied by every tuple in the relation
(i) Check in the create table command
Example: declare branch_name as the primary key for
branch and ensure that the values of assets are non-
negative
create table branch
(branch_name char(15) not null,
branch_city char(30),
assets integer,
primary key (branch_name),
check (assets >= 0))
21
(ii) Check in the create domain command
Example: use the check clause to ensure that an
hourly_wage domain allows only values greater than
the allowed minimum wage:
create domain hourly_wage numeric(5,2)
constraint value_test check(value > = 4.00)

• The domain has a constraint that ensures that the


hourly_wage is greater than 4.00
• The optional “constraint value_test” assigns a
name to the constraint:
• Helpful when inserts output errors

22
4. Referential Integrity (Foreign Keys)
• Foreign key: ensures that a value that appears in one
table for a given (set of) attributes also appears in
another relation So now we can’t delete this row in branch table;
because it is a foreign key of another table’s row
Example:
• “Perryridge” appears as a branch name in a row in account
table
• Then we want to make sure there exists a row in the branch
table for branch “Perryridge”.
branch
account

23
Example

(we can also take out


Here we use a shorthand: “(product_no)” if
that’s the PK in table
products):

24
4. Referential Integrity (Foreign Keys)

• Primary and candidate keys and foreign keys


can be specified as part of the SQL create
table statement:
• The primary key clause lists attributes that comprise
the primary key.
• The foreign key clause lists the attributes that
comprise the foreign key and the name of the relation
referenced by the foreign key. By default, a foreign key
references the primary key attributes of the
referenced table.
25
Example

create table customer


(customer_name char(20),
customer_street char(30),
customer_city char(30),
create table account primary key (customer_name ))
(account_number char(10),
branch_name char(15), create table branch
balance integer, (branch_name char(15),
primary key (account_number), branch_city char(30),
foreign key (branch_name) references branch ) assets numeric(12,2),
primary key (branch_name ))
create table depositor
(customer_name char(20),
account_number char(10),
primary key (customer_name, account_number),
foreign key (account_number ) references account,
foreign key (customer_name ) references customer )
26
• When a referential integrity constraint is
violated, the normal procedure is to
reject the action that caused the
violation. Other solutions are also
possible.
• Integrity constraints can be added to an
existing relation by using the command:
alter table table_name add <constraint>
In this case the system first ensures that
the relation satisfies the new constraint.
If it does, the constraint is added.
27
Assertions
• We’ve seen Foreign Keys and domain constraints
• These are special case of assertions.
• An assertion is a predicate (like check) expressing a
condition that we wish the database always to
satisfy.
• It relates to a database object (like a table).
• E.g., “the sum of all loans at the branch must be less
than the sum of all account balances”
create assertion <assertion-name> check <predicate>
• When an assertion is made, the system tests it for
validity, and tests it again on every update that may
violate the assertion. (May introduce a significant amount
of overhead; hence assertions should be used with great care.)
28
End

You might also like