Managing Database Constraints
Managing Database Constraints
Creating Constraints
Types of Constraints
Altering constraints
Dropping constraints
Database Constraints
• Database constraints are SQL statement parts that are used in Association
with SQL DDL statements to specify restrictions and limitations as well as
relationship among objects being created or their characteristics.
• Constraints can be associated with particular database or table, view or
some database object.
• In this section we only focus on constraints defined on tables and We
will later on discuss the specification of more general constraints,
called assertions.
• The use of constraints in tables include key and referential integrity
constraints, restrictions on attribute domains and NULLs, and constraints
on individual tuples within a relation using the CHECK clause.
Database Constraints
Specifying Attribute Constraints and Attribute Defaults
Because SQL allows NULLs as attribute values, a constraint NOT NULL may
be specified if NULL is not permitted for a particular attribute.
This is always implicitly specified for the attributes that are part of the
primary key of each relation, but it can be specified for any other attributes
whose values are required not to be NULL.
It is also possible to define a default value for an attribute by appending the
clause DEFAULT <value> to an attribute definition.
The default value is included in any new tuple if an explicit value is not
provided for that attribute.
If no default clause is specified, the default default value is NULL for
attributes that do not have the NOT NULL constraint.
Database Constraints
Specifying Attribute Constraints and Attribute Defaults
Assume the employee table create statement we wrote previously:
create table Employee
(
EmpID Varchar(10),
EmpFName Varchar(20),
EmpLname Varchar(20),
EmpAdress Varchar(20),
EmpMObNumber Varchar(15),
EmpTitle Varchar(20),
PRIMARY KEY(EmpID)
);
Database Constraints
Specifying Attribute Constraints and Attribute Defaults
We can modify the create table statement and add attribute constraints and
default value constraints as:
1. create table Employee
2. (EmpID Varchar(10),
3. EmpFName Varchar(20) NOT NULL,
4. EmpLname Varchar(20) NOT NULL,
5. EmpAdress Varchar(20) NOT NULL DEFAULT ‘HARAR’,
6. EmpMObNumber Varchar(15),
7. EmpTitle Varchar(20) NOT NULL DEFAULT ‘Lecturer’,
8. PRIMARY KEY(EmpID) );
All the phrases in bold are specifying NOT NULL (as in line 4,5) and NOT
NULL and DEFAULT value constraints (as in line 6 and 8).
Database Constraints
Specifying Attribute Constraints and Attribute Defaults
Another type of constraint can restrict attribute or domain values
using the CHECK clause following an attribute or domain definition.
suppose the age for employees is restricted to be integer numbers
between 21 and 70; then, we can change the attribute declaration of
age in the Employee table.
To do this we can add the following statement into the create table
statement
Empage int NOT NULL CHECK(Empage > 20 AND Empage < 70);
Database Constraints
Specifying Attribute Constraints and Attribute Defaults
The CHECK clause can also be used in conjunction with the CREATE DOMAIN statement.
The Create Domain command creates a domain for an attribute that can be referred as
We can then use the created domain EmpageC as the attribute type for all attributes that
refer to Empage such as Empage of Employee, Empage of in any other table that uses
Empage, and so on
Database Constraints
Specifying Key and Referential Integrity Constraints
The other use of constraints specified on tables is to define key and referential
A referential integrity is a rule in Relational DBs used to restrict inserting value for a
Suppose we have Employee table where empID is a primary key and we have
Referential integrity rule dictates that we cannot allow insertion of value for empID
in the Proj_Payment table if that same value isn’t found in the Employee Table.
Database Constraints
Specifying Key and Referential Integrity Constraints
Coming Back to our point, we can use constraints to specify Primary Key for a table,
Because keys and referential integrity constraints are very important, there are special
The PRIMARY KEY clause specifies one or more attributes that make up the
If a primary key has a single attribute, the clause can follow the attribute directly
Primary Key (empID) which can alternatively be written as empID INT PRIMARY KEY;
Database Constraints
Integrity Constraint States
and data that does not conform to the constraint is prevented from being entered.
If a constraint is DISABLED, then data that does not conform can be allowed to enter the
database.
Additionally, you can specify that existing data in the table must conform to the constraint
(VALIDATE).
Conversely, if you specify NOVALIDATE, you are not ensured that existing data conforms.
Database Constraints
Integrity Constraint States
VALIDATE and ENABLE integrity constraint seem similar in effect but are different.
The VALIDATE integrity constraint command tries to check an already existing data in a table to
conform to the constraint specified in the data dictionary and referred by name.
The same is true for DISABLE and NOVALIDATE integrity constraint commands.
ENABLE, VALIDATE
ENABLE, NOVALIDATE
DISABLE, VALIDATE
DISABLE, NOVALIDATE
Database Constraints
Specifying Key and Referential Integrity Constraints
The UNIQUE clause specifies alternate (unique) keys, also known as candidate keys as
The UNIQUE clause can also be specified directly for a unique key if it is a single attribute.
Suppose we want to add column called empBankAcctNo (for employee bank account
This attribute (empBankAcctNo ) isn’t a Primary key for the employee table however since
every employee should receive payment’s via own empBankAcctNo it shall be UNIQUE
Database Constraints
Specifying Key and Referential Integrity Constraints
a referential integrity constraint can be violated when tuples are inserted or deleted, or
The default action that SQL takes for an integrity violation is to reject the update
operation that will cause a violation, which is known as the RESTRICT option.
This RESTRICT is due the fact that the delete or Update statement using the foreign-
key of the table as primary key in its base table will results in a row in the second table
with a value for the foreign key that’s not in the base table.
Database Constraints
Specifying Key and Referential Integrity (RI) Constraints
Suppose the case in which employee with empID ‘HR006’ is updated its ID to ‘HR004’ in the
But before this operation happened there was entry in the Proj_Payment table for the
By default SQL takes for an integrity violation is to reject the update operation that will cause
a violation hence reject the update empID or delete employee with empID = ‘HR006’ in our
case.
For example, if we deleted employee with empID ‘HR006’ the result is that we will have
empID HR006 in the Proj_Payment table but not in the employee table (violation of RI)
Database Constraints
Specifying Key and Referential Integrity (RI) Constraints
For example , we can specify ON DELETE SET NULL and ON UPDATE CASCADE for the
It demands great care what triggered action to set for foreign-key constraints.
Database Constraints
Specifying Key and Referential Integrity (RI) Constraints
1. if the tuple for an employee with empID ’HR006’ is deleted, the value of empID is
automatically set to NULL for all employee tuples in the Proj_Payment table that
2. Again when empID is updated to other value say ‘HR004’ ,since the CASCADE
option is used ON UPDATE, the value of empID is automatically set to the new
value ‘HR004’ for all employee tuples in the Proj_Payment table that were
In the first case (ON DELETE SET NULL), two problems may arise:
1. What is the sense of the tuple in the Proj_Payment table with Null for empID?
- Even if empID is not an element of the primary keys in the proj_payment table we can’t
- Setting Null value for attribute that is a PK or element of PKs isn’t allowed at all. Meaning, we
In general, the action taken by the DBMS for SET NULL or SET DEFAULT is the same for both
That is, the value of the affected referencing attributes is changed to NULL for SET NULL and
to the specified default value of the referencing attribute for SET DEFAULT.
The SET DEFAULT is good option than NULL if the column is defined as NOT NULL.
However, one more word to remind you on the usage of SET DEFAULT is that if you
haven't specified DEFAULT clause for the column for which you chosen SET DEFAULT
The action for CASCADE ON DELETE is to delete all the referencing tuples, whereas the action
for CASCADE ON UPDATE is to change the value of the referencing foreign key attribute(s) to
the updated (new) primary key value for all the referencing tuples.
It is the responsibility of the database designer to choose the appropriate action and to specify
Question: Suppose an employee with empID ‘HR006’ was an employee of say HU for
example; He left HU and is no more an employee of HU. But there is Payment prepared in
his/her name (using HR006) that he/she shall collect. but that haven't been collected.
What shall we do this payment data ? Delete, set Null, set Default?
Database Constraints
Specifying Key and Referential Integrity (RI) Constraints
Here’s command to create the Employee Table with all the constraints discussed are itemized
1. create table Employee(
2. EmpID Varchar(10) PRIMARY KEY,
3. EmpFName Varchar(20) NOT NULL,
4. EmpLname Varchar(20) NOT NULL,
5. EmpAdress Varchar(20) NOT NULL DEFAULT ‘HARAR’,
6. EmpMObNumber Varchar(15),
7. EmpDepartment VARCHAR (15),
8. EmpTitle Varchar(20) NOT NULL DEFAULT ‘HARAR’,
9. empBankacctNo VARCHAR (20) UNIQUE,
10.Empage int NOT NULL CHECK(Empage > 20 AND Empage < 70) );
o Note that all constraints on the Employee table are key constraint types
Database Constraints
Specifying Key and Referential Integrity (RI) Constraints
Here’s command to create the Proj_Payment Table with all the constraints discussed are
itemized
1. create table Proj_Payment
2. (PayNumber INTEGER DEFAULT 1,
3. ProjID Varchar(10),
4. Empid Varchar(20),
5. EmpTitle Varchar(20),
6. TotalHours NUMBER,
7. PayPerHour NUMBER,
8. GrossPay NUMBER,
9. NetPay NUMBER,
10.PRIMARY KEY(ProjID, Empid)
Database Constraints
Giving Names to Constraints
The constraints we have created so far are unnamed so that we can not refer
If the constraints for each table is written the way we wrote earlier (without
naming the constraints) altering a constraint may be possible via alter table
The constraints we have created so far are unnamed so that we can not refer
If the constraints for each table is written the way we wrote earlier (without
naming the constraints) altering a constraint may be possible via alter table
Assertions can be used to specify additional types of constraints that are outside the scope of
the built-in relational model constraints (primary and unique keys, entity integrity, and
referential integrity)
These built-in constraints can be specified within the CREATE TABLE statement of SQL
,
Database Constraints
Specifying Constraints as Assertions
In SQL, users can specify general constraints—those that do not fall into any of the built in
statement.
Each assertion is given a constraint name and is specified via a condition similar to the
For example, to specify the constraint that the salary of an employee must not be greater
than the salary of the manager of the department that the employee works for in SQL, we
is followed by a condition in parentheses that must hold true on every database state for
The constraint name can be used later to disable the constraint or to modify or drop it.
The DBMS is responsible for ensuring that the condition is not violated.
Any WHERE clause condition can be used, but many constraints can be specified using
Whenever some tuples in the database cause the condition of an ASSERTION statement to
The basic technique for writing such assertions is to specify a query that selects any
By including this query inside a NOT EXISTS clause, the assertion will specify that the result
of this query must be empty so that the condition will always be TRUE.
Database Constraints
Specifying Constraints as Assertions
Thus, the assertion is violated if the result of the query is not empty. In the preceding
example, the query selects all employees whose salaries are greater than the salary of the
Note that the CHECK clause and constraint condition can also be used to specify
A major difference between CREATE ASSERTION and the individual domain constraints
and tuple constraints is that the CHECK clauses on individual attributes, domains, and
tuples are checked in SQL only when tuples are inserted or updated in a specific table.
Database Constraints
Specifying Constraints as Assertions
Hence, constraint checking can be implemented more efficiently by the DBMS in these
cases.
The schema designer should use CHECK on attributes, domains, and tuples
only when he or she is sure that the constraint can only be violated by insertion or
updating of tuples.
On the other hand, the schema designer should use CREATE ASSERTION only in cases
where it is not possible to use CHECK on attributes, domains, or tuples, so that simple
ALTER TABLE emp DROP PRIMARY KEY KEEP INDEX, // DROP PRIMARY KEY
If a constraint is enabled, no row violating the constraint can be inserted into the table.
However, while the constraint is disabled such a row can be inserted. This row is known
If the constraint is in the enable no-validated state, violations resulting from data entered
The rows that violate the constraint must be either updated or deleted in order for the
Constraints disabled for performance reason shall be enabled for user action on the DB
Database Constraints
Disabling and deferring Constraints
In all three cases, temporarily disabling integrity constraints can improve the
performance of the operation, especially in data warehouse configurations.
Database Constraints
Setting Integrity Constraints Upon Definition
When an integrity constraint is defined in a CREATE TABLE or ALTER TABLE
statement.
It can be enabled, disabled, or validated or not validated as determined by
your specification of the ENABLE/DISABLE clause.
The following CREATE TABLE and ALTER TABLE statements both define and
disable integrity constraints:
CREATE TABLE emp ( empno NUMBER(5) PRIMARY KEY DISABLE, . . . ;
Using integrity constraint states in the ff order ensure the best benefits:
1. Disable state.
2. Perform the operation (load, export, import).
3. Enable novalidate state.
4. Enable state.
Some benefits of using constraints in this order are:
1. No locks are held.
2. All constraints can go to enable state concurrently.
3. Constraint enabling is done in parallel.
4. Concurrent activity on table is permitted.
Managing Views (Virtual
Tables)
What are Views
Creating Views
Modifying Views
Using views
This limits the possible update operations that can be applied to views, but
operations performed on a view actually affect the base table of the view.
You can query, update, insert into, and delete from views, like tables.
Managing Views (Virtual Tables)
What are Views ....
Views are very powerful because they allow you to tailor the presentation
Using Views you can present the same data on the same table(s) in
different ways for different ways as per the information classification rule
Constraints can be specified on views the same way like table constraints
Managing Views (Virtual Tables)
What are Views: Specification of Views
The view is given a (virtual) table name (or view name), a list of attribute names, and a query to
If none of the view attributes results from applying functions or arithmetic operations, we do not
have to specify new attribute names for the view, since they would be the same as the names of
Syntax:
To create a view in your schema, you must have the CREATE VIEW privilege.
To create a view in another user's schema, you need the CREATE ANY VIEW
system privilege.
The owner of the view (whether it is you or another user) must have been
explicitly granted privileges to access all objects referenced in the view definition.
If the owner of the view intends to grant access to the view to other users, the
owner must have received the object privileges to the base objects with the
Create View is key word and creates a view (Virtual Table) with view-name as the
The key word as tells to create the view as follows (using the SQL SELECT
To create a view from student table that contains all the data in that table
Now we can issue DESCRIBE Allstud to see the description of this view
Managing Views (Virtual Tables)
Creating Views
For example we want to create a View called studView that selects studID
firstname and last name from student table and course ID, course grd for
each course to the student from the studresult table having same ID as the
student table
Now we can issue the DESCRIBE STUDVIEW command to see the structure of
student s, studresult sr
You must take into consideration these effects when replacing views.
Managing Views (Virtual Tables)
Using Views in Queries
To issue a query or an INSERT, UPDATE, or DELETE statement against a
view, you must have the SELECT, INSERT, UPDATE, or DELETE object
privilege for the view, respectively, either explicitly or through a role.
Views can be queried in the same manner as tables. For example, to query
the Division1_staff view, enter a valid SELECT statement that references
the view:
SELECT * FROM Division1_staff;
ENAME EMPNO JOB DNAME
-----------------------------------------------------------------------
CLARK 7782 MANAGER ACCOUNTING
Managing Views (Virtual Tables)
Using Views in Queries
With some restrictions, rows can be inserted into, updated in, or deleted
from a base table using a view.
The following statement inserts a new row into the emp table using the
sales_staff view:
INSERT INTO sales_staff VALUES (7954, 'OSTER', 30);
Managing Views (Virtual Tables)
Using Views in Queries
Restrictions on DML operations for views use the following criteria in the
order listed:
1. If a view is defined by a query that contains SET or DISTINCT operators, a GROUP BY clause, or
a group function, then rows cannot be inserted into, updated in, or deleted from the base tables
using the view.
2. If a view is defined having WITH CHECK OPTION, a row cannot be inserted into, or updated in,
the base table (using the view), if the view cannot select the row from the base table.
3. If a NOT NULL column that does not have a DEFAULT clause, then a row cannot be inserted into
the base table using the view.
4. If the view was created by using an expression, such as DECODE(deptno, 10, "SALES", ...), then
rows cannot be inserted into or updated in the base table using the view.
Database Security
Database security is a broad area that discourses issues, like the following:
Various legal & ethical issues regarding the right to access certain data
Policy issues at the governmental, institutional, or corporate level regarding what
kinds of information should not be made publicly available
System-related issues such as the system levels at which various security
functions should be enforced
The need in some organizations to identify multiple security levels and to
categorize the data and users based on these classifications (we will focus on these
aspect only)
In general the need for DB security is to assure information access only by
authorized users and keeping data safe.
Database Security
Take your lab assignment as an example where an employee can only
view his own monthly salary details but cant modify it.
Similarly, consider a bank system (CBE for example) that contains DB of
users bank account information;
If end users are able to accesss the database directly, everyone could have
had Millions in his/her bank account with the help of a single and simple
SQL statements like
UPDATE customer_account set current_balance = 100000000000……
where account_number = xxxxxx;
When a user logs in, the DBMS can record the user’s account name and
associate it with the computer or device from which the user logged in.
All operations applied from that computer or device are attributed to the
applied to the database so that, if the database is tampered with, the DBA
Privileges and roles can be granted to other users by users who have been
granted the privilege to do so.
End of the Course
This is, However, Not where this course was
ought to end.
Anyways,
WWW?