Sei sulla pagina 1di 22

CS 338: Computer Applications in Business: Databases (Fall 2014)

Basic SQL

DDL and Data Types,


Specifying Constraints
Chapter 4

Fall 2014

1992-2014 by Addison Wesley & Pearson Education, Inc., McGraw Hill, Cengage Learning

Slides adapted and modified from Fundamentals of Database Systems (5/6) (Elmasri et al.), Database System
Concepts (5/6) (Silberschatz et al.), Database Systems (Coronel et al.), Database Systems (4/5) (Connolly et al. )

CS 338: Computer Applications in Business: Databases


Rice University Data Center

Announcements
Assignment 1
Due Monday October 6th, 2014
Solutions will be posted on midnight

Lecture 4 Exercise
Solutions posted LEARN

Content

Lecture 4

1992-2014 by Addison Wesley & Pearson Education, Inc., McGraw Hill, Cengage Learning
Slides adapted and modified from Fundamentals of Database Systems (5/6) (Elmasri et al.), Database System
Concepts (5/6) (Silberschatz et al.), Database Systems (Coronel et al.), Database Systems (4/5) (Connolly et al. )

CS 338: Computer Applications in Business: Databases (Fall 2014)

Questions & Review

Review
Partial Schema
Example of a partial schema:

can be read as
A Students relation consists of the columns (attributes)
named: sid, name, login, age, and gpa
The column (or attribute) named sid has a domain named
string. The set of values associated with domain string is
the set of all character strings

1992-2014 by Addison Wesley & Pearson Education, Inc., McGraw Hill, Cengage Learning
Slides adapted and modified from Fundamentals of Database Systems (5/6) (Elmasri et al.), Database System
Concepts (5/6) (Silberschatz et al.), Database Systems (Coronel et al.), Database Systems (4/5) (Connolly et al. )

CS 338: Computer Applications in Business: Databases (Fall 2014)

Review
Rows or Tuples
Rows (or tuples):
Each row (tuple) has the same number of columns (or attributes) as the relation
schema

Review
relational database state/schemas
What is a relational database state?
a collection of relation states with distinct relation names
m is the number of relations
DB = {r1, r2, ..., rm}

What is a relational database schemas?


the collection of schemas for the relations in the database
S = {R1, R2, ..., Rm}
m is the number of schemas

1992-2014 by Addison Wesley & Pearson Education, Inc., McGraw Hill, Cengage Learning
Slides adapted and modified from Fundamentals of Database Systems (5/6) (Elmasri et al.), Database System
Concepts (5/6) (Silberschatz et al.), Database Systems (Coronel et al.), Database Systems (4/5) (Connolly et al. )

CS 338: Computer Applications in Business: Databases (Fall 2014)

Review
Preserving quality of database
A database is only good as the data stored in it
DBMS must prevent the entry of incorrect data to preserve
the quality of the information stored
How?
Using integrity constraints (ICs):

a condition that is specified on a database schema and


restricts data that can be stored in an instance of the database

DBMS enforces ICs, that is, it only permits legal


instances to be stored in a database

Review
Referential Constraints
What is
Sometimes data stored in one relation is linked to data
stored in another relation

If one relation is modified, the other must be checked, and


perhaps modified, to keep data consistent

How to enforce data consistency in this case?


Using Foreign Keys

1992-2014 by Addison Wesley & Pearson Education, Inc., McGraw Hill, Cengage Learning
Slides adapted and modified from Fundamentals of Database Systems (5/6) (Elmasri et al.), Database System
Concepts (5/6) (Silberschatz et al.), Database Systems (Coronel et al.), Database Systems (4/5) (Connolly et al. )

CS 338: Computer Applications in Business: Databases (Fall 2014)

Review
Terminologies
A relation is a table (logical) with columns and rows.
An attribute is a named column of a relation.
A domain is a set of allowable values for one or more
attributes.
A tuple is a row of a relation.
Degree is a number of attributes in a relation.
Cardinality is a number of tuples in a relation.
Relational Database is a collection of relations.

Basic SQL

DDL and Data Types,


Specifying Constraints
Chapter 4

10

1992-2014 by Addison Wesley & Pearson Education, Inc., McGraw Hill, Cengage Learning
Slides adapted and modified from Fundamentals of Database Systems (5/6) (Elmasri et al.), Database System
Concepts (5/6) (Silberschatz et al.), Database Systems (Coronel et al.), Database Systems (4/5) (Connolly et al. )

CS 338: Computer Applications in Business: Databases (Fall 2014)

