You are on page 1of 45

Data Definition

Week 6
National College of Ireland
Dublin, Ireland.

Lecturer: Dr. Muhammad Iqbal


Email: Muhammad.Iqbal@ncirl.ie 1
Outline
• Data types supported by SQL standard.

• Purpose of integrity enhancement feature of SQL.

• How to use the integrity enhancement feature in the CREATE and


ALTER TABLE statements.

• How to create and delete views using SQL.


• How the DBMS performs operations on views.
• Advantages and Disadvantages of views.
• How the International Organization for Standardization (ISO)
transaction model works.
• How to use the GRANT and REVOKE statements as a level of
security. 2
ISO SQL Data Types

SQL identifiers are used to identify objects in the database, such as


table names, view names, and columns.

• The ISO standard provides a default character set, which consists


of the upper-case letters A . . . Z, the lower-case letters a . . . z, the
digits 0 . . . 9, and some special characters (_, $, ..).

• The following restrictions are imposed on an identifier:

• 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. 3


ISO SQL Data Types

Boolean Data
Boolean data consists of the distinct truth values TRUE and FALSE. Unless
prohibited by a NOT NULL constraint, boolean data also supports the
UNKNOWN truth value as the NULL value.
SELECT true, false;

Character Data
Character data consists of a sequence of characters from an implementation-
defined character set, it is defined by the vendor of the particular SQL dialect.

For example: the branch number column Bno of the Branch table, which has
a fixed length of four characters, is declared as: Bno VARCHAR(4)
The column address of the PrivateOwner table, which has a variable number of
characters up to a maximum of 40, is declared as: address VARCHAR(40) 4
ISO SQL Data Types

Bit Data
The bit data type is used to define bit strings or a sequence of
binary digits (bits), each having either the value 0 or 1.
The format for specifying the bit data type is
BIT [VARYING] [length]
For example, to hold the fixed length binary string '0011', we declare a column
bitString, as:
bitString BIT(4) Precision is the number of
digits in a number. Scale is the
number of digits to the right of
the decimal point in a number.
Exact Numeric Data
The number consists of digits, an optional decimal point, and an optional
sign. An exact numeric data type consists of a precision and a scale. For
example, the exact numeric value −12.345 has precision 5 and scale 3.
5
ISO SQL Data Types

All these functions along


with examples are available
on the website address
mentioned below as

• http://dev.mysql.com/doc/ref
man/5.7/en/string-
functions.html

• https://www.w3schools.com/s
ql/func_mysql_trim.asp

6
Integrity Enhancement Feature

• Integrity control consists of constraints that we wish to


impose in order to protect the database from becoming
inconsistent.
• Consider five types of integrity constraints:
1. Required Data
2. Domain Constraints
3. Entity Integrity
4. Referential Integrity
5. General Constraints 7
Integrity Enhancement Feature

1. Required Data
• Some columns must contain a valid value; they are not allowed to
contain nulls.
• For example, every member of staff must have an associated job
position (for example, Manager, Assistant, and so on).
• The ISO standard provides the NOT NULL column specifier in the
CREATE and ALTER TABLE statements to provide this type of
constraint.
• For example, to specify that the column position of the Staff table
cannot be null, we define the column as:
position VARCHAR(10) NOT NULL 8
Integrity Enhancement Feature

2. Domain Constraints
Every column has a domain, in other words a set of legal values.

• For example, the sex of a member of staff is either 'M' or 'F', so the
domain of the column sex of the Staff table is a single character string
consisting of either 'M' or 'F'.

• The ISO standard provides two mechanisms for specifying domains in


the CREATE and ALTER TABLE statements.

• The first is the CHECK clause, which allows a constraint to be defined


on a column or the entire table.
9
CREATE DOMAIN Gender AS CHAR(1) CHECK(VALUE IN ('M', 'F'));
Integrity Enhancement Feature (IEF)
Entity Integrity
• Primary key of a table must contain a unique, non-null value
for each row.

• ISO standard supports FOREIGN KEY clause in CREATE


and ALTER TABLE statements:

PRIMARY KEY(Sno)

PRIMARY KEY(RNo, Pno)

• Can only have one PRIMARY KEY clause per table. Can still
ensure uniqueness for alternate keys using UNIQUE:

UNIQUE(telNo) 10
IEF - Referential Integrity
• FK is column or set of columns that links each row in the child table containing
foreign FK to row of parent table containing matching PK.

• Referential integrity means that, if FK contains a value, that value must refer to
existing row in parent table.

• ISO standard supports definition of FKs with FOREIGN KEY clause in


CREATE and ALTER TABLE: FOREIGN KEY(Bno) REFERENCES Branch

• Any INSERT/ UPDATE attempting to create FK value in the child table


