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

Chapter 4 LAU

This document discusses SQL data definition language (DDL) which allows defining database schema elements like tables, columns, data types, and constraints. It covers SQL identifiers, common data types like numbers, characters, dates, and their properties. Scalar operators for handling data types are also introduced.

Uploaded by

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

Chapter 4 LAU

This document discusses SQL data definition language (DDL) which allows defining database schema elements like tables, columns, data types, and constraints. It covers SQL identifiers, common data types like numbers, characters, dates, and their properties. Scalar operators for handling data types are also introduced.

Uploaded by

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

School of Engineering

Lebanese American University Department of Electrical &


Chartered in the State of New York Computer Engineering
www.lau.edu.lb www.lau.edu.lb/ece

Database Systems
COE 418

Chapter 6 - SQL: Data Definition

Joe M. Tekli, Ph.D.


Computer Software Engineering
Database Systems

Ch. 6 – SQL: Data Definition Engineering

1. Introduction

• SQL was defined as a standard by ANSI1 in 1986, adopted by ISO2 in 1987


• Non-procedural English-like relational DB language
• Including both data manipulation and data definition features

• Data Manipulation Language (DML) covered in Ch. 5


– Provides basic data manipulation operations on data held in the database
 Allowing data insertion, selection, modification, and deletion

• Data Definition Language (DDL)


– Allows the DBA or user to describe relations (tables), attributes, data-types,
and views required to represent the data
– Allows defining associated integrity and security constraints
Covered in this chapter…
Database Systems

Ch. 6 – SQL: Data Definition Engineering

Chapter Contents

1. Introduction
2. Identifiers and Data-Types
3. Constraints
4. Data Definition
5. Views
6. Access Control

11/29/2020 J. TEKLI – [email protected] 3


Database Systems

Ch. 6 – SQL: Data Definition Engineering

2. Identifiers and Data-Types


2.1. Identifies

• SQL identifiers are used to identify the components of a database


– E.g.: DB name, table (relation) names, column (attribute) names, view names, etc.

• Default ISO character set for defining SQL identifiers:


– Upper case characters: A, …, Z
– Lower case characters: a, …, z
– Digits: 0, …, 9
– The underscore character: _

• NOTE:
• An identifier can be no longer than 128 characters
• An identifier must start with a letter
4
Database Systems

Ch. 6 – SQL: Data Definition Engineering

2. Identifiers and Data-Types


2.2. Scalar Data-Types

• Most common SQL scalar data types:


• Boolean
• Character
• Numeric
• DateTime

• SQL allows object types


• Allowing to store large binary objects
• Such as images, videos, animations, and other multimedia objects…

Disregarded in the remainder of this chapter!

11/29/2020 J. TEKLI – [email protected] 5


Database Systems

Ch. 6 – SQL: Data Definition Engineering

2. Identifiers and Data-Types


2.2. Scalar Data-Types

• Boolean
• Consists of truth values: TRUE and FALSE, as well as an UNKOWN value
• Boolean data-type values can be processed using Boolean operators:
• AND, OR, and NOT
 Operations involving UNKOWN and/or NULL values return an UNKOWN value

• Example: Declaring an attribute named “answer” of type Boolean


answer BOOLEAN

11/29/2020 J. TEKLI – [email protected] 6


Database Systems

Ch. 6 – SQL: Data Definition Engineering

2. Identifiers and Data-Types


2.2. Scalar Data-Types

• Character data
• Sequence of characters from a DBMS-defined character set
 Most DBMSs adopt the ASCII character set (and more recently Unicode)

• Example: Declaring an attribute named “productID” of type: sequence of characters


productID CHAR(5)

 Each productID value is made of a sequence of 5 characters


- The default length (in number of characters when not provided ) is 1
Example: gender CHAR /* Potential values are: ‘M’ or ‘F’
so we only need one character */

11/29/2020 J. TEKLI – [email protected] 7


Database Systems

Ch. 6 – SQL: Data Definition Engineering

2. Identifiers and Data-Types


2.2. Scalar Data-Types

• Character data
• SQL allows two kinds of character data types
• CHAR: Allows to define fixed length strings of characters
 If we enter a value which does not correspond to the specified length
- Strings are padded with blanks on the right to make up the size
• Example: productID CHAR(5)
 Sample values: “P1050”, “P2000”, “p10 ”, “p2 ”, etc.

• VARCHAR: Allows to define variable length strings of characters


- Up to a maximum size
• Example: label VARCHAR(10)
 Sample values: “Keyboard”, “Screen”, “Scanner“, etc.
Database Systems

Ch. 6 – SQL: Data Definition Engineering

2. Identifiers and Data-Types


2.2. Scalar Data-Types

• Numeric data
• SQL allows integer and decimal numeric data-types
• Integer types allow to define whole numbers
Value Domain Memory size
Data-type Description
(Min & Max) (in Bytes)
TINYINT Very small integer -27 (= -128) 27-1 (=127) 1 (8 bits)
SMALLINT Small integer -215 (=- 32768) 215-1 (= 32767) 2 (16 bits)
INT Standard integer - 231 231 -1 4 (32 bits)
BIGINT Big integer - 263 263 -1 8 (64 bits)

Example: clientID INT

11/29/2020 J. TEKLI – [email protected] 9


Database Systems

Ch. 6 – SQL: Data Definition Engineering

2. Identifiers and Data-Types


2.2. Scalar Data-Types

• Numeric data
• SQL allows integer and decimal numeric data-types
• In contrast with integers, SQL allows one main decimal type: DECIMAL
– Allows to define numbers with the decimal point
– While specifying the maximum number of allowed digits

Example: price DECIMAL(5, 2) /* price  [-999.99, 999.99] */

Precision: Total number Scale: Number of decimal digits


of decimal digits allowed after the decimal point

- clientID DECIMAL (4) is equivalent to clientID DECIMAL(4, 0)


- NOTE: Some DBMSs use reserved word NUMERIC instead of DECIMAL (or allow both)
Database Systems

Ch. 6 – SQL: Data Definition Engineering