Basic SQL
Ideally, database language should allow users to:
create the database and relation structures;
perform insertion, modification, deletion of data from relations;
perform simple and complex queries

Must perform these tasks with


minimal user effort
command structure/syntax must be easy to learn

It must be portable
11

Basic SQL
Structured Query Language (SQL)
SQL is a comprehensive database language

Has statements for data definitions, queries, and


updates
it is both a DDL and a DML

Has facilities for defining views on the database,


security and authorization, defining integrity
constraints

SQL is considered one of the major reasons for the


commercial success of relational databases

1992-2014 by Addison Wesley & Pearson Education, Inc., McGraw Hill, Cengage Learning
Slides adapted and modified from Fundamentals of Database Systems (5/6) (Elmasri et al.), Database System
Concepts (5/6) (Silberschatz et al.), Database Systems (Coronel et al.), Database Systems (4/5) (Connolly et al. )

12

CS 338: Computer Applications in Business: Databases (Fall 2014)

Basic SQL
SQL is easy to learn
it is non-procedural

you specify what information you require, rather than how to get it
In other words, SQL does not require you to specify the access methods to
the data

it is essentially free-format

Parts of the statements do not have to be typed at particular locations on the


screen

SQL can be used by a range of users


can be used by DBAs, management, application developers, and other
types of end-users

An ISO standard exists


An ISO standard exists for SQL, making it both the formal and de facto
standard language for relational databases
13

Basic SQL
SQL consists of standard English words
CREATE TABLE staff(

);

id
lname
ssn

VARCHAR(5),
VARCHAR(15),
NUMBER(7,2)

INSERT INTO staff


VALUES ('SG16', 'Brown', 8300);
SELECT sno, lname, salary
FROM staff
WHERE salary > 10000;

14

1992-2014 by Addison Wesley & Pearson Education, Inc., McGraw Hill, Cengage Learning
Slides adapted and modified from Fundamentals of Database Systems (5/6) (Elmasri et al.), Database System
Concepts (5/6) (Silberschatz et al.), Database Systems (Coronel et al.), Database Systems (4/5) (Connolly et al. )

CS 338: Computer Applications in Business: Databases (Fall 2014)

Basic SQL
SQL standards are mainly divided into two parts:
core specification
core SQL: a set of features that a vendor must implement to
claim conformance with the SQL standard

specialized extensions
can be implemented as optional modules to be purchased
independently for specific database applications (i.e. data
mining, multimedia data, etc)

15

Basic SQL

Basic Guidelines for Writing SQL Statements

SQL statement consists of reserved words and


user-defined words
reserved words are a fixed part of SQL and must be
spelled exactly as required and cannot split across lines
user-defined words are made up by user and represent
names of various database objects such as table, columns,
views, etc

Most components of an SQL statement are case


insensitive, except for literal character data
16

1992-2014 by Addison Wesley & Pearson Education, Inc., McGraw Hill, Cengage Learning
Slides adapted and modified from Fundamentals of Database Systems (5/6) (Elmasri et al.), Database System
Concepts (5/6) (Silberschatz et al.), Database Systems (Coronel et al.), Database Systems (4/5) (Connolly et al. )

CS 338: Computer Applications in Business: Databases (Fall 2014)

Basic SQL

Basic Guidelines for Writing SQL Statements

More readable with indentation and lineation:


Each clause should begin on a new line
Start of a each clause should line up with start of other clauses
If clause has several parts, they should each appear on a
separate line and be indented under start of clause to show the
relationship

Use extended form of Backus Normal Form (BNF)


notation
Upper case letters represent reserved words
Lower case letters represent user-defined words
| indicates a choice among alternatives e.g. a | b | c
{} Curly braces indicate a required element
[] Square brackets indicate an optional element
An ellipsis () indicates optional repetition (0 or more)
17

Basic SQL

Basic Guidelines for Writing SQL Statements

Literals are constants used in SQL statements


All non-numeric literals must be enclosed in single
quotes (e.g. London)
All numeric literals must not be enclosed in quotes
(e.g. 650.00).

18

1992-2014 by Addison Wesley & Pearson Education, Inc., McGraw Hill, Cengage Learning
Slides adapted and modified from Fundamentals of Database Systems (5/6) (Elmasri et al.), Database System
Concepts (5/6) (Silberschatz et al.), Database Systems (Coronel et al.), Database Systems (4/5) (Connolly et al. )

CS 338: Computer Applications in Business: Databases (Fall 2014)

SQL Data Definition and Data Types


SQL uses the terms table, row, and column for the formal
relational model terms relation, tuple, and attribute,
respectively
CREATE statement
Main SQL command for data definition
Used to create
schemas,
tables (relations)
views, assertions, and triggers
19