without matching PK value in the parent is rejected.

• Action taken attempting to update/delete a PK value in the parent table with


matching rows in child is dependent on referential action specified using ON
UPDATE and ON DELETE subclauses:
– CASCADE - SET NULL
11
– SET DEFAULT - NO ACTION
IEF - Referential Integrity

CASCADE: Delete row from parent and delete matching


rows in child, and so on in the cascading manner.

SET NULL: Delete row from parent and set FK column(s)


in child to NULL. Only valid if FK columns are NOT NULL.

SET DEFAULT: Delete row from parent and set each


component of FK in the child to specify as default. Only
valid if DEFAULT specified for FK columns.

NO ACTION: Reject delete from parent. Default.


12
Entity and Referential Integrity

PK PK
PK

FK

PK

PK
FK

13
IEF - Referential Integrity
• For example, in the Property_For_Rent table, the staff number Sno is a
foreign key referencing the Staff table.

• In deletion rule, if a staff record is deleted from the Staff table, the
values of the corresponding Sno column in the Property_For_Rent table
are set to NULL:

FOREIGN KEY (Sno) REFERENCES Staff ON DELETE SET NULL

• The owner number Ono in the Property_For_Rent table is a foreign key


referencing the Owner table. If an owner number is updated in the
Owner table, the corresponding column(s) in the Property_For_Rent
table are set to the new value:
FOREIGN KEY (Ono) REFERENCES Owner ON UPDATE CASCADE
14
Data Definition
• SQL DDL allows database objects such as schemas, domains, tables,
views, and indexes to be created and destroyed.
• Main SQL DDL statements are:
• CREATE SCHEMA/ DATABASE
• DROP SCHEMA / DATABASE
CREATE/ALTER TABLE DROP TABLE
CREATE/ ALTER VIEW DROP VIEW

• Many DBMSs also provide:


CREATE INDEX DROP INDEX

• Relations and other database objects exist in an environment.


• Each environment contains one or more catalogs, and each catalog consists of
set of schemas.
15
• Schema is a named collection of related database objects.
CREATE TABLE
CREATE TABLE TableName
{(colName dataType [NOT NULL] [UNIQUE]
[DEFAULT defaultOption]
[CHECK searchCondition] [,...]}
[PRIMARY KEY (listOfColumns),]
{[UNIQUE (listOfColumns),] […,]}
{[FOREIGN KEY (listOfFKColumns)
REFERENCES ParentTableName [(listOfCKColumns)],
[ON UPDATE referentialAction]
[ON DELETE referentialAction ]] [,…]}
{[CHECK (searchCondition)] [,…] }) 16
CREATE TABLE (Example)

CREATE TABLE Property_For_Rent11 (


Pno VARCHAR(8) NOT NULL,
rooms Integer NOT NULL DEFAULT 4,
rent Integer NOT NULL DEFAULT 600,
Ono VARCHAR(8) NOT NULL,
Sno VARCHAR(4),
Bno VARCHAR(8) NOT NULL,
PRIMARY KEY (Pno),
FOREIGN KEY (Sno) REFERENCES Staff (sno)
ON DELETE SET NULL/ON UPDATE CASCADE);
• With CASCADE, SQL drops all dependent objects (and
objects dependent on these objects) 17
RENAME TABLE

RENAME TABLE
tbl_name TO new_table_name [, tbl_name2 TO new_table_name2, ...]

Example:
Assuming a table called old_table exists!

CREATE TABLE new_table (...);

RENAME TABLE old_table TO backup_table,

new_table TO old_table;

RENAME TABLE old_table TO new_table;


18
ALTER TABLE

1. Add a new column to a table. 4. Drop a table constraint.

2. Drop a column from a table. 5. Set a default for a column.

3. Add a new table constraint. 6. Drop a default for a column.

Change Staff table by removing default of 'Assistant' for


position column and setting default for sex column to female
('F').
ALTER TABLE Staff
ALTER position DROP DEFAULT;
ALTER TABLE Staff
ALTER sex SET DEFAULT 'F'; 19
DROP TABLE

DROP TABLE TableName [RESTRICT | CASCADE]

For example, DROP TABLE Property_For_Rent;

SET FOREIGN_KEY_CHECKS = 0;

drop table if exists customers;

20
Views

• Dynamic result of one or more relational operations


operating on base relations to produce another relation.

• Virtual relation that does not necessarily actually exist


in the database but is produced upon request, at time of
request.

• Contents of a view are defined as a query on one or


more base relations.

• Any operations on view are automatically translated


into operations on relations from which it is derived. 21
SQL - CREATE VIEW

CREATE VIEW ViewName [ (newColumnName [,...]) ]


