0% found this document useful (0 votes)
27 views76 pages

Managing Database Constraints

This document discusses database constraints including creating, altering, and dropping constraints. It describes different types of constraints such as primary keys, foreign keys, unique constraints, check constraints, and null constraints. It provides examples of how to specify these constraints when creating tables in SQL using clauses like PRIMARY KEY, FOREIGN KEY, UNIQUE, CHECK, and NOT NULL. It also discusses referential integrity constraints and the different actions that can be specified for violations like RESTRICT, CASCADE, SET NULL, and SET DEFAULT.

Uploaded by

Esmael Mohammed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views76 pages

Managing Database Constraints

This document discusses database constraints including creating, altering, and dropping constraints. It describes different types of constraints such as primary keys, foreign keys, unique constraints, check constraints, and null constraints. It provides examples of how to specify these constraints when creating tables in SQL using clauses like PRIMARY KEY, FOREIGN KEY, UNIQUE, CHECK, and NOT NULL. It also discusses referential integrity constraints and the different actions that can be specified for violations like RESTRICT, CASCADE, SET NULL, and SET DEFAULT.

Uploaded by

Esmael Mohammed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 76

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

data-type for attributes.

For example, we can write the following statement:

1. CREATE DOMAIN EmpageC AS INTEGER

2. CHECK (Empage > 0 AND Empage < 21);

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

integrities constraints among tables.

A referential integrity is a rule in Relational DBs used to restrict inserting value for a

foreign key attribute that isn’t found it its base table.

Suppose we have Employee table where empID is a primary key and we have

Proj_Payment table which contains empID as one of its attribute.

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,

Foreign-key (key constraints) for a table and referential integrity constraints.

Because keys and referential integrity constraints are very important, there are special

clauses within the CREATE TABLE statement to specify them.

The PRIMARY KEY clause specifies one or more attributes that make up the

primary key of a relation.

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

You can specify that a constraint is enabled (ENABLE) or disabled (DISABLE).

If a constraint is ENABLED, data is checked as it is entered or updated in the database,

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.

An integrity constraint defined on a table can be in one of the following states:

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

illustrated in the Employee and Proj_Payment table declarations.

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

number) assume it is used to make proj_payment and salary_payment thru 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

Referential integrity is specified via the FOREIGN KEY clause

a referential integrity constraint can be violated when tuples are inserted or deleted, or

when a foreign key or primary key attribute value is updated.

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

employee table, or say it is deleted from the employee table

But before this operation happened there was entry in the Proj_Payment table for the

employee with that empID (‘HR006’).

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

So, What is the solution?

We can specify an alternative action to be taken by attaching a referential

triggered action clause to any foreign key constraint.

The options include SET NULL, CASCADE, and SET DEFAULT.

An option must be qualified with either ON DELETE or ON UPDATE.

For example , we can specify ON DELETE SET NULL and ON UPDATE CASCADE for the

foreign key empID of Employee in the Proj_Payment table.

It demands great care what triggered action to set for foreign-key constraints.
Database Constraints
Specifying Key and Referential Integrity (RI) Constraints

This means that:

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

were referencing the deleted employee tuple.

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

referencing the Updated employee tuple (HR006).


Database Constraints
Specifying Key and Referential Integrity (RI) Constraints

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

identify to which employee this payment tuple is due to be paid.

1. What if empID is an element of primary key in the proj_payment table?

- Setting Null value for attribute that is a PK or element of PKs isn’t allowed at all. Meaning, we

violated key Constraint in an attempt to define RI constraints.

This is why we noted and emphasized ‘choosing what triggered action to

associate during violation of RI constraints needs GREAT CARE


Database Constraints
Specifying Key and Referential Integrity (RI) Constraints

In general, the action taken by the DBMS for SET NULL or SET DEFAULT is the same for both

ON DELETE and ON UPDATE:

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

option ON DELETE or ON UPDATE, this is PROBLEMATIC scenario.


Database Constraints
Specifying Key and Referential Integrity (RI) Constraints

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

it in the database schema.

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

them by name if we want to alter or drop them latter.

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

command (that’s not good thing to do)

The names of all constraints within a particular schema must be unique.

A constraint name is used to identify a particular constraint in case the

constraint must be dropped later and replaced with another constraint,


Database Constraints
Specifying Constraints on Tuples Using CHECK

The constraints we have created so far are unnamed so that we can not refer

them by name if we want to alter or drop them latter.

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

command (that’s not good thing to do)

