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

Lecture 05 SQL Definition

The document discusses SQL data definition and integrity constraints. It covers: 1. The different data types supported in SQL like numeric, character, datetime. 2. How to define integrity constraints like required fields, domain checks, entity integrity, referential integrity using SQL keywords like NOT NULL, CHECK, PRIMARY KEY, FOREIGN KEY. 3. How to create and alter tables using SQL, specifying data types, constraints, defaults, indexes in the CREATE TABLE statement.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Lecture 05 SQL Definition

The document discusses SQL data definition and integrity constraints. It covers: 1. The different data types supported in SQL like numeric, character, datetime. 2. How to define integrity constraints like required fields, domain checks, entity integrity, referential integrity using SQL keywords like NOT NULL, CHECK, PRIMARY KEY, FOREIGN KEY. 3. How to create and alter tables using SQL, specifying data types, constraints, defaults, indexes in the CREATE TABLE statement.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

Lecture 05:

SQL: DATA DEFINITION

1
Objectives
• The data types supported by the SQL standard.
• The purpose of the integrity enhancement feature of SQL.
• How to define integrity constraints using SQL including:
– required data; domain constraints; entity integrity; referential
integrity; general constraints.
• How to use the integrity enhancement feature in the CREATE and
ALTER TABLE statements.
• The purpose of views.
• How to create and delete views using SQL.
• How the DBMS performs operations on views.
• Under what conditions views are updatable.
• The advantages and disadvantages of views.
• How the ISO transaction model works.
• How to use the GRANT and REVOKE statements as a level of
security.
2
The ISO SQL Data Types
• SQL Identifiers
– an identifier can be no longer than 128 characters (most
dialects have a much lower limit than this);
– an identifier must start with a letter;
– an identifier cannot contain spaces.

Data type Declarations


boolean BOOLEAN
character CHAR VARCHAR
bit BIT BIT VARYING
exact numeric NUMERIC DECIMAL INTEGER SMALLINT
approximate numeric FLOAT REAL DOUBLE PRECISION
datetime DATE TIME TIMESTAMP
interval INTERVAL
large objects CHARACTER LARGE OBJECT BINARY LARGE OBJECT

3
SQL Scalar Data Types
• Boolean data consists of the distinct truth values TRUE
and FALSE.
• Character data consists of a sequence of characters
from an implementation-defined character set
branchNo CHAR(4)
address VARCHAR(30)
• Bit data type is used to define bit strings, that is, a
sequence of binary digits (bits), each having either the
value 0 or 1
bitString BIT(4)

4
Exact Numeric Data
• The exact numeric data type is used to define numbers
with an exact representation.
• NUMERIC and DECIMAL store numbers in decimal
notation. The default scale is always 0. INTEGER is used
for large positive or negative whole numbers. SMALLINT
is used for small positive or negative whole numbers.
rooms SMALLINT
The column salary of the Staff table can be declared as:
salary DECIMAL(7,2)

5
Approximate numeric data & Datetime data
• The approximate numeric data type is used for defining
numbers that do not have an exact representation, such as
real numbers.
FLOAT [precision]
REAL
DOUBLE PRECISION
• The ISO standard subdivides the datetime data type into
YEAR, MONTH, DAY, HOUR, MINUTE, SECOND,
TIMEZONE_HOUR, and TIMEZONE_MINUTE.
DATE
TIME [timePrecision] [WITH TIME ZONE]
TIMESTAMP [timePrecision] [WITH TIME ZONE]
viewDate DATE