AS subselect
[WITH [CASCADED | LOCAL] CHECK OPTION]

• Can assign a name to each column in view.


• If list of column names is specified, it must have same
number of items as number of columns produced by
subselect.
• If omitted, each column takes name of corresponding
column in subselect.
22
Create Horizontal View
Create view so that manager at branch B3 can only see details for
staff who work in his or her office.
CREATE VIEW Manager3Staff
AS SELECT *
FROM Staff
WHERE Bno = 'B3';

Create view of staff details at branch B3 excluding salaries.


CREATE VIEW Staff3
AS SELECT Sno, fName, lName, position, sex
FROM Staff
WHERE Bno = 'B3'; 23
Grouped and Joined Views
Create view of staff who manage properties for rent,
including branch number they work at, staff number,
and number of properties they manage.
CREATE VIEW StaffPropCnt (Bno, Sno, cnt)
AS SELECT s.Bno, s.Sno, COUNT(*)
FROM Staff s, Property_For_Rent p
WHERE s.Sno = p.Sno
GROUP BY s.Bno, s.Sno;

24
SQL - DROP VIEW

DROP VIEW ViewName [RESTRICT |


CASCADE]

• Causes definition of view to be deleted from


database.

• For example: we could remove


Manager3Staff view using the statement:
DROP VIEW Manager3Staff;
25
View Resolution
a) View column names in SELECT list are translated into their corresponding
column names in the defining query:
SELECT s.Sno As Sno, COUNT(*) As cnt
b) View names in FROM are replaced with corresponding FROM lists of
defining query:
FROM Staff s, Property_For_Rent p
c) WHERE from user query is combined with WHERE of defining query using
AND:
WHERE s.Sno = p.Sno AND Bno = 'B3'
d) GROUP BY and HAVING clauses copied from defining query:
GROUP BY s.Bno, s.Sno
e) ORDER BY copied from query with view column name translated into
defining query column name ORDER BY s.Sno 26
Restrictions on Views

SQL imposes several restrictions on creation and


use of views.
(a) If the column in view is based on an
aggregate function:
– Column may appear only in SELECT and
ORDER BY clauses of queries that accesses
view.
– Column may not be used in WHERE nor be an
argument to an aggregate function in any query
based on view.
27
Restrictions on Views

• For example,
SELECT COUNT(cnt)
FROM StaffPropCnt;

• Similarly,
SELECT *
FROM StaffPropCnt
WHERE cnt >= 2;

(b) Grouped view may never be joined with a base table or a


view.
• For example, StaffPropCnt view is a grouped view, so any
attempt to join this view with another table or view fails.
28
View Updatability
• All updates to the base table reflected in all views that encompass
base table.
• Similarly, may expect that if the view is updated, then the base
table(s) will reflect change.
• Consider again view StaffPropCnt.
• If we tried to insert record showing that at branch 'B3', 'SG5' manages
2 properties:
INSERT INTO StaffPropCnt
VALUES ('B3', 'SG5', 2);
• Have to insert 2 records into Property_For_Rent showing which
properties SG5 manages. However, do not know which properties they
are; i.e. do not know primary keys! 29
View Updatability

• If change definition of view and replace count with actual


property numbers:
CREATE VIEW StaffPropList (Bno, Sno, Pno)
AS SELECT s.Bno, s.Sno, p.Pno
FROM Staff s, Property_For_Rent p
WHERE s.Sno = p.Sno;
• Now try to insert the record:
INSERT INTO StaffPropList
VALUES ('B3', 'SG5', 'PG19');
• Still problem, because in Property_For_Rent all columns except
postcode/Sno are not allowed nulls.
• However, have no way of giving remaining non-null columns values.30
Advantages and Disadvantages of Views

Advantages Disadvantages
• Data independence • Update restriction
• Currency • Structure restriction
• Improved security • Performance
• Reduced complexity
• Convenience
• Customization
• Data integrity 31
Transactions
• SQL defines transaction model based on COMMIT and ROLLBACK.

• Transaction is logical unit of work with one or more SQL statements


guaranteed to be atomic with respect to recovery.

• An SQL transaction automatically begins with a transaction-initiating


SQL statement (e.g., SELECT, INSERT).
• Use dreamhome;
• Start transaction;
• select * from branch;
• # Update the one record of the branch table
• Update branch set Street = '25 James St' where Bno = 'B7';
• If you use the command "commit;", then you cannot rollback the updated record.
• If you use "rollback" command, then the previous record will be restored.
• The command "commit" terminates the session of transactions. 32
Transactions
• Transaction can complete in one of four ways:
‒ COMMIT ends transaction successfully, making changes
permanent.

‒ ROLLBACK aborts transaction, backing out any changes


made by transaction.

‒ For programmatic SQL, successful program termination