The names of all constraints within a particular schema must be unique.

A constraint name is used to identify a particular constraint in case the

constraint must be dropped later and replaced with another constraint,


Database Constraints
Specifying Constraints as Assertions

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

type constraints via declarative assertions, using the CREATE ASSERTION

statement.

Each assertion is given a constraint name and is specified via a condition similar to the

WHERE clause of an SQL query.

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

can write the following assertion:


Database Constraints
Specifying Constraints as Assertions
CREATE ASSERTION SALARY_CONSTRAINT
CHECK ( NOT EXISTS ( SELECT *
FROM EMPLOYEE E, EMPLOYEE M, DEPARTMENT D
WHERE E.Salary>M.Salary
AND E.Dno = D.Dnumber
AND D.Mgr_ssn = M.Ssn ) );
,
Database Constraints
Specifying Constraints as Assertions

The constraint name SALARY_CONSTRAINT is followed by the keyword CHECK, which

is followed by a condition in parentheses that must hold true on every database state for

the assertion to be satisfied.

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

the EXISTS and NOT EXISTS style of SQL conditions.


Database Constraints
Specifying Constraints as Assertions

Whenever some tuples in the database cause the condition of an ASSERTION statement to

evaluate to FALSE, the constraint is violated.

The constraint is satisfied by a database state if no combination of tuples in that database

state violates the constraint.

The basic technique for writing such assertions is to specify a query that selects any

tuples that violate the desired condition.

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

manager of their department.

If the result of the query is not empty, the assertion is violated.

Note that the CHECK clause and constraint condition can also be used to specify

constraints on individual attributes and domains and on individual tuples

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

checks are implemented more efficiently by the DBMS.


Database Constraints
Altering Constraints
Database Constraints
Dropping constraints

Creating, enabling, disabling and altering constraints can be done in


either of two ways;
either during the table definition (using create table statements) or
during table change (using the alter table statements).

Sometimes a constraint defined might be found useless (not working


anymore due to organizational need). So it must be dropped.
To drop the constraint use the drop constraint statements, like
ALTER TABLE dept DROP UNIQUE (dname, loc); // DROP UNIQUE

ALTER TABLE emp DROP PRIMARY KEY KEEP INDEX, // DROP PRIMARY KEY

DROP CONSTRAINT dept_fkey; // DROP CONSTRAINT by its Name


Database Constraints
Enabling Constraints

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

as an exception to the constraint.

If the constraint is in the enable no-validated state, violations resulting from data entered

while the constraint was disabled remain.

The rows that violate the constraint must be either updated or deleted in order for the

constraint to be put in the validated state.

Constraints disabled for performance reason shall be enabled for user action on the DB
Database Constraints
Disabling and deferring Constraints

 To enforce the rules defined by integrity constraints, the constraints


should always be enabled.
 We need temporarily disabling the integrity constraints of a table for
the following performance reasons:
 When loading large amounts of data into a table (Backup or import)
 When performing batch operations that make massive changes to a table (for
example, entering Bonus pay for all employees)
 When importing or exporting one table at a time

 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, . . . ;

 ALTER TABLE emp ADD PRIMARY KEY (empno) DISABLE;

 An ALTER TABLE statement that defines and disables an integrity constraint


never fails because of rows in the table that violate the integrity constraint.
 The definition of the constraint is allowed because its rule is not enforced.
Database Constraints
Setting Integrity Constraints Upon Definition
 The following CREATE TABLE and ALTER TABLE statements both define