Schema and Catalog Concepts in SQL


SQL schema
Identified by a schema name
Includes an authorization identifier and descriptors for each
element
Each statement in SQL ends with a semicolon
Schema elements include
tables, constraints, views, domains, and other constructs

Example
CREATE SCHEMA statement
CREATE SCHEMA COMPANY AUTHORIZATION Jsmith;
schema name

authorization identifier

1992-2014 by Addison Wesley & Pearson Education, Inc., McGraw Hill, Cengage Learning
Slides adapted and modified from Fundamentals of Database Systems (5/6) (Elmasri et al.), Database System
Concepts (5/6) (Silberschatz et al.), Database Systems (Coronel et al.), Database Systems (4/5) (Connolly et al. )

20

10

CS 338: Computer Applications in Business: Databases (Fall 2014)

SQL Data Definition Statements

CREATE SCHEMA and DROP SCHEMA


CREATE TABLE
ALTER TABLE
DROP TABLE

21

The CREATE TABLE Command in SQL


CREATE TABLE
The CREATE TABLE command is used to specify a new relation
You need to
1. provide a table name,
2. specify attributes and initial constraints

Attributes

Attributes are specified first and each attribute is given:


1.
a name,
2.
a data type (to specify its domain of values), and
3.
Attribute constraints (i.e. NOT NULL)

Initial constraints

Key, entity integrity, and referential integrity constraints can be


specified within the CREATE TABLE statement after the
attributes are declared
They can also be added later using the ALTER TABLE command

1992-2014 by Addison Wesley & Pearson Education, Inc., McGraw Hill, Cengage Learning
Slides adapted and modified from Fundamentals of Database Systems (5/6) (Elmasri et al.), Database System
Concepts (5/6) (Silberschatz et al.), Database Systems (Coronel et al.), Database Systems (4/5) (Connolly et al. )

22

11

CS 338: Computer Applications in Business: Databases (Fall 2014)

The CREATE TABLE Command in SQL


There are two methods for creating SQL Schema:
1. SQL schema is implicitly specified in the environment in which
the CREATE TABLE statements are executed

2. Explicitly attach the schema name to the relation name


separated by a period

Example
CREATE TABLE COMPANY.EMPLOYEE ...

23

The CREATE TABLE Command in SQL


Relations declared through CREATE TABLE statement are
called base tables (or base relations)
relation and its tuples are actually created and stored as
a file by the DBMS

Different from Virtual relations


Created through the CREATE VIEW statement
May or may not correspond to an actual physical file
24

1992-2014 by Addison Wesley & Pearson Education, Inc., McGraw Hill, Cengage Learning
Slides adapted and modified from Fundamentals of Database Systems (5/6) (Elmasri et al.), Database System
Concepts (5/6) (Silberschatz et al.), Database Systems (Coronel et al.), Database Systems (4/5) (Connolly et al. )

12

CS 338: Computer Applications in Business: Databases (Fall 2014)

The CREATE TABLE Command in SQL

25

The CREATE TABLE Command in SQL

26

1992-2014 by Addison Wesley & Pearson Education, Inc., McGraw Hill, Cengage Learning
Slides adapted and modified from Fundamentals of Database Systems (5/6) (Elmasri et al.), Database System
Concepts (5/6) (Silberschatz et al.), Database Systems (Coronel et al.), Database Systems (4/5) (Connolly et al. )

13

CS 338: Computer Applications in Business: Databases (Fall 2014)

The CREATE TABLE Command in SQL


Some foreign keys may cause errors
Specified either via:
Circular references

Example: Super_ssn in Employee refers to the table itself

Or because they refer to a table that has not yet been created
Example: Foreign key Dno in EMPLOYEE refers to
DEPARTMENT table which has not been created yet

Solution
Omit these initial constraints and add them
later using ALTER TABLE statement

27

Attribute Data Types and Domains in SQL


Basic data types
Numeric data types
Integer numbers: INTEGER, INT, and SMALLINT
Floating-point (real) numbers: FLOAT or REAL, and DOUBLE
PRECISION

Character-string data types


Fixed length: CHAR(n), CHARACTER(n)
Varying length: VARCHAR(n), CHAR VARYING(n), CHARACTER
VARYING(n)

Bit-string data types


Fixed length: BIT(n)
Varying length: BIT VARYING(n)
28

1992-2014 by Addison Wesley & Pearson Education, Inc., McGraw Hill, Cengage Learning
Slides adapted and modified from Fundamentals of Database Systems (5/6) (Elmasri et al.), Database System
Concepts (5/6) (Silberschatz et al.), Database Systems (Coronel et al.), Database Systems (4/5) (Connolly et al. )