6
Scalar operators
• SQL provides a number of built-in scalar operators (+, −, *, / )
Operator Meaning
BIT_LENGTH Returns the length of a string in bits. For example,
BIT_LENGTH(X‘FFFF’) returns 16.
OCTET_LENGTH Returns the length of a string in octets (bit length divided by 8).
For example, OCTET_LENGTH(X‘FFFF’) returns 2.
CHAR_LENGTH Returns the length of a string in characters (or octets, if the string
is a bit string). For example, CHAR_LENGTH(‘Beech’) returns 5.
CAST Converts a value expression of one data type into a value in
another data type. For example, CAST(5.2E6 AS INTEGER)
|| Concatenates two character strings or bit strings. For example,
fName || lName.
CURRENT_USER Returns a character string representing the current authorization
or USER identifier (informally, the current user name).
SESSION_USER Returns a character string representing the SQL-session
authorization identifier.
7
Scalar operators
Operator Meaning
SYSTEM_USER Returns a character string representing the identifier of the user
who invoked the current module.
LOWER Converts upper-case letters to lower-case. For example,
LOWER(SELECT fName FROM Staff WHERE
staffNo = ‘SL21’) returns ‘john’
UPPER Converts lower-case letters to upper-case. For example,
UPPER(SELECT fName FROM Staff WHERE
staffNo = ‘SL21’) returns ‘JOHN’
TRIM Removes leading (LEADING), trailing (TRAILING), or both
leading and trailing (BOTH) characters from a string. For
example, TRIM(BOTH ‘*’ FROM ‘*** Hello World ***’)
returns ‘Hello World’
POSITION Returns the position of one string within another string.
For example, POSITION(‘ee’ IN ‘Beech’) returns 2.
SUBSTRING Returns a substring selected from within a string. For example,
SUBSTRING(‘Beech’ FROM 1 TO 3) returns the string ‘Bee’.
8
Scalar operators
Operator Meaning
CASE Returns one of a specified set of values, based on some
condition. For example,
CASE type
WHEN ‘House’ THEN 1
WHEN ‘Flat’ THEN 2
ELSE 0
END
CURRENT_DATE Returns the current date in the time zone that is local to the user.
CURRENT_TIME Returns the current time in the time zone that is the current
default for the session. For example, CURRENT_TIME(6)
gives time to microseconds precision.
CURRENT_TIMESTAMP Returns the current date and time in the time zone that is the
current default for the session. For example,
CURRENT_TIMESTAMP(0) gives time to seconds precision.
EXTRACT Returns the value of a specified field from a datetime or interval
value. For example, EXTRACT(YEAR FROM
Registration.dateJoined).
9
Creating a Database
CREATE DATABASE database_name
[ CONTAINMENT = { NONE | PARTIAL } ]
[ ON
[ PRIMARY ] <filespec> [ ,...n ]
[ , <filegroup> [ ,...n ] ]
[ LOG ON <filespec> [ ,...n ] ] ]
[ COLLATE collation_name ]
[ WITH <option> [,...n ] ]
[;]
– database_name: both the logical_file_name and the os_file_name
– CONTAINMENT = NONE is non-contained database. PARTIAL is partially
contained database
– LOG ON Specifies that the disk files used to store the database log, log files,
are explicitly defined
– COLLATE collation_name Specifies the default collation for the database
10
Domain Constraints
CHECK (searchCondition)
sex CHAR NOT NULL CHECK (sex IN (‘M’, ‘F’))
CREATE DOMAIN DomainName [AS] dataType
[DEFAULT defaultOption]
[CHECK (searchCondition)]
CREATE DOMAIN SexType AS CHAR
DEFAULT ‘M’
CHECK (VALUE IN (‘M’, ‘F’));
CREATE DOMAIN BranchNumber AS CHAR(4)
CHECK (VALUE IN (SELECT branchNo FROM Branch));
DROP DOMAIN DomainName [RESTRICT | CASCADE]

11
Creating a Table (CREATE TABLE)
• Having created the database structure, the table structures for the
base relations is located in the database. This is achieved using
the CREATE TABLE statement.

CREATE TABLE TableName