and ENABLE integrity constraints:
 CREATE TABLE emp ( empno NUMBER(5) CONSTRAINT emp.pk
PRIMARY KEY, . . . ;
 ALTER TABLE emp ADD CONSTRAINT emp.pk PRIMARY KEY (empno);
 An ALTER TABLE statement that defines and attempts to enable an the
constraint can fail if rows of the table violate the integrity constraint.
 If this case, the statement is rolled back and the constraint definition is not
stored and not enabled.
 When you enable a UNIQUE or PRIMARY KEY constraint an associated
index is created.
Database Constraints
Renaming Constraints
 The ALTER TABLE...RENAME CONSTRAINT statement enables you to
rename any currently existing constraint for a table.
 The new constraint name must not conflict with any existing constraint
names for a user.
 The following statement renames the dname_ukey constraint for table
dept:
 ALTER TABLE dept RENAME CONSTRAINT dname_ukey TO dname_unikey;
 When you rename a constraint, all dependencies on the table remain valid.
 The RENAME CONSTRAINT clause provides a means of renaming
system generated constraint names.
Database Constraints
Differing Constraints
 When the database checks a constraint, it signals an error if the constraint
is not satisfied.
 You can defer checking validity of constraints till the end of a transaction.
 When you issue the SET CONSTRAINTS statement, the SET
CONSTRAINTS mode lasts for the duration of the transaction, or until
another SET CONSTRAINTS statement resets the mode.
 Within the application being used to manipulate the data, you must set all
constraints deferred before you actually begin processing any data.
Use the following DML statement to set all deferrable constraints deferred:
 SET CONSTRAINTS ALL DEFERRED;
Database Constraints
Efficient Use of Integrity Constraints: A Procedure

 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

Inserting, Updating and Deleting data via Views


Managing Views (Virtual Tables)
What are Views

 A view in SQL is a single table that is derived from other tables.

 These other tables can be base tables or previously defined views.

 A view does not necessarily exist in physical form; it is considered to be a

virtual table, in contrast to base tables, whose tuples are always

physically stored in the database.

 This limits the possible update operations that can be applied to views, but

it does not provide any limitations on querying a view.

 We can think of a view as a way of specifying a table that we need to


Managing Views (Virtual Tables)
What are Views

 A view is a logical representation of a table or combination of tables.

 In essence, a view is a stored query.

 A view derives its data from the tables on which it is based.

 These tables are called base tables.

 Base tables might in turn be actual tables or might be views themselves.

 operations performed on a view actually affect the base table of the view.

 You can use views in almost the same way as tables.

 You can query, update, insert into, and delete from views, like tables.
Managing Views (Virtual Tables)
What are Views ....

 Views can provide a different representation (such as subsets or supersets)

of the data that resides within other tables and views.

 Views are very powerful because they allow you to tailor the presentation

of data to different types of users.

 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

of the company for which the database is created.

 Constraints can be specified on views the same way like table constraints
Managing Views (Virtual Tables)
What are Views: Specification of Views

In SQL, the command to specify a view is CREATE VIEW.

The view is given a (virtual) table name (or view name), a list of attribute names, and a query to

specify the contents of the view.

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

the attributes of the defining tables in the default case.

Syntax:

Create View View-Name AS

SQL SELECT – or JOIN Statement


Managing Views (Virtual Tables)
To create a view, you must meet the following requirements:

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

GRANT OPTION or the system privileges with the ADMIN OPTION.


Managing Views (Virtual Tables)
Creating Views

 To create a view from an existing table or view use the following

CREATE VIEW view-name AS

SELECT attribute-lists FROM source-table/view-list(s) WHERE conditions

 Create View is key word and creates a view (Virtual Table) with view-name as the

name of the View

 The key word as tells to create the view as follows (using the SQL SELECT

STATEMENT that immediately Follows it)

 The select statement simply queries data from source-table(s)/view(s) which

fulfills the condition specified


Managing Views (Virtual Tables)
Creating Views

 To create a view from student table that contains all the data in that table

CREATE VIEW Allstud AS

SELECT * FROM student;

Allstud is name of the view (Virtual Table)

 It is created as SELECT * FROM STUDENT

 The Source table is Student

 Now we can issue DESCRIBE Allstud to see the description of this view
Managing Views (Virtual Tables)
Creating Views

 We can create a view by merging data from several Tables

 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

CREATE VIEW studview

AS SELECT s.Studid, s.studFname, s.studLname, sr.courseID, sr.stucouresult,

sr.studcougrd FROM student s, studresult sr

WHERE s.Studid = sr.SID;


Managing Views (Virtual Tables)
Creating Views

 Now we can issue the DESCRIBE STUDVIEW command to see the structure of

the studView view


Managing Views (Virtual Tables)
Creating Views
 We can now issue SQL query from the view Created already to see its data content
or to further create another view.
 See the SQL SELECT statement and its result from the studView we created earlier:
Select studFname, studLname from studView;
Managing Views (Virtual Tables)
Creating Views having WITH clause
 Views can be constructed specifying the WITH clause, which prevents
any updates, inserts, or deletes from being done to the base table through
the view.
 If no WITH clause is specified, the view, with some restrictions, is
innately updatable.
 In database Application with multiple user types (for example your lab
assignment EPRMS there are at least four user roles with different type of
privilege) having different role creating views having the WITH clause is
important to set some of the views only READ ONLY.
 Remember, Employees can only view their monthly salary information
they can’t Modify data.
Managing Views (Virtual Tables)
Replacing Views
 To replace a view, you must have all of the privileges required to drop
and create a view.
 If the definition of a view must change, the view must be replaced; you
cannot use an ALTER VIEW statement to change the definition of a view.
 You can replace views in the following ways:
You can drop and re-create the view.
 When a view is dropped, all grants of matching object privileges are
revoked from roles & users.
 After the view is re-created, privileges must be regranted.
Managing Views (Virtual Tables)
 Replacing Views
 You can redefine the view with a CREATE VIEW statement that contains
the OR REPLACE clause.
 The OR REPLACE clause replaces the current definition of a view and
preserves the current security authorizations.
 For example, assume that you created the studView view as shown
earlier, and, in addition, you granted several object privileges to roles and
other users.
 However, now you must redefine the studView view to change the
change the list of attributes to be included.
Managing Views (Virtual Tables)
 Replacing Views
 You can replace the current version of the studView view with the
following statement:

CREATE OR REPLACE VIEW studview

AS SELECT s.Studid, s.studFname, s.studLname, sr.courseID, sr.studcougrd FROM

student s, studresult sr

WHERE s.Studid = sr.SID;


Managing Views (Virtual Tables)
 Consequences of Replacing Views
 When we use CREATE OR REPLACE option to modify an already existing
view and replace the view this way, the following effects are done:
Replacing a view replaces the view definition in the data dictionary. All
underlying objects referenced by the view are not affected.
If a constraint in the CHECK OPTION was previously defined but not
included in the new view definition, the constraint is dropped.
All views dependent on a replaced view become invalid (not usable).
In addition, dependent PL/SQL program units may become invalid,
depending on what was changed in the new version of the view.

 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;

hence a database system shall identify all users (and user-categories


called roles) and grant privilege to the different users as per the business
need.
Database Security and the DBA
May be you are asking by now that Who is going to do that? And How?
The short answer for this is, it is the DBA. Who is the DBA?
The database administrator (DBA) is the central authority for managing a
database system.
The DBA’s responsibilities include granting privileges to users who need
to use the system and classifying users and data in accordance with the
policy of the organization.
The DBA has a DBA account in the DBMS, sometimes called a SYSTEM or
SUPE-RUSER account, which provides powerful capabilities that are not
made available to regular database accounts and users.
Using these accounts the DBA creates and manage other users.
Database Security
DBA-privileged commands include commands for granting and revoking
privileges to individual accounts, users, or user groups and for performing
the following types of actions:
1. Account creation. This action creates a new account and password for a
user or a group of users to enable access to the DBMS or its part.
2. Privilege granting. This action permits the DBA to grant certain
privileges
to certain accounts.
3. Privilege revocation. This action permits the DBA to revoke (cancel)
certain privileges that were previously given to certain accounts.
4. Security level assignment. This action consists of assigning user accounts
Database Security and the DBA …
The DBA shall be able to create a data access policy that fulfills all the
requirements of data confidentiality in the organization to whom the DB
is targeted.
The DBA is responsible for the overall security of the database system.
The Account creation action in the preceding list is used to control access
to the DBMS as a whole.
Whereas the actions granting privilege and revoking privilege are used to
control discretionary database authorization, and
The DBA action called security level assignment is used to control
mandatory authorization.
Database Security
Access Control, User Accounts, and Database Audits
Whenever a person or a group of persons needs to access a database
system, the individual or group must first apply for a user account.
The DBA will then create a new account number and password for the
user if there is a legitimate need to access the database.
The user must log in to the DBMS by entering the account number and
password whenever database access is needed.
The DBMS checks that the account number and password are valid; if they
are, the user is permitted to use the DBMS and to access the database.
Application programs can also be considered users and are required to log
in to the database.
Database Security
Access Control, User Accounts, and Database Audits
It is straightforward to keep track of database users and their accounts
and passwords by creating an encrypted table or file with a minimum of
two fields: Account-name & Password.
This table can easily be maintained by the DBMS, and whenever a new
account is created, a new record is inserted into the table.
When an account is canceled, the corresponding record must be deleted
from the table.
The database system must also keep track of all operations on the
database that are applied by a certain user throughout each login session,
which consists of the sequence of database interactions that a user
performs from the time of logging in to the time of logging off.
Database Security
Access Control, User Accounts, and Database Audits

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

user’s account until the user logs off.

It is particularly important to keep track of update operations that are

applied to the database so that, if the database is tampered with, the DBA

can determine which user did the tampering.

This activity is part of what we call DB access control.


Database Security
Access Control, User Accounts, and Database Audits
To keep a record of all updates applied to the database and of particular
users who applied each update, we can modify the system log.
The system log includes an entry for each operation applied to the
database that may be required for recovery from a transaction failure or
system crash.
We can expand the system log (using PL/SQL Program elements) entries
so that they also include the account number of the user and the online
computer or device ID that applied each operation recorded in the log.
If any tampering with the database is suspected, a database audit is
performed, which consists of reviewing the log to examine all accesses
and operations applied to the database during a certain time period.
Database Security and the DBA …
Access Control, User Accounts, and Database Audits
When an illegal or unauthorized operation is found, the DBA can
determine the account number used to perform the operation.
Database audits are particularly important for sensitive databases that are
updated by many transactions and users, such as a banking database that
can be updated by thousands of bank tellers.
A database log that is used mainly for security purposes serves as an
audit trail.
Database access control is hence a mechanism used to allow or deny
database users access to database operation on the database or its
elements.
Database Access control can be done at account level or database element
Database Security
Discretionary Access Control: USING Granting & Revoking Privileges
The typical method of enforcing discretionary access control in a database
system is based on the granting and revoking of privileges.
The main idea is to include statements in the query language that allow
the DBA and selected users to grant and revoke privileges.
Types of Discretionary Privileges
Since SQL 2 the concept of an authorization identifier is used to
refer, roughly speaking, to a user account (or group of user accounts).
The DBMS must provide selective access to each relation in the database
based on specific accounts.
Operations may also be controlled; thus, having an account does not
necessarily entitle the account holder to all the functionality provided by the
Database Security
Discretionary Access Control: USING Granting & Revoking Privileges
Easily, there are two levels for assigning privileges to use the DB
1. The account level: At this level, the DBA specifies the particular
privileges that each account holds independently of the relations in the
database.
2. The relation (or table) level: At this level, the DBA can control the
privilege to access each individual relation or view in the database.
This means there is an already created database/schema consisting of
many database objects (table, view, types, Triggers, functions, etc).
If a user is given privilege account level, he/she is allowed to access the
specified access via that account. else sometimes, we will manual set
privilege for users for individual DB objects.
Database Security
Discretionary Access Control: USING Granting & Revoking Privileges
The privileges at the account level apply to the capabilities provided to the
account itself and can include:
the CREATE SCHEMA or CREATE TABLE privilege,
the CREATE VIEW privilege;
the ALTER privilege,
the DROP privilege, to delete relations or views;
the MODIFY privilege, to insert, delete, or update tuples; and
the SELECT privilege, to retrieve information from the DB by using a SELECT query.

Notice that these account privileges apply to the account in general.


If a certain account does not have the CREATE TABLE privilege, no table
can be created from that account.
Account-level privileges are not defined as part of SQL2; they are left to
Database Security
Discretionary Access Control: USING Granting & Revoking Privileges
The second level of privileges applies to the relation level, which includes
base relations and virtual (view) relations.
These privileges are defined for SQL2.
Privileges at the relation level specify for each user the individual relations
on which each type of command can be applied.
Some privileges also refer to individual columns (attributes) of relations.
SQL2 commands provide privileges at the relation and attribute level only.
Although this distinction is general, it makes it difficult to create accounts
with limited privileges.
The granting and revoking of privileges generally follow an authorization
model for discretionary privileges known as the access matrix model,
Database Security
Discretionary Access Control: USING Granting & Revoking Privileges
Each position M(i, j) in the matrix represents the types of privileges (read,
write, update) that subject i holds on object j.
For example the table below can show the Access control in EPRMS (Your
Lab Assignment)
User\Privileged to employee Emp_salary attendance OvertimeP
ay
employee SELECT SELECT NO Previlege NO Previlege
privilege privilege
Cashier SELECT SELECT Create, Alter, Create, Alter,
privilege privilege SELECT SELECT
privilege privilege
Accountant Alter, Create, Alter, Create, Alter, Create, Alter,
SELECT, SELECT, SELECT, SELECT,
Modify, Modify, Drop Modify, Drop Modify, Drop
privilege privilege privilege privilege
Database Security
Big-bang example
Create a schema with tables and a view and assign SELECT privilege to
the account anwar (anwar can only select cant delete update ….)
Database Security
Managing User Privileges and Roles
in general, Privileges and roles are used to control user access to data and
the types of SQL statements that can be executed.
The table that follows describes the three types of privileges and roles:

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?

You might also like