14

CS 338: Computer Applications in Business: Databases (Fall 2014)

Attribute Data Types and Domains in SQL


Basic data types
.
.
.

Boolean data type


Values of TRUE or FALSE or NULL

DATE data type


Ten positions
Components are YEAR, MONTH, and DAY in the form YYYY-MM-DD

29

Attribute Data Types and Domains in SQL


Additional data types
Timestamp data type (TIMESTAMP)
Includes the DATE and TIME fields
Plus a minimum of six positions for decimal fractions of seconds
Optional WITH TIME ZONE qualifier

INTERVAL data type


Specifies a relative value that can be used to increment or
decrement an absolute value of a date, time, or timestamp

30

1992-2014 by Addison Wesley & Pearson Education, Inc., McGraw Hill, Cengage Learning
Slides adapted and modified from Fundamentals of Database Systems (5/6) (Elmasri et al.), Database System
Concepts (5/6) (Silberschatz et al.), Database Systems (Coronel et al.), Database Systems (4/5) (Connolly et al. )

15

CS 338: Computer Applications in Business: Databases (Fall 2014)

Attribute Data Types and Domains in SQL


It is possible to specify the data type of each attribute directly
(as in Figure 4.1)
Alternatively, a domain can be declared
Name used with the attribute specification
Makes it easier to change the data type for a domain that is
used by numerous attributes
Improves schema readability
Example: CREATE DOMAIN SSN_TYPE AS CHAR(9);

We can use SSN_TYPE in place of CHAR(9) in Figure 4.1


31

Specifying Constraints in SQL

32

1992-2014 by Addison Wesley & Pearson Education, Inc., McGraw Hill, Cengage Learning
Slides adapted and modified from Fundamentals of Database Systems (5/6) (Elmasri et al.), Database System
Concepts (5/6) (Silberschatz et al.), Database Systems (Coronel et al.), Database Systems (4/5) (Connolly et al. )

16

CS 338: Computer Applications in Business: Databases (Fall 2014)

Specifying Constraints in SQL


Basic constraints can be specified in SQL as part of the table
creation. These include:
Key and referential integrity constraints
Restrictions on attribute domains and NULLs
Constraints on individual tuples within a relation

33

Specifying Attribute Constraints


and Attribute Defaults
Attribute Constraints
Since SQL allows NULL as an attribute value, a constraint NOT
NULL may be specified
NOT NULL indicates that NULL is not permitted for a particular
attribute

Attribute Defaults
It is possible to specify a default value for an attribute by
appending the clause DEFAULT <value>

34

1992-2014 by Addison Wesley & Pearson Education, Inc., McGraw Hill, Cengage Learning
Slides adapted and modified from Fundamentals of Database Systems (5/6) (Elmasri et al.), Database System
Concepts (5/6) (Silberschatz et al.), Database Systems (Coronel et al.), Database Systems (4/5) (Connolly et al. )

17

CS 338: Computer Applications in Business: Databases (Fall 2014)

Specifying Attribute Constraints


and Attribute Defaults

35

Specifying Attribute Constraints


and Attribute Defaults
Restricting attribute or domain values
CHECK clause
Dnumber INT NOT NULL CHECK (Dnumber > 0 AND Dnumber < 21);

Example: Department numbers are restricted to integer


numbers between 1 and 20
CHECK clause can also be used with CREATE DOMAIN statement

CREATE DOMAIN D_NUM AS INTEGER


CHECK (D_NUM > 0 AND D)NUM < 21);

36

1992-2014 by Addison Wesley & Pearson Education, Inc., McGraw Hill, Cengage Learning
Slides adapted and modified from Fundamentals of Database Systems (5/6) (Elmasri et al.), Database System
Concepts (5/6) (Silberschatz et al.), Database Systems (Coronel et al.), Database Systems (4/5) (Connolly et al. )

18

CS 338: Computer Applications in Business: Databases (Fall 2014)

Specifying Key and Referential Integrity


Constraints
Keys and referential integrity constraints are very important

We use special clauses within the CREATE TABLE statement to specify


them

PRIMARY KEY clause


Specifies one or more attributes that make up the primary
key of a relation
Example: Dnumber INT PRIMARY KEY;

UNIQUE clause
Specifies alternate (secondary) keys
Example: Dname VARCHAR(15) UNIQUE;
37

Specifying Key and Referential Integrity


Constraints
Keys and referential integrity constraints are very important

We use special clauses within the CREATE TABLE statement to specify


