05 basic sql

22
1 CS 338: Computer Applications in Business: Databases (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 Basic SQL DDL and Data Types, Specifying Constraints ©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. ) Rice University Data Center Fall 2014 Chapter 4 Announcements Assignment 1 Due Monday October 6 th , 2014 Solutions will be posted on midnight Lecture 4 Exercise Solutions posted LEARN Æ Content Æ Lecture 4 … 2

Upload: nathan-wilson

Post on 16-Jan-2016

222 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 05 Basic SQL

1

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

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

CS 338: Computer Applications in Business: Databases

Basic SQLDDL and Data Types, Specifying Constraints

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

Rice University Data Center

Fall 2014

Chapter 4

Announcements

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

• Lecture 4 Exercise• Solutions posted LEARN Æ Content Æ Lecture 4 …

2

Page 2: 05 Basic SQL

2

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

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

Questions & Review

3

Review Partial Schema…

4

Example of a partial schema:Example of a partial schema:

• A Students relation consists of the columns (attributes) named: sid, name, login, age, and gpa

• The column (or attribute) named sid has a domain namedstring. The set of values associated with domain string isthe set of all character strings

can be read as…can be read as…

Â

Page 3: 05 Basic SQL

3

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

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

Review Rows or Tuples…

Each row (tuple) has the same number of columns (or attributes) as the relation schema

5

Rows (or tuples): Rows (or tuples):

Â

Review relational database state/schemas…

a collection of relation states with distinct relation namesDB = {r1, r2, ..., rm} Æm is the number of relations

6

What is a relational database state?What is a relational database state?

Â

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

What is a relational database schemas?What is a relational database schemas?

Page 4: 05 Basic SQL

4

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

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

Review Preserving quality of database…

DBMS must prevent the entry of incorrect data to preserve the quality of the information stored

7

A database is only good as the data stored in it …A database is only good as the data stored in it …

Â

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

How?How?

Review Referential Constraints…

• 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

8

What is What is

Â

Using Foreign Keys

How to enforce data consistency in this case?How to enforce data consistency in this case?

Page 5: 05 Basic SQL

5

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

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

Review Terminologies…

9

Â

• 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 SQLDDL and Data Types, Specifying ConstraintsChapter 4

10

Â

Page 6: 05 Basic SQL

6

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

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

Basic SQL

• create the database and relation structures;

• perform insertion, modification, deletion of data from relations;

• perform simple and complex queries

Ideally, database language should allow users to:

11

• minimal user effort

• command structure/syntax must be easy to learn

Must perform these tasks with

It must be portable

Basic SQL

• SQL is a comprehensive database language

Structured Query Language (SQL)

12

• it is both a DDL and a DML

Has statements for data definitions, queries, andupdates

Has facilities for defining views on the database,security and authorization, defining integrityconstraints

Â

SQL is considered one of the major reasons for the commercial success of relational databases

Page 7: 05 Basic SQL

7

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

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

Basic SQL

• 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 is easy to learn …

13

Â

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

SQL can be used by a range of users …

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

An ISO standard exists …

Basic SQL

CREATE TABLE staff(id VARCHAR(5),lname VARCHAR(15),ssn NUMBER(7,2)

);

INSERT INTO staffVALUES ('SG16', 'Brown', 8300);

SELECT sno, lname, salaryFROM staffWHERE salary > 10000;

SQL consists of standard English words …

14

Â

Page 8: 05 Basic SQL

8

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

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

Basic SQL

15

Â

SQL standards are mainly divided into two parts:

• core SQL: a set of features that a vendor must implement to claim conformance with the SQL standard

core specification

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

specialized extensions

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 bespelled exactly as required and cannot split across lines

� user-defined words are made up by user and representnames of various database objects such as table, columns,views, etc…

� Most components of an SQL statement are caseinsensitive, except for literal character data

16

Page 9: 05 Basic SQL

9

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

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

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 therelationship

� 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 singlequotes (e.g. ‘London’)

� All numeric literals must not be enclosed in quotes(e.g. 650.00).

18

Â

Page 10: 05 Basic SQL

10

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

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

SQL Data Definition and Data Types

19

• Main SQL command for data definition

• Used to create

• schemas,

• tables (relations)

• views, assertions, and triggers

CREATE statement

SQL uses the terms table, row, and column for the formalrelational model terms relation, tuple, and attribute,respectively

Schema and Catalog Concepts in SQL

20

• 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

SQL schema

• CREATE SCHEMA statement• CREATE SCHEMA COMPANY AUTHORIZATION ‘Jsmith’;

Example

schema name authorization identifier

Page 11: 05 Basic SQL

11

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

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

SQL Data Definition Statements

21

• CREATE SCHEMA and DROP SCHEMA

• CREATE TABLE

• ALTER TABLE

• DROP TABLE

The CREATE TABLE Command in SQL

22

• 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

CREATE TABLE

• Attributes are specified first and each attribute is given:1. a name, 2. a data type (to specify its domain of values), and3. Attribute constraints (i.e. NOT NULL)

Attributes …

• 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

Initial constraints …

Page 12: 05 Basic SQL

12

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

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

The CREATE TABLE Command in SQL

23

1. SQL schema is implicitly specified in the environment in which the CREATE TABLE statements are executed

There are two methods for creating SQL Schema:

2. Explicitly attach the schema name to the relation name separated by a period

CREATE TABLE COMPANY.EMPLOYEE ...

Example

Â

The CREATE TABLE Command in SQL

24

• Different from Virtual relations

• Created through the CREATE VIEW statement

• May or may not correspond to an actual physical file

• Relations declared through CREATE TABLE statement arecalled base tables (or base relations)• relation and its tuples are actually created and stored as

a file by the DBMS

Â

Page 13: 05 Basic SQL

13

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

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

The CREATE TABLE Command in SQL

25

Â

The CREATE TABLE Command in SQL

26

Â

Page 14: 05 Basic SQL

14

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

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

The CREATE TABLE Command in SQL

27

• 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

Some foreign keys may cause errors

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

Solution

Â

Attribute Data Types and Domains in SQL

28

Basic data types

• Integer numbers: INTEGER, INT, and SMALLINT• Floating-point (real) numbers: FLOAT or REAL, and DOUBLE

PRECISION

Numeric data types

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

VARYING(n)

Character-string data types

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

Bit-string data types

Page 15: 05 Basic SQL

15

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

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

Attribute Data Types and Domains in SQL

29

Basic data types

• Values of TRUE or FALSE or NULL

Boolean data type

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

DATE data type

Â

.

.

.

30

Additional data types

• Includes the DATE and TIME fields• Plus a minimum of six positions for decimal fractions of seconds• Optional WITH TIME ZONE qualifier

Timestamp data type (TIMESTAMP)

Attribute Data Types and Domains in SQLÂ

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

INTERVAL data type

Page 16: 05 Basic SQL

16

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

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

Attribute Data Types and Domains in SQL

31

• 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

Alternatively, a domain can be declared

It is possible to specify the data type of each attribute directly(as in Figure 4.1)

Â

Specifying Constraints in SQL

32

Page 17: 05 Basic SQL

17

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

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

Specifying Constraints in SQL

33

Basic constraints can be specified in SQL as part of the tablecreation. These include:

• Key and referential integrity constraints

• Restrictions on attribute domains and NULLs

• Constraints on individual tuples within a relation

Specifying Attribute Constraintsand Attribute Defaults

34

• 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 Constraints

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

Attribute Defaults

Page 18: 05 Basic SQL

18

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

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

Specifying Attribute Constraintsand Attribute Defaults

35

Â

Specifying Attribute Constraintsand Attribute Defaults

36

• 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);

Restricting attribute or domain values

Page 19: 05 Basic SQL

19

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

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

Specifying Key and Referential Integrity Constraints

37

• Specifies one or more attributes that make up the primary key of a relation

• Example: Dnumber INT PRIMARY KEY;

PRIMARY KEY clause

Keys and referential integrity constraints are very important• We use special clauses within the CREATE TABLE statement to specify

them

• Specifies alternate (secondary) keys

• Example: Dname VARCHAR(15) UNIQUE;

UNIQUE clause

Specifying Key and Referential Integrity Constraints

38

• 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

FOREIGN KEY clause

Keys and referential integrity constraints are very important• We use special clauses within the CREATE TABLE statement to specify

them

Â

Nathan Wilson
Page 20: 05 Basic SQL

20

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

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

Updating or Deleting Foreign Keys

39

Specifies that if an attempt is made to delete a row with a keyreferenced by foreign keys in existing rows in other tables, an error israised and the DELETE statement is rolled back

ON DELETE NO ACTION

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 } ]

Specifies that if an attempt is made to update a key value in a rowwhose key is referenced by foreign keys in existing rows in othertables, an error is raised and the UPDATE statement is rolled back

ON UPDATE NO ACTION

Updating or Deleting Foreign Keys

40

Specifies that if an attempt is made to delete a row with a keyreferenced by foreign keys in existing rows in other tables, all rowsthat contain those foreign keys are also deleted

ON DELETE 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 inother tables, all the values that make up the foreign key are alsoupdated to the new value specified for the key

ON UPDATE CASCADE

Â

.

.

.

Page 21: 05 Basic SQL

21

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

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

Updating or Deleting Foreign Keys

41

Æ Albums(AlbumID, Name)Æ Tracks(TrackID, Title, AlbumID, Duration)

• Tracks.AlbumID references Albums.AlbumID• Specify two options:

• ON DELETE SET NULL• ON UPDATE CASCADE

Example: Two Tables

Â

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

ON DELETE SET NULL

When an AlbumID is updated in Albums, the all matching rows forAlbumID in Tracks will also have the updated AlbumID

ON UPDATE CASCADE

Giving Names to Constraints

42

You can assign a name to any defined constraint following thekeyword CONSTRAINT

Example:CREATE TABLE EMPLOYEE (

…,CONSTRAINT EMPPKPRIMARY KEY (Ssn)

);• Constraint name must be unique

• when to use: it is used to identify a particular constraint incase it must be dropped or altered

Page 22: 05 Basic SQL

22

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

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

Specifying Constraints on Tuples Using CHECK

43

In addition to key and referential constraints, other tableconstraints can be specified using CHECK clauses at the end ofa CREATE TABLE statement• These are called tuple-based constraints

• Apply to each tuple individually

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 manager’s start

date is later than the department’s create date• CHECK (Dept_create_date <= Mgr_start_date);

Example

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

44