2. Identifiers and Data-Types


2.2. Scalar Data-Types

• Date-time data
• Allows representing date-time data such as year, month, day, hour, etc.
• SQL supports three main date-time data types:
• DATE: used to store calendar dates using the ‘YYYY-MM-DD’ format
– The supported range is '1000-01-01' to '9999-12-31‘

• TIME: used to store time using the ‘HH:MM:SS’ format


– The supported range is ’00:00:00’ to ’23:59:59’

• DATETIME: stores date & time using the ‘YYY-MM-DD HH:MM:SS’ format
– The supported range is ’ '1000-01-01 00:00:00’ to ’ 9999-12-31 23:59:59’

11/29/2020 J. TEKLI – [email protected] 11


Database Systems

Ch. 6 – SQL: Data Definition Engineering

2. Identifiers and Data-Types


2.3. Scalar Operators

• SQL provides a number of built in operators to handle scalar types


 Used to build scalar expressions that evaluate to a scalar value

• SQL number manipulation operators/functions:


• Arithmetic operators: + (addition), - (subtraction), * (multiplication)
/ (division), and % (remainder)

• ROUND(): Rounds a numeric field to the number of decimals specified


– Example: ROUND(15.3453, 2) returns 15.35

• FORMAT(): Converts a number to a string format which is rounded up to the


number of decimal places specified, and returns the result as a string
– Example: FORMAT(15.34, 4) returns “15.3400”

11/29/2020 J. TEKLI – [email protected] 12


Database Systems

Ch. 6 – SQL: Data Definition Engineering

2. Identifiers and Data-Types


2.3. Scalar Operators

• SQL allows character manipulation functions:


– LOWER(): Converts a string into lower case
• Example: LOWER(“JOE”) returns “joe”

– UPPER(): Converts a string into upper case


– Example: UPPER(“Joe”) returns “JOE”

– POSITION(): Returns the position of a string within another


• Example: POSITION(“nn” IN “Scanner”) returns 4
– NOTE: character strings in SQL are indexed from 1 to length of string
– SUBSTRING(): Returns a substring from within a string
• Example: SUBSTRING(“Scanner”, 1, 3) returns “Sca”

11/29/2020 J. TEKLI – [email protected] 13


Database Systems

Ch. 6 – SQL: Data Definition Engineering

2. Identifiers and Data-Types


2.3. Scalar Operators

• SQL allows character manipulation functions:


– LPAD(): Returns a string, left padded with a parameter string, to a certain length
– Example: LPAD(“John”, 7, “*”) returns “***John”
LPAD(“John”, 3, “*”) returns “Joh”

– RPAD(): Returns a string, right padded with a parameter string, to a certain length
– Example: RPAD(“John”, 7, “*”) returns “John***”

– CONCAT(): Returns the concatenation of strings provided as arguments


• Example: CONCAT(“**”, “John”, “***”) returns “**John***”

– TRIM(): Removes LEADING, TRAILING, or BOTH leading and trailing characters


• Example: TRIM(LEADING “*” FROM “***James**”) returns “James**”
TRIM(BOTH “*” FROM “***James**”) returns “James”
Database Systems

Ch. 6 – SQL: Data Definition Engineering

2. Identifiers and Data-Types


2.3. Scalar Operators

• SQL allows date manipulation functions:


– CURRENT_DATE(): Returns the system current date in “YYYY-MM-DD” format

– CURRENT_TIME(): Returns the system’s current time in “HH:MM:SS” format

– EXTRACT(): Returns the value of a specified field from a date-time data-type


• Example: EXTRACT(YEAR FROM CURRENT_DATE()) returns the current year

– YEAR(): Returns the hour of a time data value


• Example: YEAR(‘2014-06-04’) returns 2014

– HOUR(): Returns the hour of a time data value


• Example: HOUR(‘11:00:00’) returns 11

– Likewise for MONTH(), DAY(), MINUTE(), and SECOND()…


Database Systems

Ch. 6 – SQL: Data Definition Engineering

3. Constraints

• SQL provides many facilities for data control which we group in four main
categories:
• Data occurrence constraints: designating whether data occurrence is
optional or mandatory for a given attribute value
• Domain constraints: restrictions on attribute values based on domain
definitions
• Integrity constraints: rules that have to apply on all instances of the data to
preserve data coherence in the DB
• General constraints: rules specified by the DBA/user regarding special
requirements

11/29/2020 J. TEKLI – [email protected] 16


Database Systems

Ch. 6 – SQL: Data Definition Engineering

3. Constraints
3.1. Data Occurrence Constraints

• Data occurrence constraints: designate whether data occurrence is optional or


mandatory for a given attribute value
• Some attributes (columns) must contain values, and thus cannot contain NULLs
• Other attributes (columns) can contain NULLs
– NOTE: NULL is different from the empty character string

• SQL provides NOT NULL as a data occurrence attribute (column) specifier


• To be used when creating or modifying the structure of a table
– Example: productID VARCHAR(5) NOT NULL

– NOT NULL can be omitted when defining an attribute


 Allowing NULL values for the designate attribute

11/29/2020 J. TEKLI – [email protected] 17


Database Systems

Ch. 6 – SQL: Data Definition Engineering

3. Constraints
3.2. Domain Constraints

• Following the relational data model:


• Every attribute (column) in a relation (table) has a domain of values
– For instance: The gender of an employee can be either ‘M’ for male, or ‘F’ for female
A productID can vary between “p001” and “p999”
The age of a person can vary between 0 and 140 years

• A domain of values consists of:


• A data-type, as well as
• A set of allowed values for the designated data-type

• A domain of values is defined by:


• Declaring the corresponding attribute data-type as described in the previous section
• Defining the set of allowed values using special CHECK and CREATE DOMAIN clauses

11/29/2020 J. TEKLI – [email protected] 18


Database Systems

Ch. 6 – SQL: Data Definition Engineering

3. Constraints
3.2. Domain Constraints

• The CHECK clause: allows a domain constraint to be defined on an attribute (column)