them

FOREIGN KEY clause


Referential integrity constraints can be violated when tuples
are inserted or deleted, or when a foreign key or primary
key attribute value is modified
Default operation: reject update on violation
Can always specify an alternative action by attaching a
referential triggered action clause
Options include SET NULL, CASCADE, and SET
DEFAULT
38

1992-2014 by Addison Wesley & Pearson Education, Inc., McGraw Hill, Cengage Learning
Slides adapted and modified from Fundamentals of Database Systems (5/6) (Elmasri et al.), Database System
Concepts (5/6) (Silberschatz et al.), Database Systems (Coronel et al.), Database Systems (4/5) (Connolly et al. )

19

CS 338: Computer Applications in Business: Databases (Fall 2014)

Updating or Deleting Foreign Keys


Updating or deleting foreign keys

CREATE TABLE statement support ON DELETE and ON UPDATE


clauses

[ ON DELETE { NO ACTION | CASCADE | SET NULL | SET DEFAULT } ]


[ ON UPDATE { NO ACTION | CASCADE | SET NULL | SET DEFAULT } ]

ON DELETE NO ACTION
Specifies that if an attempt is made to delete a row with a key
referenced by foreign keys in existing rows in other tables, an error is
raised and the DELETE statement is rolled back

ON UPDATE NO ACTION
Specifies that if an attempt is made to update a key value in a row
whose key is referenced by foreign keys in existing rows in other
tables, an error is raised and the UPDATE statement is rolled back
39

Updating or Deleting Foreign Keys


.
.
.

ON DELETE CASCADE
Specifies that if an attempt is made to delete a row with a key
referenced by foreign keys in existing rows in other tables, all rows
that contain those foreign keys are also deleted

ON UPDATE CASCADE
Specifies that if an attempt is made to update a key value in a row,
where the key value is referenced by foreign keys in existing rows in
other tables, all the values that make up the foreign key are also
updated to the new value specified for the key
40

1992-2014 by Addison Wesley & Pearson Education, Inc., McGraw Hill, Cengage Learning
Slides adapted and modified from Fundamentals of Database Systems (5/6) (Elmasri et al.), Database System
Concepts (5/6) (Silberschatz et al.), Database Systems (Coronel et al.), Database Systems (4/5) (Connolly et al. )

20

CS 338: Computer Applications in Business: Databases (Fall 2014)

Updating or Deleting Foreign Keys


Example: Two Tables
Albums(AlbumID, Name)
Tracks(TrackID, Title, AlbumID, Duration)
Tracks.AlbumID references Albums.AlbumID
Specify two options:

ON DELETE SET NULL


ON UPDATE CASCADE

ON DELETE SET NULL


When a row is deleted from Albums, AlbumID will be set to NULL
for all matching rows in Tracks

ON UPDATE CASCADE
When an AlbumID is updated in Albums, the all matching rows for
AlbumID in Tracks will also have the updated AlbumID
41

Giving Names to Constraints


You can assign a name to any defined constraint following the
keyword CONSTRAINT
Example:
CREATE TABLE EMPLOYEE (
,
CONSTRAINT EMPPK
PRIMARY KEY (Ssn)
);

Constraint name must be unique


when to use: it is used to identify a particular constraint in
case it must be dropped or altered
42

1992-2014 by Addison Wesley & Pearson Education, Inc., McGraw Hill, Cengage Learning
Slides adapted and modified from Fundamentals of Database Systems (5/6) (Elmasri et al.), Database System
Concepts (5/6) (Silberschatz et al.), Database Systems (Coronel et al.), Database Systems (4/5) (Connolly et al. )

21

CS 338: Computer Applications in Business: Databases (Fall 2014)

Specifying Constraints on Tuples Using CHECK


In addition to key and referential constraints, other table
constraints can be specified using CHECK clauses at the end of
a CREATE TABLE statement
These are called tuple-based constraints
Apply to each tuple individually
Example
Add a new column called Dept_create_date which
stores the date when the department was created.
Add a CHECK clause to make sure that a managers start
date is later than the departments create date
CHECK (Dept_create_date <= Mgr_start_date);
43

Practice Question(s)
Do exercise 4.8 on page 112 (6th Edition)

44

1992-2014 by Addison Wesley & Pearson Education, Inc., McGraw Hill, Cengage Learning
Slides adapted and modified from Fundamentals of Database Systems (5/6) (Elmasri et al.), Database System
Concepts (5/6) (Silberschatz et al.), Database Systems (Coronel et al.), Database Systems (4/5) (Connolly et al. )

22

Potrebbero piacerti anche