Chapter 4 LAU
Chapter 4 LAU
Database Systems
COE 418
1. Introduction
Chapter Contents
1. Introduction
2. Identifiers and Data-Types
3. Constraints
4. Data Definition
5. Views
6. Access Control
• NOTE:
• An identifier can be no longer than 128 characters
• An identifier must start with a letter
4
Database Systems
• 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
• Character data
• Sequence of characters from a DBMS-defined character set
Most DBMSs adopt the ASCII character set (and more recently Unicode)
• 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.
• 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)
• 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
• 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‘
• 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’
– RPAD(): Returns a string, right padded with a parameter string, to a certain length
– Example: RPAD(“John”, 7, “*”) returns “John***”
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
3. Constraints
3.1. Data Occurrence Constraints
3. Constraints
3.2. Domain Constraints
3. Constraints
3.2. Domain Constraints
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:
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
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
3. Constraints
3.3. Integrity Constraints
3. Constraints
3.3. Integrity Constraints
• 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
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
• 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
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
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
3. Constraints
3.4. General Constraints
• 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
4. Data Definition
• 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
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
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.
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
4. Data Definition
4.2. Creating a Table
Primary keys:
- PK(SUPPLIER) = {supplierID}
- PK(PRODUCT) = {productID}
- PK(DELIVERY) = {supplierID, productID, date}
Foreign keys:
- FK(DELIVERY) = { (supplierID, SUPPLIER.supplierID), (productID, PRODUCT.productID)
4. Data Definition
4.2. Creating a Table
4. Data Definition
4.2. Creating a Table
4. Data Definition
4.2. Creating a Table
• Running example: Having defined the basic tables, we can now create tables
containing foreign keys
NOTE: It is not advised to use SQL reserved words as identifiers (e.g., date)
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
4. Data Definition
4.3. Changing the Definition of a Table
4. Data Definition
4.3. Changing the Definition of a Table
4. Data Definition
4.3. Changing the Definition of a Table
The constraint label can be used to drop the constraint when needed:
4. Data Definition
4.3. Changing the Definition of a Table
4. Data Definition
4.3. Changing the Definition of a Table
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
4. Data Definition
4.3. Changing the Definition of a Table
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
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
4. Data Definition
4.4. Dropping a Table
– 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
5. Views
External level
Conceptual level
Internal level
Physical data
organization
5. Views
• 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
5. Views
5.1. Creating a View
5. Views
5.1. Creating a View
5. Views
5.1. Creating a View
• 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
5. Views
5.2. View Processing
5. Views
5.2. View Processing
– 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
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:
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
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
5. Views
5.3. Modifying Data in Views
• 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
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
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
5. Views
5.4. Removing a View
5. Views
5.5. Pros and Cons
5. Views
5.5. Pros and Cons
– 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!
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…
6. Access Control
6.1. Authorization Identifiers
6. Access Control
6.2. Privileges
6. Access Control
6.2. Privileges
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
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
6. Access Control
6.3. Granting Privileges
6. Access Control
6.4. Revoking Privileges
6. Access Control
6.4. Revoking Privileges
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