• Formal syntax: attributeName datatype CHECK (VALUE IN setOfValues)
– Example: gender CHAR CHECK(VALUE IN (‘M’, ‘F’))

• SQL allows a domain to be defined more explicitly using CREATE DOMAIN:


• Formal syntax: CREATE DOMAIN domainName AS dataType
DEFAULT defaultValue /* Optional */
CHECK (VALUE IN allowedValues) /* Optional */

– Example: CREATE DOMAIN genderType AS CHAR


DEFAULT ‘M’
CHECK (VALUE IN (‘M’, ‘F’))
Consequently, we defined the domain of attribute gender: gender genderType

11/29/2020 J. TEKLI – [email protected] 19


Database Systems

Ch. 6 – SQL: Data Definition Engineering

3. Constraints
3.2. Domain Constraints

• The set of allowed values in the CREATE DOMAIN clause can invoke a table look-up
• For instance, we can create a domain cityName to make sure that values correspond
to existing city names defined in an existing table (relation) CITY:

– Example: CREATE DOMAIN cityName AS VARCHAR(20)


DEFAULT “Byblos”
CHECK (VALUE IN (SELECT name FROM CITY))

Consequently, we can define the domain of an attribute city:


city cityName

11/29/2020 J. TEKLI – [email protected] 20


Database Systems

Ch. 6 – SQL: Data Definition Engineering

3. Constraints
3.2. Domain Constraints

• Domains can be removed from the database using the DROP clause:
• Formal syntax: DROP DOMAIN domainName

• We can also associate RESTRICT or CASCADE clauses with the DROP clause
• Specifying the action to be taken when the domain to be dropped is currently used
– Formal syntax: DROP DOMAIN domainName RESTRICT
DROP DOMAIN domainName CASCADE

• When RESTRICT is used: the drop will fail if the domain is being used
• Default behavior when RESTRICT is not mentioned
• When CASCADE is used: any attribute based on the domain being dropped is
automatically changed to the use the domain’s underlying data-type

11/29/2020 J. TEKLI – [email protected] 21


Database Systems

Ch. 6 – SQL: Data Definition Engineering

3. Constraints
3.3. Integrity Constraints

• Integrity constraints: restriction rules defined on data values which can be stored
in the tables (relations) of a relational DB, and which have to be satisfied by all
tables (relations) in the DB
• Objective: To guaranty the accuracy and coherence of the data in the DB

• There exist multiple forms of integrity constraints, among which three essential
rules in relational DB:
i. Key uniqueness constraint
ii. Entity integrity constraint
iii. Referential integrity constraint

11/29/2020 J. TEKLI – [email protected] 22


Database Systems

Ch. 6 – SQL: Data Definition Engineering

3. Constraints
3.3. Integrity Constraints

• Key uniqueness constraint:


• A primary (candidate) key cannot have the same value for two or many distinct tuples
in the same relation (table)

• Entity integrity constraint:


• No attribute of a primary (candidate) key can have a null value, and should necessarily
have a certain value for each tuple in the relation (table)

• Referential integrity constraint:


• The values of a foreign key in a relation (table) depend on the values of the corresponding
primary key in the relation (table) of origin
• The foreign key value must either match a primary key value of some tuple in the
relation (table) of origin, or it can be null

11/29/2020 J. TEKLI – [email protected] 23


Database Systems

Ch. 6 – SQL: Data Definition Engineering

3. Constraints
3.3. Integrity Constraints

• SQL enforces both key uniqueness and entity integrity constraints


• Using the PRIMARY KEY clause specified per table (relation)

• Example: PRIMARY KEY (productID) /* in table PRODUCT */


PRIMARY KEY (supplierID, productID) /* in table DELIVERY */

• SQL allows a UNIQUE clause to enforce key uniqueness for alternative keys
• Attributes appearing in UNIQUE should be declared as NOT NULL
• Example: clientNo VARCHAR(5) NOT NULL
propertyNo VARCHAR(5) NOT NULL
UNIQUE (clientNo, PropertyNo)
 Any insert or update operation attempting to create a duplicate or
a null value is rejected

11/29/2020 J. TEKLI – [email protected] 24


Database Systems

Ch. 6 – SQL: Data Definition Engineering

3. Constraints
3.3. Integrity Constraints

• SQL supports the definition of a foreign key using the FOREIGN KEY clause
• Formal syntax: FOREIGN KEY attributeName(s) REFERENCES refAttributes

• Example: Considering relations SUPPLIER(supplierID, name, address) and


PRODUCT(productID, label, price), we can define the foreign key constraints in
DELIVERY(supplierID, productID, date, qty) as follows:
FOREIGN KEY supplierID REFERENCES SUPPLIER (supplierID)
FOREIGN KEY productID REFERENCES PRODUCT(productID)

• SQL will reject any insert or update operation that attempts to create a foreign key
value without matching its corresponding candidate key in the parent table
• We can omit the candidate key attribute name if it is equivalent to the foreign key
attribute name, e.g., FOREIGN KEY supplierID REFERENCES SUPPLIER

11/29/2020 J. TEKLI – [email protected] 25


Database Systems

Ch. 6 – SQL: Data Definition Engineering

3. Constraints
3.3. Integrity Constraints

• SQL can extend the FOREIGN KEY clause with referential actions
• When the user attempts to update/delete a row in the parent table having one or more
matching foreign keys in the child table, SQL can take the following actions:

• CASCADE: update/delete the row from the parent table, & matching rows in the child
• If rows in the child table also have foreign keys in descendent tables, those too are
deleted: in a cascading manner…
Example: FOREIGN KEY (productID) REFERENCES PRODUCT ON DELETE CASCADE

• SET NULL: update/delete the row from the parent table, and set the foreign key values
in the child table to NULL
• Valid only if the foreign key attributes do not have a NOT NULL constraint
Example: FOREIGN KEY (productID) REFERENCES PRODUCT ON UPDATE SET NULL

11/29/2020 J. TEKLI – [email protected] 26


Database Systems

Ch. 6 – SQL: Data Definition Engineering