ends final transaction successfully, even if COMMIT has
not been executed.

‒ For programmatic SQL, abnormal program end aborts


transaction. 33
Transactions

• New transaction starts with next transaction-initiating


statement.
• SQL transactions cannot be nested.
• SET TRANSACTION configures transaction:
SET TRANSACTION

[READ ONLY | READ WRITE] |

[ISOLATION LEVEL READ UNCOMMITTED |

READ COMMITTED |

REPEATABLE READ | SERIALIZABLE ] 34


Access Control - Authorization
Identifiers and Ownership
• Authorization identifier is normal SQL identifier used to
establish identity of a user. Usually has an associated
password.

• Used to determine which objects user may reference and


what operations may be performed on those objects.

• Each object created in SQL has an owner, as defined in


AUTHORIZATION clause of schema to which object
belongs.

• Owner is only person who may know about it. 35


Privileges
• User actions permitted to carry out on given base table or view:
SELECT Retrieve data from a table.
INSERT Insert new rows into a table.
UPDATE Modify rows of data in a table.
DELETE Delete rows of data from a table.
REFERENCES Reference columns of named table in the
integrity constraints.
USAGE Use domains, collations, character sets,
36
and translations.
Privileges

• Can restrict INSERT/UPDATE/REFERENCES


to named columns.

• Owner of table must grant other users the


necessary privileges using GRANT statement.

• To create view, the user must have SELECT


privilege on all tables that make up view and
REFERENCES privilege on the named
columns. 37
GRANT

GRANT {PrivilegeList | ALL PRIVILEGES}

ON ObjectName

TO {AuthorizationIdList | PUBLIC}

[WITH GRANT OPTION]

• PrivilegeList consists of one or more of above


privileges separated by commas.

• ALL PRIVILEGES grants all privileges to a user.


38
GRANT

• PUBLIC allows access to be granted to all


present and future authorized users.

• ObjectName can be a base table, view, domain,


character set, collation or translation.

• WITH GRANT OPTION allows privileges to


be passed on.
SHOW GRANTS FOR 'root'@'localhost';
39
http://dev.mysql.com/doc/refman/5.7/en/charset-examples.html
GRANT
Give Manager full privileges to Staff table. create user
'Manager'@'localhost'
GRANT all PRIVILEGES on *.* identified by ‘password';
to 'Manager'@'localhost' with grant option;
Give users Personnel and Director SELECT and UPDATE on
column salary of Staff.
GRANT SELECT, update(salary)
ON Staff to
'Personnel'@'localhost' with grant option;

Give all users SELECT on Branch table.


GRANT SELECT
ON Branch
TO PUBLIC/ ROOT; 40
REVOKE

• REVOKE takes away privileges granted with


GRANT.
REVOKE [GRANT OPTION FOR]
{PrivilegeList | ALL PRIVILEGES}
ON ObjectName
FROM {AuthorizationIdList | PUBLIC}
[RESTRICT | CASCADE]
• ALL PRIVILEGES refer to all privileges granted
to a user by user revoking privileges. 41
REVOKE

• GRANT OPTION FOR allows privileges passed on


via WITH GRANT OPTION of GRANT to be
revoked separately from the privileges themselves.

• REVOKE fails if it results in an abandoned object,


such as a view, unless the CASCADE keyword has
been specified.

• Privileges granted to this user by other users are not


42
affected.
REVOKE

43
REVOKE Specific Privileges
Revoke privilege SELECT on Branch table from all users.
REVOKE SELECT
ON Branch
FROM PUBLIC;

Revoke all privileges given to Director on Staff table.


REVOKE ALL PRIVILEGES ON Staff
FROM 'Director'@'localhost';

Stored Procedure:
A program that performs one or more actions and is called as an executable
PL/SQL statement. You can pass information into and out of a procedure through
44
its parameter list.
Module Resources
Recommended Book Resources Dr. Muhammad M Iqbal*
• Thomas Connolly, Carolyn Begg 2014, Database Systems: A Practical Approach
to Design, Implementation, and Management, 6th Edition Ed., Pearson
Education [ISBN: 1292061189] [Present in our Library]
Supplementary Book Resources
• Gordon S. Linoff, Data Analysis Using SQL and Excel, Wiley [ISBN:
0470099518]
• Eric Redmond, Jim Wilson, Seven Databases in Seven Weeks, Pragmatic
Bookshelf [ISBN: 1934356921]
• Baron Schwartz, Peter Zaitsev, Vadim Tkachenko, High Performance MySQL,
O'Reilly Media [ISBN: 1449314287]
Other Resources
• Website: http://www.thearling.com
• Website: http://www.mongodb.org
45
• Website: http://www.mysql.com

You might also like