{(columName dataType [NOT NULL] [UNIQUE]
[DEFAULT defaultOption] [CHECK (searchCondition)] [, . . . ]}
[PRIMARY KEY (listOfColumns),]
{[UNIQUE (listOfColumns)] [, . . . ]}
{[FOREIGN KEY (listOfForeignKeyColumns)
REFERENCES ParentTableName [(listOfCandidateKeyColumns)]
[MATCH {PARTIAL | FULL}
[ON UPDATE referentialAction]
[ON DELETE referentialAction]] [, . . . ]}
{[CHECK (searchCondition)] [, . . . ]})
12
Creating a Table (CREATE TABLE)
• The CREATE TABLE statement creates a table called TableName
• The optional DEFAULT clause is specified to provide a default
value for a particular column
• The NOT NULL, UNIQUE, and CHECK clauses will be discussed.
• The PRIMARY KEY clause specifies the column or columns that
form the primary key for the table.
• The FOREIGN KEY clause specifies a foreign key in the (child)
table and the relationship it has to another (parent) table. This
clause implements referential integrity constraints.
– A listOfForeignKeyColumns, the columns from the table being created
that form the foreign key.
– A REFERENCES subclause, giving the parent table; the table holding
the matching candidate key. If the listOfCandidateKeyColumns is
omitted, the foreign key is assumed to match the primary key of the
parent table. In this case, the parent table must have a PRIMARY KEY
clause in its CREATE TABLE statement.
13
Creating a Table (CREATE TABLE)
• An optional (ON UPDATE) rule for the relationship that specifies the
action to be taken when a candidate key is updated in the parent table
that matches a foreign key in the child table. The referentialAction can
be CASCADE, SET NULL, SET DEFAULT, or NO ACTION. If the ON UPDATE
clause is omitted, the default NO ACTION is assumed.
• An optional (ON DELETE) rule for the relationship that specifies the
action to be taken when a row is deleted from the parent table that has
a candidate key that matches a foreign key in the child table. The
referentialAction is the same as for the ON UPDATE rule.
• By default, the referential constraint is satisfied if any component of the
foreign key is null or there is a matching row in the parent table. The
MATCH option provides additional constraints relating to nulls within
the foreign key. If MATCH FULL is specified, the foreign key components
must all be null or must all have values. If MATCH PARTIAL is specified,
the foreign key components must all be null, or there must be at least
one row in the parent table that could satisfy the constraint if the other
nulls were correctly substituted.
14
Example 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 BranchNumber AS CHAR(4)
CHECK (VALUE IN (SELECT branchNo FROM Branch));
CREATE DOMAIN PropertyNumber AS VARCHAR(5);
CREATE DOMAIN Street AS VARCHAR(25);
CREATE DOMAIN City AS VARCHAR(15);
CREATE DOMAIN PostCode AS VARCHAR(8);
CREATE DOMAIN PropertyType AS CHAR(1)
CHECK(VALUE IN (‘B’, ‘C’, ‘D’, ‘E’, ‘F’, ‘M’, ‘S’));
CREATE DOMAIN PropertyRooms AS SMALLINT;
CHECK(VALUE BETWEEN 1 AND 15);
CREATE DOMAIN PropertyRent AS DECIMAL(6,2)
CHECK(VALUE BETWEEN 0 AND 9999.99);
15
Example 1: CREATE TABLE
CREATE TABLE PropertyForRent(
propertyNo PropertyNumber NOT NULL,
street Street NOT NULL,
city City NOT NULL,
postcode PostCode,
type PropertyType NOT NULL DEFAULT ‘F’,
rooms PropertyRooms NOT NULL DEFAULT 4,
rent PropertyRent NOT NULL DEFAULT 600,
ownerNo OwnerNumber NOT NULL,
staffNo StaffNumber
CONSTRAINT StaffNotHandlingTooMuch
CHECK (NOT EXISTS (SELECT staffNo
FROM PropertyForRent
GROUP BY staffNo
HAVING COUNT(*) > 100)),
branchNo BranchNumber NOT NULL,
PRIMARY KEY (propertyNo),
FOREIGN KEY (staffNo) REFERENCES Staff ON DELETE SET NULL
ON UPDATE CASCADE,
FOREIGN KEY (ownerNo) REFERENCES PrivateOwner ON DELETE NO
ACTION ON UPDATE CASCADE,
FOREIGN KEY (branchNo) REFERENCES Branch ON DELETE NO
ACTION ON UPDATE CASCADE); 16
Changing a Table Definition (ALTER TABLE)
An ALTER TABLE statement for changing the structure of a
table once it has been created. The definition of the ALTER
TABLE statement in the ISO standard consists of six options
– 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.

17
Changing a Table Definition (ALTER TABLE)
ALTER TABLE TableName
[ADD [COLUMN] columnName dataType [NOT NULL] [UNIQUE]
[DEFAULT defaultOption] [CHECK (searchCondition)]]
[DROP [COLUMN] columnName [RESTRICT | CASCADE]]
[ADD [CONSTRAINT [ConstraintName]] tableConstraintDefinition]
[DROP CONSTRAINT ConstraintName [RESTRICT | CASCADE]]
[ALTER [COLUMN] SET DEFAULT defaultOption]
[ALTER [COLUMN] DROP DEFAULT]
The DROP COLUMN clause specifies the name of the column to be
dropped from the table definition, and has an optional qualifier that
specifies whether the DROP action is to cascade or not
– RESTRICT: The DROP operation is rejected if the column is referenced by
another database object. This is the default setting.
– CASCADE: The DROP operation proceeds and automatically drops the
column from any database objects it is referenced by. This operation
cascades, so that if a column is dropped from a referencing object, SQL
checks whether that column is referenced by any other object and drops it
from there if it is, and so on.
18
Example 2 ALTER TABLE
(a) Change the Staff table by removing the default of ‘Assistant’ for the
position column & setting the default for the sex column to female (‘F’)
ALTER TABLE Staff
ALTER position DROP DEFAULT;
ALTER TABLE Staff
ALTER sex SET DEFAULT ‘F’;

(b) Change the PropertyForRent table by removing the constraint that staff
are not allowed to handle more than 100 properties at a time. Change the
Client table by adding a new column representing the preferred number of
rooms.
ALTER TABLE PropertyForRent
DROP CONSTRAINT StaffNotHandlingTooMuch;
ALTER TABLE Client
ADD prefNoRooms PropertyRooms;
19
Removing a Table (DROP TABLE)
a redundant table from the database can be deleted using the
DROP TABLE statement.
DROP TABLE TableName [RESTRICT | CASCADE]
DROP TABLE PropertyForRent;
The DROP TABLE statement allows to specify whether the
DROP action is to be cascaded or not:
– RESTRICT: The DROP operation is rejected if there are any other
objects that depend for their existence upon the continued
existence of the table to be dropped.
– CASCADE: The DROP operation proceeds and SQL automatically
drops all dependent objects (and objects dependent on these
objects).

20
Views
View: The dynamic result of one or more relational operations
operating on the base relations to produce another
relation. A view is a virtual relation that does not
necessarily exist in the database but can be produced
upon request by a particular user, at the time of
request.
• To the database user, a view appears just like a real table,
with a set of named columns and rows of data. However,
unlike a base table, a view does not necessarily exist in the
database as a stored set of data values.

21
Creating a View (CREATE VIEW)
The format of the CREATE VIEW statement is:
CREATE VIEW ViewName [(newColumnName [, . . . ])]
AS subselect
• A view is defined by specifying an SQL SELECT statement. A name
may optionally be assigned to each column in the view. If a list of
column names is specified, it must have the same number of
items as the number of columns produced by the subselect.
– If the list of column names is omitted, each column in the view takes
the name of the corresponding column in the subselect statement.
– The list of column names must be specified if there is any ambiguity
in the name for a column. This may occur if the subselect includes
calculated columns, and the AS subclause has not been used to name
such columns, or it produces two columns with identical names as
the result of a join.
• The subselect is known as the defining query.
22
Example 3: Create a horizontal view
• A horizontal view restricts a user’s access to selected rows of
one or more tables.
CREATE VIEW Manager3Staff
AS SELECT *
FROM Staff
WHERE branchNo = ‘B003’;
Execute the statement:
SELECT * FROM Manager3Staff;

23
Example 4: Create a vertical view
• Create a view of the staff details at branch B003 that excludes salary
information, so that only managers can access the salary details for staff
who work at their branch.
• A vertical view restricts a user’s access to selected columns of 1 or more tables.
CREATE VIEW Staff3
AS SELECT staffNo, fName, lName, position, sex
FROM Staff
WHERE branchNo = ‘B003’;
Note: that we could rewrite this statement to use the Manager3Staff view instead
of the Staff table, thus:
CREATE VIEW Staff3
AS SELECT staffNo, fName, lName, position, sex
FROM Manager3Staff;

24
Example 5: Grouped and joined views
• Create a view of staff who manage properties for rent, which
includes the branch number they work at, their staff number,
and the number of properties they manage
CREATE VIEW StaffPropCnt (branchNo, staffNo, cnt)
AS SELECT s.branchNo, s.staffNo, COUNT(*)
FROM Staff s, PropertyForRent p
WHERE s.staffNo = p.staffNo
GROUP BY s.branchNo, s.staffNo;

25
Removing a View (DROP VIEW)
A view is removed from the database with the DROP VIEW
statement:
DROP VIEW ViewName [RESTRICT | CASCADE]
DROP VIEW causes the definition of the view to be deleted from
the database.
DROP VIEW Manager3Staff;

RESTRICT: Refuse to drop the view if any objects depend on it. This
is the default.

CASCADE: DROP VIEW deletes all related dependent objects (such


as other views).

26
View Updatability
Updatable view: For a view to be updatable, the DBMS must be able to
trace any row or column back to its row or column in the source table.
The views that must be updatable in a system that conforms to the
standard. The definition standard is that a view is updatable if and only if:
• DISTINCT is not specified; duplicate rows must not be eliminated from
the query results.
• Every element in the SELECT list of the defining query is a column name
(rather than a constant, expression, or aggregate function) and no
column name appears more than once.
• The FROM clause specifies only one table; that is, the view must have a
single source table for which the user has the required privileges.
– If the source table is itself a view, then that view must satisfy these
conditions. Therefore, excludes any views based on a join, union
(UNION), intersection (INTERSECT), or difference (EXCEPT).
• The WHERE clause does not include any nested SELECTs that reference
the table in the FROM clause.
• There is no GROUP BY or HAVING clause in the defining query.

27
Advantages and Disadvantages of Views
Advantages Disadvantages
Data independence Update restriction
Currency Structure restriction
Improved security Performance
Reduced complexity
Convenience
Customization
Data integrity

28
Advantages
• Currency: Changes to any of the base tables in the
defining query are immediately reflected in the view.
• Improved security: Each user can be given the privilege
to access the database only through a small set of views
that contain the data appropriate for that user, thus
restricting and controlling each user’s access to the
database.
• Reduced complexity: A view can simplify queries, by
drawing data from several tables into a single table,
thereby transforming multi-table queries into single-
table queries.

29
Advantages
• Convenience: Views can provide greater convenience to
users as users are presented with only that part of the
database that they need to see. This also reduces the
complexity from the user’s point of view.
• Customization: Views provide a method to customize
the appearance of the database, so that the same
underlying base tables can be seen by different users in
different ways.
• Data integrity: ensuring the integrity of the view.

30
Disadvantages
• Update restriction: In a view cannot be updated.
• Structure restriction: The structure of a view is
determined at the time of its creation. If the defining
query was of the form SELECT * FROM . . . , then the *
refers to the columns of the base table present when
the view is created. If columns are subsequently added
to the base table, then these columns will not appear in
the view, unless the view is dropped and recreated.
• Performance: There is a performance penalty to be paid
when using a view. In some cases, this will be negligible;
in other cases, it may be more problematic.

31
Stored Procedures
• Similar to procedures in programming languages
• Stored inside the database
• Can access database tables
• May contain SQL statements
• Additionally they support:
– LOOP
– IF-THEN-ELSE statement

32
Syntax
CREATE PROCEDURE Procedure_name
/*The variable parameter in/out */
{@parameter data_type input/output }
AS
BEGIN
[Declare variables for processing]
{Transact-SQL statements}
END

33
Commands
-- Declare variables
DECLARE @parameter_name data_type
-- Assigning values to variables
SET @parameter_name = value
SELECT @parameter_name = value
-- Show notice
print 'message‘
-- Run stored-proc nonparametric
EXECUTE procedure_name
--Stored-proc with parameters
EXEC procedure_name Para1_value, Para2_value, …

34
IF and WHILE
IF (condition)
BEGIN
{Transaction-SQL statements}
END
ELSE
BEGIN
{Transaction-SQL statements}
END

WHILE (condition)
BEGIN
{Transaction-SQL statements}
END

35
Example
--- Sum all even number from m to n
CREATE PROCEDURE SumEvenNo @m int, @n int
AS
BEGIN
Declare @sumno int,
Declare @i int
Set @sumno = 0
Set @i = @m
While (@i < @n)
BEGIN
IF (@i % 2 = 0)
SET @sumno = @sumno + @i
SET @i = @i + 1
END
Print @sumno
END

--- F5 ---

Exec SumEvenNo 1, 20
36
Example
CREATE PROCEDURE proCount
@userrent int,
@mycount int output
AS
BEGIN
SELECT @mycount = COUNT(*)
FROM PropertyForRent
WHERE rent > @userrent;
END

--- F5 ---
DECLARE @mycount int
EXEC proCount 350, @mycount out
print @mycount

37
Cursors
• A SELECT statement can be used if the query returns one and only
one row.
declare @vstreet varchar(20)
declare @vcity varchar(10)
declare productCursor cursor for
select street, city from PropertyForRent where rent>350
open productCursor
fetch next from productCursor into @vstreet, @vcity
while (@@FETCH_STATUS=0)
begin
print 'street='+cast(@vstreet as varchar(30))+'city='+@vcity
fetch next from productCursor into @vstreet, @vcity
end
close productCursor
deallocate productCursor

38
explanation
DECLARE statements - Declare variables used in the code block
SET\SELECT statements – assign/initialize the variables to a specific value
DECLARE CURSOR statement - Populate the cursor with values that will be
evaluated
NOTE - There are an equal number of variables in the DECLARE CURSOR FOR
statement as there are in the SELECT statement. This could be 1 or many variables
and associated columns.
OPEN statement - Open the cursor to begin data processing
FETCH NEXT statements - Assign the specific values from the cursor to the
variables
NOTE - This logic is used for the initial population before the WHILE statement and
then again during each loop in the process as a portion of the WHILE statement
WHILE statement - Condition to begin and continue data processing
BEGIN...END statement - Start and end of the code block
NOTE - Based on the data processing multiple BEGIN...END statements can be used
Data processing - In this example, display the value street and city
CLOSE statement - Releases the current data and associated locks, but permits the
cursor to be re-opened
DEALLOCATE statement - Destroys the cursor

39
Trigger
• Database Triggers refer to an active mechanism that
allows the programming of reaction to database events.
– Insertion, deletion, update
• A database trigger takes the general form:
– ``When something happens and if some condition is met
do something’’
• Triggers are code stored in the database and invoked
(triggered) by events that occur in the database.

40
Syntax
CREATE TRIGGER trigger_name ON table_name
FOR [insert, update, delete] [OF <column>[, column]*]
AS
BEGIN
{Declare variables for processing}
{Transact-SQL statements}
END

41
Example
CREATE TRIGGER rentvalue ON PropertyForRent
FOR insert, update
AS
if update(rent)
BEGIN
if exists (select * from inserted where rent < 300)
begin
raiserror ('error: rent must >= 300 ', 16, 1)
rollback
end
END

--run update--
UPDATE PropertyForRent
SET rent=150 WHERE propertyNo = 'PA15‘

--run insert--
INSERT INTO PropertyForRent
VALUES ('PA11','142 Jones st ', 'aberdeen', 'AB75T', 'flat',
6, 150, 'CO47', 'SA5', 'B009')
42
Transactions
A transaction model based on two SQL statements: “COMMIT and
ROLLBACK”. A transaction is a logical unit of work consisting of one
or more SQL statements that is guaranteed to be atomic with
respect to recovery. The standard specifies that an SQL transaction
automatically begins with a transaction-initiating SQL statement
executed (for example, SELECT, INSERT, UPDATE). Changes made by
a transaction are not visible to other concurrently executing
transactions until the transaction completes. A transaction can
complete in one of four ways:
• A COMMIT statement ends the transaction successfully, making
the database changes permanent.
• A ROLLBACK statement aborts the transaction, backing out any
changes made by the transaction.
• For programmatic SQL, successful program termination ends the
final transaction successfully, even if a COMMIT statement has
not been executed.
• For programmatic SQL, abnormal program termination aborts the
transaction.
43
Transactions
BEGIN { TRAN | TRANSACTION }
[ { transaction_name | @tran_name_variable }
[ WITH MARK [ 'description' ] ] ]
[ ; ]

44
Transactions
SQL transactions cannot be nested. The SET TRANSACTION
statement allows the user to configure certain aspects of the
transaction. The basic format of the statement is:
SET TRANSACTION
[READ ONLY | READ WRITE] |
[ISOLATION LEVEL READ UNCOMMITTED | READ COMMITTED |
REPEATABLE READ | SERIALIZABLE]
The READ ONLY and READ WRITE qualifiers indicate whether the
transaction is read only or involves both read and write operations. The
default is READ WRITE if neither qualifier is specified (unless the isolation
level is READ UNCOMMITTED). Perhaps confusingly, READ ONLY allows a
transaction to issue INSERT, UPDATE, and DELETE statements against
temporary tables (but only temporary tables).

45
Transactions
The isolation level indicates the degree of interaction that is
allowed from other transactions during the execution of the
transaction.
• Dirty read: A transaction reads data that has been written
by another as yet uncommitted transaction.
• Nonrepeatable: read A transaction rereads data it has
previously read but another committed transaction has
modified or deleted the data in the intervening period.
• Phantom read: A transaction executes a query that retrieves
a set of rows satisfying a certain search condition. When the
transaction re-executes the query at a later time additional
rows are returned that have been inserted by another
committed transaction in the intervening period.
The SERIALIZABLE isolation level is safe, that is generates
serializable schedules.
46
Violations of serializability permitted by isolation levels

Isolation level Dirty read Nonrepeatable read Phantom read


READ UNCOMMITTED Y Y Y
READ COMMITTED N Y Y
REPEATABLE READ N N Y
SERIALIZABLE N N N

47
Chapter Summary
• The ISO standard provides eight base data types: boolean, character, bit,
exact numeric, approximate numeric, datetime, interval, and character/
binary large objects.
• The SQL DDL statements allow database objects to be defined. The
CREATE and DROP DATABASE statements allow database to be created
and destroyed; the CREATE, ALTER, and DROP TABLE statements allow
tables to be created, modified, and destroyed.
• The CREATE and ALTER TABLE statements to define integrity constraints
that handle: required data, domain constraints, entity integrity,
referential integrity, and general constraints.
– Required data can be specified using NOT NULL.
– Domain constraints can be specified using the CHECK clause or by defining
domains using the CREATE DOMAIN statement.
– Primary keys should be defined using the PRIMARY KEY clause and alternate
keys using the combination of NOT NULL and UNIQUE.
– Foreign keys should be defined using the FOREIGN KEY clause and update and
delete rules using the subclauses ON UPDATE and ON DELETE.
– General constraints can be defined using the CHECK and UNIQUE clauses.
48
Chapter Summary
• A view is a virtual table representing a subset of columns and/or rows
and/or column expressions from one or more base tables or views. A
view is created using the CREATE VIEW statement by specifying a
defining query. It does not necessarily be a physically stored table, but
may be recreated each time it is referenced.
• Views can be used to simplify the structure of the database and make
queries easier to write. They can also be used to protect certain
columns and/or rows from unauthorized access. Not all views are
updatable.
• View resolution merges the query on a view with the definition of the
view producing a query on the underlying base table(s). This process is
performed each time the DBMS has to process a query on a view. An
alternative approach, called view materialization, stores the view as a
temporary table in the database when the view is first queried.
Thereafter, queries based on the materialized view can be much faster
than recomputing the view each time. One disadvantage with
materialized views is maintaining the currency of the temporary table.
49
Chapter Summary
• The COMMIT statement signals successful completion of a
transaction and all changes to the database are made
permanent. The ROLLBACK statement signals that the transaction
should be aborted and all changes to the database are undone.
• SQL access control is built around the concepts of authorization
identifiers, ownership, and privileges. Authorization identifiers
are assigned to database users by the DBA and identify a user.
Each object that is created in SQL has an owner. The owner can
pass privileges on to other users using the GRANT statement and
can revoke the privileges passed on using the REVOKE statement.
The privileges that can be passed on are USAGE, SELECT, DELETE,
INSERT, UPDATE, and REFERENCES; the latter three can be
restricted to specific columns. A user can allow a receiving user to
pass privileges on using the WITH GRANT OPTION clause and can
revoke this privilege using the GRANT OPTION FOR clause.
50
Thank you for your listen
End of lecture 05

51

You might also like