3. Constraints
3.3. Integrity Constraints

• SQL can extend the FOREIGN KEY clause with referential actions
• When the user attempts to update/delete a row in the parent table having one or
more matching foreign keys in the child table, SQL can take the following actions:

• SET DEFAULT: update/delete the row from the parent table, and set each
component of the foreign key in the child table to the specified default value
• Valid only if the foreign key attributes have a DEFAULT value
Example: FOREIGN KEY (clientID) REFERENCES CLIENT ON UPDATE SET DEFAULT

• NO ACTION: reject the update/deletion operation from the parent table


• This is the default setting if the ON DELETE/ON UPDATE rules are omitted
Example: FOREIGN KEY (clientID) REFERENCES CLIENT ON DELETE NO ACTION
equivalent to FOREIGN KEY (clientID) REFERENCES CLIENT

11/29/2020 J. TEKLI – [email protected] 27


Database Systems

Ch. 6 – SQL: Data Definition Engineering

3. Constraints
3.4. General Constraints

• SQL allows the definition of general constraints


• General rules defined by the DBA allowing to enforce enterprise regulations…
• Formal syntax: CREATE CONSTRAINT ConstraintName
CHECK (condition)
• Example: Define a general constraint verifying that a supplier cannot supply more
than 10 products:
CREATE CONSTRAINT SupplierProductLimit
CHECK (NOT EXISTS (SELECT supplierID FROM DELIVERY
GROUP BY supplierID HAVING COUNT(*) > 10))

• Constraints can be defined using the CHECK clause when creating a domain of values
• Yet we usually use the CREATE CONSTRAINT clause when dealing with data from
multiple tuples
Database Systems

Ch. 6 – SQL: Data Definition Engineering

4. Data Definition

• SQL DDL allows different statements to create all components of a database


• We will cover the most basic ones in this chapter, including:
• CREATE DATABASE
• CREATE TABLE and ALTER TABLE
• CREATE DOMAIN and ALTER DOMAIN
• CREATE VIEW

• SQL DDL also allows different statements to remove components from a database
• We will cover the most basic ones in this chapter, including:
• DROP DATABASE
• DROP TABLE
• DROP DOMAIN
• DROP VIEW

11/29/2020 J. TEKLI – [email protected] 29


Database Systems

Ch. 6 – SQL: Data Definition Engineering

4. Data Definition
4.1. Creating the Database

• The process of creating a database can differ from one DBMS to another
• Here, we present the most general statements adopted in the SQL ISO standard
• Formal syntax: CREATE DATABASE databaseName

• The CREATE DATABASE statement is usually followed by a USE statement


• In order to connect to the database and start creating its components (tables,
constraints, etc.)
• Formal syntax: USE databaseName

• Example: CREATE DATABASE ProductDelivery; /* A semi-column is typically required */


USE ProductDelivery; /* after each statement */

11/29/2020 J. TEKLI – [email protected] 30


Database Systems

Ch. 6 – SQL: Data Definition Engineering

4. Data Definition
4.2. Creating a Table

• Having created and connected to the database, we can start creating tables
• Formal syntax: CREATE TABLE tableName
( columnName columnDomainDefinition,
… /* including all column definitions as described previously */
… /* along with data-type definitions and domain constraints */
PRIMARY KEY(columnName(s)),
FOREIGN KEY… /* optional */ )

• Example: In the following, we will create the relational DB schema describing product
deliveries, defined and used as a running example in Ch. 4 and Ch. 5, including all
relations (tables), including all attributes (columns), along with their data-type
definitions, domain constraints, and integrity constraints.

11/29/2020 J. TEKLI – [email protected] 31


Database Systems

Ch. 6 – SQL: Data Definition Engineering

4. Data Definition
4.2. Creating a Table

• Running example: Recall the relational data model covered in Ch. 4 and Ch. 5:

Supplier Product
1,n Delivers 1,n
supplierID productID
CDM-ER name qty
date label
address price
Entity Entity

SUPPLIER DELIVERY PRODUCT


supplierID supplierID productID
LDM-RDM name productID label
address date price
qty
Table Table

11/29/2020 J. TEKLI – [email protected] 32


Database Systems

Ch. 6 – SQL: Data Definition Engineering

4. Data Definition
4.2. Creating a Table

• Running example: The resulting relational DB schema (RDM):


Relations:
- SUPPLIER (supplierID, name, address)
- PRODUCT (productID, label, price)
- DELIVERY (supplierID, productID, date, qty)

Primary keys:
- PK(SUPPLIER) = {supplierID}
- PK(PRODUCT) = {productID}
- PK(DELIVERY) = {supplierID, productID, date}

Foreign keys:
- FK(DELIVERY) = { (supplierID, SUPPLIER.supplierID), (productID, PRODUCT.productID)

11/29/2020 J. TEKLI – [email protected] 33


Database Systems

Ch. 6 – SQL: Data Definition Engineering

4. Data Definition
4.2. Creating a Table

• Running example: Corresponding attribute domains


Regarding relation SUPPLIER:
- Dom(supplierID)= Integer number  [1, 999], formatted as “999”
- Dom(name) = String of characters of maximum size = 50
- Dom(address) = String of characters of maximum size = 100, with default address: “Byblos”

Regarding relation PRODUCT:


- Dom(productID)= Character ‘P’ followed by an integer number  [1, 999], formatted as “P999”
- Dom(label) = String of characters of maximum size = 50
- Dom(price) = Currency number  [0.00, 100000.00]

Regarding relation DELIVERY


- Dom(supplierID)= Dom(SUPPLIER.supplierD) - Dom(productID)= Dom(PRODUCT.productID)
- Dom(qty) = Integer number  [0, 1000] - Dom(date)= Date  [1900-01-01, present]

11/29/2020 J. TEKLI – [email protected] 34


Database Systems

Ch. 6 – SQL: Data Definition Engineering

4. Data Definition
4.2. Creating a Table

• Running example: After creating and connecting to the database


• We start creating the most basic tables: those with no foreign keys

CREATE TABLE SUPPLIER


( supplierID DECIMAL(3, 0) CHECK (supplierID BETWEEN 1 AND 999),
name VARCHAR(50) NOT NULL, /* Adding data occurrence constraint */
address VARCHAR(100) DEFAULT “Byblos”, /* Adding default value */
PRIMARY KEY (supplierID) ); /* Semi-column added in MySQL */

CREATE TABLE PRODUCT


( productID VARCHAR(4) NOT NULL, /* NOT NULL enforced by PK, can be removed */
label VARCHAR(50),
price DECIMAL(8, 2) DEFAULT 10 CHECK (price >=0 AND price <=100000),
PRIMARY KEY (productID) ); /* Semi-column added in MySQL */
Database Systems

Ch. 6 – SQL: Data Definition Engineering

4. Data Definition
4.2. Creating a Table

• Running example: Having defined the basic tables, we can now create tables
containing foreign keys

CREATE TABLE DELIVERY


( supplierID DECIMAL(3,0),
productID VARCHAR(4),
date DATE,
qty DECIMAL (4, 0) DEFAULT 0 CHECK (qty BETWEEN 0 AND 1000),
PRIMARY KEY (supplierID, productID, date),
FOREIGN KEY (supplierID) REFERENCES SUPPLIER(supplierID),
FOREIGN KEY (productID) REFERENCES PRODUCT(productID) )

NOTE: It is not advised to use SQL reserved words as identifiers (e.g., date)

11/29/2020 J. TEKLI – [email protected] 36


Database Systems

Ch. 6 – SQL: Data Definition Engineering

4. Data Definition
4.3. Changing the Definition of a Table

• Having created a table, we can change its definition using ALTER TABLE
• The ALTER TABLE statement allows six options:
• Adding a new column (attribute) in a table
• Dropping a column (attribute) from a table
• Modifying/changing the definition of a column
• Adding a new constraint
• Data occurrence constraint
• Domain constraint
• Integrity constraint
• General constraint
• Dropping a constraint
• Setting a default value for a column (attribute) in a table
• Dropping a default from a column (attribute) in a table
Database Systems

Ch. 6 – SQL: Data Definition Engineering

4. Data Definition
4.3. Changing the Definition of a Table

• Adding a new column (attribute) to a table

• Example: Consider table SUPPLIER defined previously

ALTER TABLE SUPPLIER


ADD COLUMN POBox CHAR(10)

• Dropping a column (attribute) from a table

• Example: Consider table SUPPLIER defined previously

ALTER TABLE SUPPLIER


DROP COLUMN POBox

11/29/2020 J. TEKLI – [email protected] 38


Database Systems

Ch. 6 – SQL: Data Definition Engineering

4. Data Definition
4.3. Changing the Definition of a Table

• Adding a new constraint

• Example: Consider table SUPPLIER, with the added POBox attribute:


ALTER TABLE SUPPLIER
ADD CONSTRAINT UNIQUE(PoBox) /* Alternative key uniqueness constraint */

• Example: Adding a primary key constraint in table SUPPLIER


ALTER TABLE SUPPLIER
ADD CONSTRAINT PRIMARY KEY (supplierID, PoBox)

• Example: Adding a foreign key constraint in table DELIVERY


ALTER TABLE DELIVERY
ADD CONSTRAINT FOREIGN KEY (supplierID) REFERENCES SUPPLIER(supplierID);
Database Systems

Ch. 6 – SQL: Data Definition Engineering

4. Data Definition
4.3. Changing the Definition of a Table

• Adding/dropping a new constraint

We can provide a label identifying the constraint:

• Example: ALTER TABLE SUPPLIER


ADD CONSTRAINT CT1 UNIQUE(PoBox) /* constraint is labeled “ct1” */

• Example: ALTER TABLE DELIVERY


ADD CONSTRAINT FK1 FOREIGN KEY(supplierID) REFERENCES
SUPPLIER(supplierID)

The constraint label can be used to drop the constraint when needed:

• Example: ALTER TABLE DELIVERY


DROP CONSTRAINT FK1 /* dropping the “FK1” constraint */
Database Systems

Ch. 6 – SQL: Data Definition Engineering

4. Data Definition
4.3. Changing the Definition of a Table

• Adding/dropping a new constraint

We can provide a label identifying the constraint:

• Example: Define a general constraint on table DELIVERY allowing a maximum of


three deliveries per supplier:
ALTER TABLE DELIVERY
ADD CONSTRAINT SupplierDeliveryLimit
CHECK (NOT EXISTS (SELECT COUNT(*) FROM DELIVERY
GROUP BY supplierID
HAVING COUNT(*) <3))
Database Systems

Ch. 6 – SQL: Data Definition Engineering

4. Data Definition
4.3. Changing the Definition of a Table

• Modifying/changing the definition of a column and its constraints:

• Example: ALTER TABLE SUPPLIER


MODIFY COLUMN POBoX CHAR(8) NOT NULL DEFAULT “00-00-00”

We can even change the name of a column:

• Example: ALTER TABLE SUPPLIER


CHANGE COLUMN POBox postalCode CHAR(8)

NOTE: When modifying or changing the definition of a column using the ALTER TABLE
statement, we always have to redefine the column data-type
- Constraints are preserved if they are not altered!
Database Systems

Ch. 6 – SQL: Data Definition Engineering

4. Data Definition
4.3. Changing the Definition of a Table

• Setting a default value:

• Example: ALTER TABLE SUPPLIER


ALTER name SET DEFAULT “Jones”

• Dropping a default value:

• Example: ALTER TABLE SUPPLIER


ALTER name DROP DEFAULT;

11/29/2020 J. TEKLI – [email protected] 43


Database Systems

Ch. 6 – SQL: Data Definition Engineering

4. Data Definition
4.3. Changing the Definition of a Table

• NOTE:
– The ALTER TABLE statement is not available in all SQL dialects/DBMSs
– The ALTER TABLE statement functionalities are limited in certain dialects/DBMSs
• E.g., Some DBMSs do not allow to drop a column or a constraint…

– It is dangerous to alter the definition of a table when changes affect the data

– It is not advised to use ALTER TABLE except when absolutely necessary


• Whenever changes in the DB schema are needed, it is advised to:
– Upload all data from the table/DB
– Remove the old table/DB
– Create a new table/DB
– Reload data in newly created tables/DB
Database Systems

Ch. 6 – SQL: Data Definition Engineering

4. Data Definition
4.4. Dropping a Table

• We can remove a table from the DB schema using the DROP TABLE statement
– Example: DROP TABLE SUPPLIER
 Dropping table SUPPLIER along with all rows and constraints in it…

• NOTE: To simply remove the data (rows) from a table and keep the structure
– We utilize the DELETE (SQL DML) statement (cf. Ch. 5)
• Example: DELETE FROM SUPPLIER

11/29/2020 J. TEKLI – [email protected] 45


Database Systems

Ch. 6 – SQL: Data Definition Engineering

4. Data Definition
4.4. Dropping a Table

• The DROP TABLE statement allows to specify two clauses:


– RESTRICT: the drop is rejected if there is data that depends for its existence on
the table
• Example: DROP TABLE SUPPLIER RESTRICT
– The statement will not execute when there are rows in DELIVERY depending
on data in SUPPLIER (referential integrity)
 We first have to delete/drop DELIVERY, to be able to drop SUPPLIER

– CASCADE: the drop operation proceeds and the DBMS automatically drops all
descendent data
• Example: DROP TABLE SUPPLIER CASCADE
– The statement will execute and will affect (delete) all rows in DELIVERY
referring to SUPPLIER
Database Systems

Ch. 6 – SQL: Data Definition Engineering

5. Views

• Recall the three-level ASNSI-SPARC architecture from Ch. 1:

External level

Conceptual level

Internal level

Physical data
organization

11/29/2020 J. TEKLI – [email protected] 47


Database Systems

Ch. 6 – SQL: Data Definition Engineering

5. Views

• The external view of a DB represents the structure of a DB as it appears to a


particular user
– Yet, following the relational model, the term view has a more technical meaning

• View: it is a derived/virtual relation (table) that does not exist in the DB schema,
and that is created upon a particular user’s request, at the time of the request
• It is dynamically derived from one/many base relations (tables) or views
• Base relation (table): relation (table) that exists in the original DB schema

• A view is defined as the result of an SQL query applied on base tables or views

11/29/2020 J. TEKLI – [email protected] 48


Database Systems

Ch. 6 – SQL: Data Definition Engineering

5. Views
5.1. Creating a View

• Formal syntax of CREATE VIEW statement:


CREATE VIEW viewName (columnName, …) /* column names are optional */
AS selectQuery

– If the list of column names is omitted:


• Each column in the view takes the name of the column in the selectQuery

– Example: CREATE VIEW SUPPLIERS_IN_BEIRUT


AS SELECT * FROM SUPPLIER WHERE address LIKE “%Beirut%”
 Horizontal view, consisting of a horizontal sub-set of an original
table/view, excluding certain rows

11/29/2020 J. TEKLI – [email protected] 49


Database Systems

Ch. 6 – SQL: Data Definition Engineering

5. Views
5.1. Creating a View

• Creating a vertical view, consisting of a vertical sub-set of the original table/view,


excluding certain attributes

– Example: CREATE VIEW SUPPLIER_NAMES


AS SELECT supplierID, name FROM SUPPLIER

• Horizontal and vertical views provide:


• Customized views of the data showing only data of interest to certain users
• A level of security: allowing certain users to access certain parts of the data,
while hiding other parts

11/29/2020 J. TEKLI – [email protected] 50


Database Systems

Ch. 6 – SQL: Data Definition Engineering

5. Views
5.1. Creating a View

• Creating joined views, combining data from different tables:


– Example: CREATE VIEW DELIVERY_DETAILS
AS SELECT S.supplierID, name, P.productID, label, date, qty, price
FROM PRODUCT P, SUPPLIER S, DELIVERY D
WHERE P.productID = D.productID AND S.supplierID = D.supplierID

• Creating grouped views, where the data is grouped following certain user preferences
– Example: CREATE VIEW PRODUCT_PRICE
AS SELECT label, AVG(price) FROM PRODUCT
GROUP BY label

• Joined and grouped views allow to simplify multi-table and group data access
Database Systems

Ch. 6 – SQL: Data Definition Engineering

5. Views
5.2. View Processing

• Let us take a closer look on how views are actually processed


 Consider the following example from the previous slide:

– Example: CREATE VIEW DELIVERY_DETAILS


AS SELECT S.supplierID, name, P.productID, label, date, qty, price
FROM PRODUCT P, SUPPLIER S, DELIVERY D
WHERE P.productID = D.productID AND S.supplierID = D.supplierID

– Now consider the following query applied on the view:

SELECT label, SUM(qty*price) AS totalPrice FROM DELIVERY_DETAILS


WHERE name != “Jones” GROUP BY label HAVING totalPrice > 500
ORDER BY label
Query processing details are developed in the following slide…
Database Systems

Ch. 6 – SQL: Data Definition Engineering

5. Views
5.2. View Processing

• Running example: The view query applied on the DELIVERY_DETAILS view is


merged with the original query defining the view

– The view column names in the select (target) list of the view query are translated into
their corresponding names in the original view defining query
– The view name in the FROM (range) clause of the view query is replaced with the
corresponding FROM (range) clause in the original view defining query
– The WHERE (qualification) clause in the view query is combined with the WHERE
clause of the original view defining query using the logical AND operator
– The GROUP BY (grouping) clause in the view query is added to the original view
defining query
– The HAVING (group qualification) clause in the view query is combined with the
HAVING clause of the original view defining query using the logical AND connective
– The ORDER BY clause in the view query is added to the original view defining query
Database Systems

Ch. 6 – SQL: Data Definition Engineering

5. Views
5.2. View Processing

• Running example: The view query applied on the DELIVERY_DETAILS view will be
merged with the original query defining the view

– The final merged query which will be processed by the DBMS becomes:

SELECT label, SUM(qty*price) AS totalPrice


FROM PRODUCT P, SUPPLIER S, DELIVERY D
WHERE P.productID = D.productID AND S.supplierID = D.supplierID
AND name != “Jones”
GROUP BY label HAVING totalPrice > 500 Considering the extensional view of the
ProductDelivery DB from Ch. 5
ORDER BY label
label totalPrice
Scanner 800.00
Screed 600.00
Database Systems

Ch. 6 – SQL: Data Definition Engineering

5. Views
5.3. Modifying Data in Views

• All modifications to the data in a base table are immediately reflected in all
views defined based the base table
– Nonetheless, modifying data from within a view is not straightforwardly
reflected in corresponding base tables

Example: Consider the following view:


CREATE VIEW SUPPLIER_NAMES
AS SELECT name FROM SUPPLIER

Attempting to insert data using the view might fail:


INSERT INTO SUPPLIER_NAMES VALUES (“Jason”)

Since critical information, such as the supplierID, is missing…

11/29/2020 J. TEKLI – [email protected] 55


Database Systems

Ch. 6 – SQL: Data Definition Engineering

5. Views
5.3. Modifying Data in Views

• Following the SQL standard: for a view to be modifiable (updatable), the DBMS must
be able to trace, without ambiguity any updated/inserted/deleted row or column
back to its row or column in the source table, i.e., when:
• DISTINCT is not specified in the query defining the view
– Duplicate rows should appear in the view to be updatable
• Elements in the SELECT (target) clause of the query defining the view should only
contain column names
– Constants, Expressions, or aggregate functions are not allowed
• The FROM (range) clause should contain only one table/view
– In case the FROM clause contains a view, it must also comply with the aforementioned
conditions
• The WHERE (qualification) clause should not contain nested sub-queries
• There should be no GROUP BY or HAVING clauses in the view defining query
Database Systems

Ch. 6 – SQL: Data Definition Engineering

5. Views
5.3. Modifying Data in Views

• Behavior of views subject to data modifications:


• If a row is altered in a way such that it no longer verifies the view selectQuery,
then it will be modified and will disappear from the current view

• If a row is inserted in the view such that it does not verify the view’s selectQuery,
then it will be inserted in the view’s base table, but it will not appear in the view

• New rows might appear in the view when an insert or update on the view/base
table causes them to satisfy the view’s selectQuery

These are called migrating rows

11/29/2020 J. TEKLI – [email protected] 57


Database Systems

Ch. 6 – SQL: Data Definition Engineering

5. Views
5.3. Modifying Data in Views

• When handling modifiable (updatable) views, SQL allows a higher level of control
using the WITH CHECK OPTION statement:
– Formal syntax: CREATE VIEW viewName (columnName, …)
AS selectQuery WITH CHECK OPTION

• This feature allows to enforce constraints on UPDATE and INSERT operations


– Allowing a higher level of control using views
• Which makes views all the more attractive!

11/29/2020 J. TEKLI – [email protected] 58


Database Systems

Ch. 6 – SQL: Data Definition Engineering

5. Views
5.3. Modifying Data in Views

• When specified, the WITH CHECK OPTION makes certain that updates/inserts of rows
which do not satisfy the selectQuery WHERE (qualification) clause are rejected

– Example: CREATE VIEW SUPPLIERS_IN_BEIRUT


AS SELECT * FROM SUPPLIER WHERE address LIKE “%Beirut%”
WITH CHECK OPTION

– The following insert operation applied on the view would fail:


INSERT INTO SUPPLIERS_IN_BEIRUT
VALUES (180, “Jason”, “39 M. Byblos”)
Does not satisfy the WHERE clause

11/29/2020 J. TEKLI – [email protected] 59


Database Systems

Ch. 6 – SQL: Data Definition Engineering

5. Views
5.4. Removing a View

• A view can be removed using the DROP VIEW statement


– Formal syntax: DROP VIEW viewName
– Drops the view if no other views depend on it
– Otherwise, if other views use the current view, the drop is rejected
– Equivalent syntax: DROP VIEW viewName RESTRICT

• DROP VIEW can also be written using the CASCADE statement


– Formal syntax: DROP VIEW viewName CASCADE
– Drops the view and all views defined on the current view (if those exist)

11/29/2020 J. TEKLI – [email protected] 60


Database Systems

Ch. 6 – SQL: Data Definition Engineering

5. Views
5.5. Pros and Cons

• Pros of using views:


– Data independence: Providing a consistent picture of the structure of the DB
• Even if the DB schema changes (given that changes do not affect the view)
– E.g., added/removed columns from the table such that they are not used in the view
• An old table structure can be recreated using a view…
– Currency: Changes in base tables are reflected in the view
– Reduced complexity: Simplify data structure w.r.t. to the user - simplify query writing
– Convenience: Users are only provided with the data they need
– Customization: Views are defined following user request/needs
– Data integrity: Ensured using the WITH CHECK OPTION of the CREATE VIEW statement
• No rows that fail to satisfy the WHERE clause of the query defining the view are added
– Security: views can be made accessible to specific users, thus restricting data access
Database Systems

Ch. 6 – SQL: Data Definition Engineering

5. Views
5.5. Pros and Cons

• Cons of using views:

– Data modification restriction: Views cannot be always updated (insert/update/delete)


• Especially when built on grouped or joined tables

– Structure restriction: The structure of a view is determined at the time of its creation
• And cannot change unless the view is dropped and a new one is created
– NOTE: A view defined on a SELECT * FROM tableName will always contain
the original columns of the table
- Even if the table columns ultimately change!

– Performance: Performance penalty, especially when dealing with multi-table views


• Since the view will have to join the base tables every time the view is accessed

11/29/2020 J. TEKLI – [email protected] 62


Database Systems

Ch. 6 – SQL: Data Definition Engineering

6. Access Control

• A DBMS should provide a mechanism to ensure that only authorized users can
access the DB, as well as what parts of the DB specific users can access…

• There are two main strategies toward access control:


– Discretionary access control: each user is given appropriate access rights
on specific database objects. Typically:
• Users obtain all data access privileges when they create an object
• Users can pass certain/all data access privileges to other users
Supported in SQL

– Mandatory access control: each database object is assigned a certain


classification level (e.g. Top Secret > Secret > Confidential > Unclassified)
• And each subject (e.g. user, application) is given a designated clearance level
• A subject needs appropriate clearance to access the data object
Database Systems

Ch. 6 – SQL: Data Definition Engineering

6. Access Control
6.1. Authorization Identifiers

• Authorization identifier: SQL identifier used to establish a user’s identity


– Each user can also be associated a password for obvious security reasons
CREATE USER USERNAME IDENTIFIED BY PASSWORD
- Example: CREATE USER “Sandy” IDENTIFIED BY “111”

• Every SQL statement executed by the DBMS is performed on behalf of a user


– Each data object (e.g., table/view) that is created in SQL has an owner user
• The owner is initially the only person having access to the created object
– And can consequently perform any operations on the object
– The owner has to pass privileges to other users so that they can manipulate the
data object

11/29/2020 J. TEKLI – [email protected] 64


Database Systems

Ch. 6 – SQL: Data Definition Engineering

6. Access Control
6.2. Privileges

• Privileges are actions that a user is permitted to carry out on a given DB


table/view, namely:
– SELECT: the privilege to retrieve data from a table/view
– INSERT: the privilege to insert new rows in a table/view
– UPDATE: the privilege to modify rows of data in a table/view
– DELETE: the privilege to delete rows of data from a table/view
– REFERENCES: the privilege to reference columns of a named table in integrity
constraints

11/29/2020 J. TEKLI – [email protected] 65


Database Systems

Ch. 6 – SQL: Data Definition Engineering

6. Access Control
6.2. Privileges

• The INSERT and UPDATE privileges can be restricted to specific columns in a


table/view
– Allowing changes to these columns, while disallowing them to other columns

• Similarly, the REFERENCES privilege can be restricted to specific columns


– Allowing these columns to be referenced in constraints such as: CHECK and FOREIGN
KEY constraints
• But disallowing others from being referenced

11/29/2020 J. TEKLI – [email protected] 66


Database Systems

Ch. 6 – SQL: Data Definition Engineering

6. Access Control
6.3. Granting Privileges

• The owner of a data object has to grant privileges to other users so that they can
access the object
– Formal syntax: GRANT privilege ON objectName TO user

• Privileges can be expressed as:


– SELECT
– DELETE
– INSERT (columnList) /* columnList is optional */
– UPDATE (columnList) /* columnList is optional */
– REFERENCES (columnList) /* columnList is optional */

11/29/2020 J. TEKLI – [email protected] 67


Database Systems

Ch. 6 – SQL: Data Definition Engineering

6. Access Control
6.3. Granting Privileges

• Example: Providing user u100 access and update privileges on table SUPPLIER where
the user can access all table columns but can only update column address

GRANT SELECT, UPDATE(address) ON SUPPLIER TO u100

• SQL allows statement ALL PRIVILIGES to assign all privileges to a user


– Example: GRANT ALL PRIVILEGES ON SUPPLIER TO u100
- GRANT ALL ON ProductDelivery.* TO u100

• SQL allows statement PUBLIC to assign privileges to all users


– Example: GRANT SELECT ON SUPPLIER TO PUBLIC

11/29/2020 J. TEKLI – [email protected] 68


Database Systems

Ch. 6 – SQL: Data Definition Engineering

6. Access Control
6.3. Granting Privileges

• SQL provides statement WITH GRANT OPTION


– Allows a user to pass privileges they have been given on a certain data object to
other users
• The user receiving WITH GRANT OPTION may in turn grant it to other users:
cascading effect
– If not specified, the receiving user will not be able to pass privileges

• Example: GRANT SELECT, UPDATE(address) ON SUPPLIER TO u100


WITH GRANT OPTION

11/29/2020 J. TEKLI – [email protected] 69


Database Systems

Ch. 6 – SQL: Data Definition Engineering

6. Access Control
6.4. Revoking Privileges

• The REVOKE statement allows to revoke user privileges


– It can take away some/all privileges
• Formal syntax: REVOKE privileges ON objectName FROM users

• We can revoke all privileges using ALL PRIVILEGES statement


– Example: REVOKE ALL PRIVILEGES ON SUPPLIER FROM u100
- REVOKE ALL PRIVILEGES ON ProductDelivery.* FROM u100

• We can revoke privileges from all users using PUBLIC statement


– Example: REVOKE SELECT ON SUPPLIER FROM PUBLIC

11/29/2020 J. TEKLI – [email protected] 70


Database Systems

Ch. 6 – SQL: Data Definition Engineering

6. Access Control
6.4. Revoking Privileges

• Privileges granted to a certain user are not affected by other users


– Even if the privilege being granted by one user has been revoked by another

User A
5. REVOKE INSERT
1. GRANT INSERT ON SUPPLIER WITH GRANT OPTION
ON SUPPLIER

User B
 2. GRANT INSERT ON SUPPLIER WITH GRANT OPTION

User C User E
3. GRANT INSERT
ON SUPPLIER
4. GRANT INSERT ON SUPPLIER WITH GRANT OPTION

User D

11/29/2020 J. TEKLI – [email protected] 71


Database Systems

Ch. 6 – SQL: Data Definition Engineering

Wrapping up with main points covered in the chapter:

• Introduction to SQL – Data Definition Language


– Covering the main SQL DDL statements
• Identifiers
• Scalar data-types
• Constraints
– Occurrence
– Domain
– Integrity
– General
• Data definition (creating and modifying databases and tables)
• Views (creating and modifying views)
• Access Control (handling user privileges)

11/29/2020 J. TEKLI – [email protected] 72


Database Systems

Ch. 6 – SQL: Data Definition Engineering

Support Material and Exercises

• Available in the textbook - Chapters 7


• Available on Blackboard!

11/29/2020 J. TEKLI – [email protected] 73

You might also like