+ All Categories
Home > Documents > Introduction to Relational Database and SQL Minder Chen CSU Channel Islands [email protected].

Introduction to Relational Database and SQL Minder Chen CSU Channel Islands [email protected].

Date post: 11-Jan-2016
Category:
Upload: florence-reed
View: 225 times
Download: 1 times
Share this document with a friend
152
Introduction to Relational Database and SQL Minder Chen CSU Channel Islands [email protected]
Transcript
Page 1: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

Introduction to Relational Database and SQL

Minder Chen

CSU Channel Islands

[email protected]

Page 2: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 2 ©Minder Chen, 1996-2011

What is a RDBMS?

• A Data Base (DB) is an integrated collection of shared data designed to meet the varied information needs of an organization.

• A Data Base Management System (DBMS) consists of a collection of software program that receives and satisfies all requests for data.

• A Relational Data Base Management System (RDBMS) is a DBMS which processes data with the Relational Data Model.

Page 3: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 3 ©Minder Chen, 1996-2011

History of RDBMS• The relational database model was originally developed

by Dr. E.F. Codd in the early 1970s

• The SQL language was originally developed by IBM in a prototype relational database management system, System R, in the mid 1970s.

• The original SQL language (SEQUEL 2) was described in IBM Journal of R&D, November 1976.

• In 1979, Oracle Corporation introduced the first commercially available implementation of SQL.

• SQL has also been implemented in IBM's DB2 and SQL/DS database systems in the mid 1980s.

• Today SQL is widely implemented and is accepted as the industry standard database access language.

Page 4: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 4 ©Minder Chen, 1996-2011

Database Technology

Before Relational systems people has been using:Before Relational systems people has been using:

- File Systems like ISAM, VSAM and B-Tree;- File Systems like ISAM, VSAM and B-Tree;

- Hierarchy Database;- Hierarchy Database;

- Network Database.- Network Database.

RDBMS has both a physical and a logical structure. By RDBMS has both a physical and a logical structure. By doing so, the physical storage of data can be managed doing so, the physical storage of data can be managed without affecting the access to logical storage without affecting the access to logical storage structures.structures.

File Systems Hierarchy Network Relational

Page 5: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 5 ©Minder Chen, 1996-2011

Relational Database Introduction

• A relational data base is perceived by its users as a collection of tables

• Invented by E. F. Codd in 1969

• Dominate the markets since late 1980s

• Strengths: – Simplicity

– End-user orientation

– Standardization (SQL – Structured Query Language)

– Value-based instead of pointer-based to provide data independence

– Endorsed by major computer companies

• Most CASE products support the development of relational data base centered applications

Page 6: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 6 ©Minder Chen, 1996-2011

SQL Terminology

p_no name quantityprice

101 Color TV 24500

201 B&W TV 10250

202 PC 52000

Product Table

Product Table

Row

Column

Set Theory Relational DB File ExampleRelation Table File Product_tableAttribute Column Data item Product_nameTuple Row Record Product_101's info.Domain Data Type Data type DATE

or Domain

Page 7: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 7 ©Minder Chen, 1996-2011

SQL Terminology CREATE TABLE PRODUCT

(p_no CHAR(5) NOT NULL, name CHAR(20), quantity SMALLINT, price DECIMAL(10, 2));

INSERT INTO PRODUCT VALUES (101, 'Color TV', 24, 500);

INSERT INTO PRODUCT VALUES (201, 'B&W TV ', 24, 500);

INSERT INTO PRODUCT VALUES (202, 'PC', 5, 2000);

SELECT p_no, name, price

FROM PRODUCT WHERE PRICE > = 1000;

p_no name price--------- ----------- ----------202 PC 2000

CREATE TABLE PRODUCT(p_no CHAR(5) NOT NULL, Name CHAR(20), Quantity INTEGER, Price Currency, CONSTRAINT pk_productPRIMARY KEY (p_no));

In Access In Access

Page 8: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 8 ©Minder Chen, 1996-2011

SQL: Data Manipulation Language (DML)

SELECT UPDATE INSERTDELETE

SELECT UPDATE INSERTDELETE

p_no name quantity price

101 Color TV 24 500

201 B&W TV 10 250

202 PC 5 2000

SELECT p_no, name, price

FROM PRODUCT

WHERE PRICE < = 1000

ORDER BY PRICE DESC;

p_no name price

------- -------------------------

101 Color TV 500

201 B&W TV 250

Page 9: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 9 ©Minder Chen, 1996-2011

SQL Principles• The result of a SQL query is always in a table like format

and is not stored (View or Dynamic Table). The definition of a query can be stored.

• Rows in a table are considered to be unordered.

• Columns sequence in a table is irrelevant in your database queries.

• Can be used in interactive programming environments.

• Provide both data definition language (DDL), data manipulation language (DML), and data control language (DCL).

• It is a non-procedural language.

• Can be embedded in 3GL (third generation languages), such as C, COBOL, etc.:

– Embedded SQL: Embedding SQL statements in host languages.

– Dynamic SQL: Constructing SQL statements dynamically.

Page 10: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 10 ©Minder Chen, 1996-2011

Database Application in the Client/Server Environments

Customer Management

Name: John DoeAddress: 101 Dalmation Street Salary: $43,000 Age: 34

PF1 - Help PF2 - Add PF3 - Update

File Edit Window HelpCustomer Management

Name:

Address:

Salary:

John Doe

101 Dalmation St.

$48,000

CancelLoan History Update

Age: 34

CUI client

GUI client

Database Server

Disks & Files

Enter details and press PF3 to update

Networks

Page 11: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 11 ©Minder Chen, 1996-2011

Database Server in the Client-Server Architecture

User File Server

ClientApplication

DatabaseServer

2 3

45

1. User enters query through client application's user interface.

2. Client application sends the formulated query to the data base server.

3. Database server processes request. Search all records.

4. Database server returns only the results from the query.

5. Client application's user interface displays retrieved information.

MechanismMechanism: SQL via SQL*Net, ODBC, Stored Procedures, Remote Procedure Calls

Access is not a database server.

3

Client Machine Server Machine

1

Page 12: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 12 ©Minder Chen, 1996-2011

Data

Software Layers Using Oracle as Example

Operating Systems

Oracle Server

SQLPL/SQL

Developer/2000 (Forms, Reports, Graphics)

SQL*Plus

Custom-build Oracle Database Applications

JDeveloper Procedure Builder

Visual Web DeveloperVisual Studio .NET

Designer/2000

Page 13: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

Indices Statistical data

Data files

Transaction manager

Buffer manager

File manager

Application programs

object code Query evaluation

engine

EmbeddedDML

precompiler

DMLprecompiler

DDLinterpreter

Application interface 3GL & 4GL Query

toolsDatabase schema

Naïve users (tellers, agents,etc)

Application programmers

Sophisticated users

Database Administrator

Query processor

Storage manager

Disk storage

DBMS

Users

• 3GL: Third Generation Languages such as C and COBOL

• 4GL: Fourth Generation Language such as Visual Basic and PowerBuilder Data dictionary

Page 14: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 14 ©Minder Chen, 1996-2011

Database StructuresThe database structures should be understood in different The database structures should be understood in different

views at different stages or for different viewers. In 1974, views at different stages or for different viewers. In 1974, the following conceptual framework was introduced in a the following conceptual framework was introduced in a conference at New Orleans city, so called New Orleans conference at New Orleans city, so called New Orleans Schema. It is also known as ANSI/X3/SPARC DBMS Schema. It is also known as ANSI/X3/SPARC DBMS Framework. Framework.

ConceptualSchema

ApplicationSchema 1

ApplicationSchema N

Logical Schema

Physical Schema

Logical Database

Physical Database

e. g., E-R Diagram

External level(Individual User View)

Conceptual View(Community User View)

Internal Level(Storage View) * E-R Diagram: Entity Relationship Diagram

Page 15: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 15 ©Minder Chen, 1996-2011

Benefits of RDBMS• Integration of Data: Data are organized into a single, logical

structure with logical relationships defined between associated data entities to eliminate redundancy and inconsistency.

• Sharing of Data: All qualified users in the organization have access to the same data, for use in a variety of activities or applications.

• Enforcement of Standards: Centralized data administration function has authority for defining and enforcing data standards. All changes to the data standards would have to be approved by the Database Administrator.

• Ease of Application Development: An end user/ programmer is no longer saddled with the burden of designing, building and maintaining traditional master files.

Page 16: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 16 ©Minder Chen, 1996-2011

Benefits of RDBMS• Uniform Security, Privacy and Integrity Controls: The

data administration function has complete jurisdiction over the database and is responsible for establishing controls for accessing, updating and protection data. Centralized control and standard procedures can offer improved level of data base protection.

• Data Accessibility and Responsiveness: Provides multiple retrieval paths to each item of data, giving a user much greater flexibility in locating and retrieving data. A database system is generally much more responsive to changing information requirements.

• Data Independence: The separation of data descriptions from application programs that use the data.

Page 17: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 17 ©Minder Chen, 1996-2011

Benefits of RDBMS• Reduce Program Maintenance: Due to the data

independence in a database system, within limits, either the data or the application program that use the data can be changed without necessitating a change in the others.

• User Friendly: SQL is a non-procedural easy-to-learn language. It allows you to work with higher level data structures. Rather than manipulating single rows. A user can gets the desired data simply by specifying SQL without go through complex procedure programming language.

• Supported by Mathematics Theory: RDBMS is the only DBMS that is supported by mathematics theory. The relational algebra is formed by a set of operators, each of which maps one or more relations into another relation.

Page 18: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 18 ©Minder Chen, 1996-2011

The Relational Model• A model represents both entities and relationships in a

flat file (table) structure.

• Relation: A mathematical concept about an entity or a relationship.

• Properties of a Relation:

- No duplicate rows in a relation (table).

- The order of rows in a relation is insignificant

- The order of columns in a relation is insignificant.

- All attributes must be atomic (single value).

- Each row must be uniquely identified by a primary key.

• In the relational model, data are logically presented in two dimensional tables (files) made up of rows (tuples, records) and columns (attributes, fields, data item).

Page 19: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 19 ©Minder Chen, 1996-2011

The Relational Model• Table: A table is a group of homogeneously

defined records, all with identical field names and types. Within a database, each table has a unique name.

• Row: The rows of a table are known as records. They are made up of a collection of values that describe an entity.

• Field: A field is the intersection of a row and a column in a table or query result.

• Key: An attribute or a set of attributes which can uniquely identify a row in a table.

Page 20: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 20 ©Minder Chen, 1996-2011

The Relational ModelDIVISION

INSTRUCTOR

PK

PK

FK

Page 21: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 21 ©Minder Chen, 1996-2011

The Relational Model• Primary Key: A key chosen to identify the rows in

a table.

• Simple Key: A key contains only one column.

• Compound(Composite, Concatenated) Key: A key has more than one column.

• Alternate Key: A key which is other than the primary key in a relation.

• Foreign Key: An attribute or a set of attributes appears in a table which also plays the role of a primary key in another tables.

• Question: What is the trick to implement relationships in the relational model?

Page 22: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 22 ©Minder Chen, 1996-2011

The Relational Model• Index: An index is a data structure used to speed up data

retrieval or enforce certain constraints on the records in a table. Relational databases use automatic query optimization algorithms to determine which indices to use when searching the database, therefore the user does not specify which indices to use in a search.

• Null value: A null value is an empty or undefined value for a field. It indicates that there is presently no data available for the field instance.

• View: A view is a logic representation of another table or combination of tables. A view derives its data from the tables on which it is based. Views permit you to query subsets of data, or joins of multiple tables as though they are an actual table. Only the view definition is stored in the database, not the data retrieved by a view. Some views are updateable; update commands actually affect the underlying table. View is called (stored) Query in Access.

Page 23: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 23 ©Minder Chen, 1996-2011

The Relational Model•Referential Integrity: The relationship between a referencing (child) table and a referenced (parent) table. The referential integrity rule requires that, for any value in the referencing columns, there must exist a row in the referenced table such that the value of the referencing columns equals the value of the corresponding referenced columns.

•Essence of a Relational Data Model:– Representation of Entities– Representation of Relationship– Database Integrity Rules:

» Primary Key Rule» Referential Integrity Rule» Existing Rule (NOT NULL)» Value Checking Rule

– DB Languages: DDL, DML, DCL

Page 24: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 24 ©Minder Chen, 1996-2011

Foreign Keys & Primary Keys in a Sample Database (ACCESS)

Page 25: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 25 ©Minder Chen, 1996-2011

SQL Programming

• SQL is a standard language used to define and manipulate data in a RDBMS, and can be used interactively or embedded in host languages such as C, PASCAL, COBOL, etc. SQL generally functions on sets of records rather than individual records. References to data are symbolic; they do not use any physical data structures such as pointers.

• SQL are divided into three sublanguages:– DDL (Data Definition Language)

– DML (Data Manipulation Language)

– DCL (Data Control Language)

Page 26: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 26 ©Minder Chen, 1996-2011

SQL Programming

• Data Definition Language (DDL) – Create, alter and drop database and database objects

– Impose integrity constraints on tables

– Automatically update system catalog tables

– Add comments to the tables.

• Data Manipulate Language (DML)– Retrieve,

– insert,

– update, and

– delete rows from database tables.

• Data Control Language (DCL)– Grant and Revoke privileges and roles

– Controls concurrent access to database.

Page 27: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 27 ©Minder Chen, 1996-2011

CREATE TABLE

CREATE TABLE division

(D_ID CHAR(4) NOT NULL,

DIR NUMBER(4),

DIV_NAME VARCHAR(15) NOT NULL,

CONSTRAINT pk_division

PRIMARY KEY (D_ID));

Table name

Primary Key Column(s)

Data Type

Mandatory or Optional

* The Primary Key column(s) of a table should be "NOT NULL"

A Constraint Name

A Constraint Type

Page 28: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 28 ©Minder Chen, 1996-2011

Create a Table in Access

CREATE TABLE division2(D_ID CHAR(4) NOT NULL, DIR Integer, DIV_NAME VARCHAR(15) NOT NULL,

CONSTRAINT pk_division PRIMARY KEY (D_ID));

What is AutoNumber in Access?

Page 29: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 29 ©Minder Chen, 1996-2011

Basic ElementsCharacter Set

– The upper- and lower-case letters A .. Z, a .. z

– The numerals 0 .. 9

– Tabs, spaces, and carriage returns

– The symbols ( ) + - * / < > = ! ~ ; : . ' @ % , " # $ ^ & | _ { } ? [ ]

Identifiers An identifier consists of a letter optionally followed by more letters, numerals and the special characters ‘#’, ‘$’ , ‘_’, ‘%’, ‘&’.

Comments– Single-line comments begin with a double hyphen (--)

anywhere on a line and extend to the end of the line.

– Multiline comments begin with a slash-asterisk (/*), end with an asterisk-slash (*/), and can span multiple lines.

Page 30: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 30 ©Minder Chen, 1996-2011

Data Types

• Every constant and variable has a data type, which specifies a storage format, constraints, and valid range of values.

– NUMBER: General numeric type. – DEC(p,s): Decimal value. Precision(p) is the total

number of digits. Scale(s) is the number of fractional digits. E.g., 9999.99 should be declared as DEC(6,2)

– FLOAT: Single precision floating-point number.– SMALLINT: Half word (2 bytes) binary integer. Value

can range from -32767 to 32767.– INT: Full word(4 bytes) binary integer. Value can range

from -2147483647 to 2147483647.– CHAR: Fixed length character string. – VARCHAR: Variable length character string. – DATE: Data stored in Gregorian date format.

Page 31: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 31 ©Minder Chen, 1996-2011

NULL

DATA ELEMENT CHARACTERISTIC

A B C

NOT NULLmust be a given value,

including blank or zero.

NULLValue not required.

(Column flagged null -- “empty value”)

NOT NULL WITH DEFAULTwill provide default value if one

is not entered.

Page 32: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 32 ©Minder Chen, 1996-2011

NULLNOTE: In SQL, NULL is an empty value, it is not

equal to blank or space. Be aware of the results when use NULL in:

– COMPARISON: Result is unknown

– COMPUTATION: Result is unknown

– FUNCTIONS: Null rows are omitted from AVG, SUM, MAX and MIN functions.

– COUNT(DISTINCT): Does not count NULLS.

Page 33: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 33 ©Minder Chen, 1996-2011

OperatorsLogical negation: NOT Identity: +Negation: - Multiplication: *Division: / Addition: +Subtraction: -Concatenation: ||Comparison: =, !=, <, >, <=, >= ,

IS NULL, LIKE, BETWEEN, IN, EXIST,ALL, SOME, ANY

Conjunction: AND Inclusion: OR

Page 34: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 34 ©Minder Chen, 1996-2011

PRIMARY KEY

• A PRIMARY KEY constraint is identical to a UNIQUE constraint, except that a table can have at most one constraint condition specified as a PRIMARY KEY. The purpose of the primary key is to uniquely identify each row of a table.

• The fields in the primary key must be defined as NOT NULL. A unique index will be built automatically by RDBMS on the primary key.

Page 35: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 35 ©Minder Chen, 1996-2011

FOREIGN KEY• FOREIGN KEY is used to enforce referential integrity -- the

relationship between referencing (child) table and a referenced (parent) table.

• The referential integrity rule requires that, for any value in the referencing columns, there must exist a row in the referenced table such that the value of the referencing columns equals the value of the corresponding referenced columns.

• This is enforced as the following:– UPDATE/INSERT Rule: The set of values placed in the referencing

columns must match a set of values that exists in the referenced table.

– DELETE Rules (When you delete rows of the referenced table): » RESTRICT: The row in referenced table can be deleted if no other row

referencing it.» SET NULL: That each nullable column of the matched foreign key in each

referencing row is set to null. » CASCADE: The designated rows in the referenced table and all match

referencing rows will be deleted.

Page 36: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 36 ©Minder Chen, 1996-2011

FOREIGN KEY• In order to create a referential integrity constraint, you must

create a FOREIGN KEY constraint on the referencing table. The FOREIGN KEY constraint must reference the PRIMARY (or a UNIQUE) KEY on the referenced table.

alter table OFFERINGadd constraint FK_OFFERING_OFFERS_FOR_COURSES foreign key (C_ID)references COURSE (C_ID) ON DELETE CASCADE;

• The foreign key must reference an existing UNIQUE or PRIMARY KEY. An index will be built on the referencing columns.

create index Offers_for_Courses_FK on OFFERING (C_ID asc)

Referenced table

PK in the Referenced table

Column name(s) of the referencing table

Referencing table

Page 37: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 37 ©Minder Chen, 1996-2011

Sample Database

C_IDP,F

O_NOP,F

S_NOP,F

GRADE

REGISTRATION

C_IDP,F

O_NOP

START_DATELOCATIONI_NOF

OFFERING

C_IDP

TITLEDIVF

FEE

COURSE

I_NOP

F_NAMEM

L_NAMEDIVF

D_O_HTITLE

EDSEX

D_O_BSALARY

INSTRUCTOR

D_IDP

DIRF

DIV_NAME

DIVISIONS_NOP

NAMEADDRESS

CITYSTATE

ZIPTEL_NO

STUDENT

Page 38: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 38 ©Minder Chen, 1996-2011

Relationships in Access Database

Page 39: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 39 ©Minder Chen, 1996-2011

Edit Relationships in Access

• Referential Integrity

Page 40: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 40 ©Minder Chen, 1996-2011

DDL

• CREATE DATABASE: Creates a database.

• CREATE TABLE: Creates a table and defines its columns and their data types.

• CREATE SYNONYM: Creates an alternate name for a table or view.

• CREATE VIEW: Defines a logical table, or view of data derived from columns and rows of existing tables and views.

• CREATE INDEX: Creates an index on one or more columns of a table, for the purpose of speeding data retrieval, and enforcing uniqueness constraints.

• ALTER: Adds, removes or renames table columns, or changes the data types of columns. Also used to create or drop UNIQUE, PRIMARY, FOREIGN KEY and CHECK constraints to enforce uniqueness, referential integrity.

Page 41: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 41 ©Minder Chen, 1996-2011

DDL

• DROP DATABASE: Deletes database and all objects associated with it.

• DROP TABLE: Deletes a table and the indexes built on that table.

• DROP SYNONYM: Deletes an alternate name for a table or view from the system catalog.

• DROP VIEW: Deletes a view from the system catalog.

• DROP INDEX: Deletes a specified index. Note that an index created as the result of a UNIQUE, PRIMARY or FOREIGN KEY constraint can only be dropped by dropping the constraint through the ALTER command.

• RENAME: Changes a table name.

• COMMENT ON: Places a remark on a database object in the appropriate system catalog table.

Page 42: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 42 ©Minder Chen, 1996-2011

DML

• SELECT: Retrieves data from one or more tables.

• UPDATE: Modifies the data in one or more rows of a table.

• INSERT: Inserts one or more rows into a table.

• DELETE: Deletes one or more rows from a table.

Page 43: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 43 ©Minder Chen, 1996-2011

DCL

• COMMIT: Instructs the system to make all DML commands executed by a transaction permanent.

• ROLLBACK: Instructs the system to reverse all DML commands executed by a transaction.

• GRANT: Assigns database access privileges to database users.

• REVOKE: Cancels database access privileges from database users.

• LOCK: Permits users to explicitly acquire table locks.

• UNLOCK: Used to unlock a table prior to the commit point.

Page 44: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 44 ©Minder Chen, 1996-2011

CREATE TABLE: Data Type in AccessCREATE TABLE STUDENT

(S_NO NUMBER(4) NOT NULL,

NAME VARCHAR(10),

ADDRESS VARCHAR(10),

CITY VARCHAR(10),

STATE VARCHAR(2),

ZIP NUMBER(5),

TEL_NO VARCHAR(10),

CONSTRAINT S_NO_ZERO

CHECK (S_NO > 0),

CONSTRAINT

STUDENT_PRIMARY_KEY

PRIMARY KEY (S_NO));

NOTE:

The fields in the primary key must be defined as NOT NULL.

Page 45: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 45 ©Minder Chen, 1996-2011

CREATE TABLECREATE TABLE INSTRUCTOR

(I_NO NUMBER(4) NOT NULL,F_NAME VARCHAR(8) NOT NULL,

M CHAR(1) NOT NULL, L_NAME VARCHAR(5) NOT NULL,

DIV CHAR(4),TEL VARCHAR(10),D_O_H DATE,TITLE VARCHAR(8),

ED SMALLINT, SEX CHAR(1), D_O_B DATE, SALARY DECIMAL(9,2),

CONSTRAINT INSTRUCT_FOREIGN_KEYFOREIGN KEY (DIV)REFERENCES DIVISION(D_ID),

CONSTRAINT INSTRUCT_PRIMARY_KEYPRIMARY KEY (I_NO));

Page 46: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 46 ©Minder Chen, 1996-2011

CREATE TABLECREATE TABLE COURSE

( C_ID CHAR(4) NOT NULL,

TITLE VARCHAR(10) NOT NULL,

DIV CHAR(4) NOT NULL,

FEE DECIMAL(5,2),

CONSTRAINT COURSE_FOREIGN_KEY

FOREIGN KEY (DIV)

REFERENCES DIVISION(D_ID),

CONSTRAINT COURSE_PRIMARY_KEY

PRIMARY KEY (C_ID));

Page 47: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 47 ©Minder Chen, 1996-2011

CREATE TABLECREATE TABLE OFFERING

(C_ID CHAR(4) NOT NULL,

O_NO NUMBER(4) NOT NULL,

START_DATEDATE NOT NULL,

LOCATION VARCHAR(12),

CONSTRAINT OFFERING_FOREIGN_KEY

FOREIGN KEY (C_ID)

REFERENCES COURSE(C_ID)

ON DELETE CASCADE, CONSTRAINT OFFERING_PRIMARY_KEY

PRIMARY KEY (C_ID, O_NO));

Page 48: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 48 ©Minder Chen, 1996-2011

CREATE TABLECREATE TABLE REGISTRATION

(C_ID CHAR(4) NOT NULL, O_NO NUMBER(4) NOT NULL, S_NO NUMBER(4) NOT NULL, GRADE SMALLINT,

CONSTRAINT REGISTRATION_FOREIGN_KEYFOREIGN KEY (C_ID,O_NO)REFERENCES OFFERING(C_ID,

O_NO)ON DELETE CASCADE,

CONSTRAINT STUDENT_FOREIGN_KEY FOREIGN KEY (S_NO)REFERENCES STUDENT(S_NO),

CONSTRAINT REGISTRATION_PRIMARY_KEYPRIMARY KEY (C_ID, O_NO, S_NO));

Page 49: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 49 ©Minder Chen, 1996-2011

Create IndexThis command creates an index on one or more columns of a table.

TYPE OF INDEXES– UNIQUE INDEX: An index built on a unique columns (or

columns) in a table.

– NON-UNIQUE INDEX: An index built on a columns (or columns) which may have the same value in more than one row.

EXAMPLE CREATE UNIQUE INDEX DIVISION_NAME

ON DIVISION(DIV_NAME ASC);

CREATE INDEX LOC_INDEX

ON OFFERING(LOCATION DESC);

Page 50: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 50 ©Minder Chen, 1996-2011

Create ViewThis command is used to define a view (a logical or virtual table) based on one or more (base) tables or views. In Access, views are saved queries. CREATE VIEW TEACHER AS

SELECT I_NO, F_NAME, L_NAME, TITLE, SALARYFROM INSTRUCTOR

WHERE TITLE = 'TEACHER';

SELECT * FROM TEACHER;

I_NO F_NAME L_NAM TITLE SALARY--------- -------- ----- -------- --------- 19 ALBERT STONE TEACHER 60000 21 BRUCE FLYNN TEACHER 48000

Page 51: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 51 ©Minder Chen, 1996-2011

Using a View

Query against a saved query

SELECT * FROM TEACHER

WHERE SALARY >= 50000;

I_NO F_NAME L_NAM TITLE SALARY--------- -------- ----- -------- --------- 19 ALBERT STONE TEACHER 60000The query is merged with the defining query of the view

TEACHER to produce the following query to be executed by the DBMS:

SELECT I_NO, F_NAME, L_NAME, TITLE, SALARYFROM INSTRUCTOR

WHERE TITLE = 'TEACHER' and SALARY >= 50000;DROP VIEW TEACHER; - - Delete the view

Page 52: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 52 ©Minder Chen, 1996-2011

Create View• Define a subset of a single table.• Combine data from two or more tables.• The data presented via the view is retrieved

dynamically from the base table.• Restrictions:

– ORDER BY and UNION can not be used in the definition of a view.

– A view is "read only" if its definition involves» A JOIN» The keyword DISTINCT» A GROUP BY clause» A HAVING clause» A function

– If you insert a row into a view, the base table columns that are not in the view must allow NULLs or set to default values.

Page 53: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 53 ©Minder Chen, 1996-2011

PROCESS VIEW BASE TABLE

SELECT

UPDATECOLUMN

DELETEROW

INSERTROW

Processing A View

?NULL or default value

Page 54: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 54 ©Minder Chen, 1996-2011

Access DMBS: DMBS vs Database

Page 55: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 55 ©Minder Chen, 1996-2011

Basic Structures and Contents of a Database

• Database Schema (Meta Data)

– Tables» Columns

• Column Name

• Data Types and Size

• Primary key

– Relationships» Foreign Keys

– Indexes

• Actual data stored in the Database

Page 56: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 56 ©Minder Chen, 1996-2011

Table

Query(View)

Form Report

Database Application

Basic Database Objects

Relationships among Access Database Objects

• A saved SELECT query is officially called View in SQL. • QUERY in Access can be SELECT, INSERT, UPDATE, or

DELETE. • You can create a query against a table or a query.• You can create a form or report against a table or a query.

Page 57: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 57 ©Minder Chen, 1996-2011

Stakeholders of a Database Environment

Application ProgrammersApplication Programmers

Advanced Advanced UsersUsers

Database Query/ReportingTools

DBA: DBA: DatabaseDatabaseAdministratorAdministrator

Internal End UsersInternal End Users

Internal End UsersInternal End Users

External End UsersExternal End Users

Database Designer Database Designer

E-commerceWeb site

Page 58: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 58 ©Minder Chen, 1996-2011

Query• Four types of operations against data in a

database– CRUD: Create, Read, Update, Delete

– SQL Data Manipulation Language (MDL):

» Insert, Select, Update, Delete

• Select statement allows you to retrieve data from the database (read only). It is also referred to as a query in Access.

• A definition of a query (not the query result) written in SQL statement can be saved in the database to be run later.

• A saved query is called “View” in SQL and you can created a query against a saved query (view)

Page 59: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 59 ©Minder Chen, 1996-2011

SELECT

• The SELECT command is a versatile and powerful command used to retrieve information from the database. SELECT commands may be executed alone, or embedded in CREATE, UPDATE, INSERT and DELETE commands.

• The SELECT command is composed of 8 clauses:

SELECT [DISTINCT | ALL ] projection list FROM table or view list [WHERE search condition ] [GROUP BY column list] [HAVING search condition] [ORDER BY {expr|position} [ ASC|DESC]] [FOR UPDATE OF column list]*

[INTO host variable list]*

Page 60: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 60 ©Minder Chen, 1996-2011

SELECT

• The SELECT clause and the FROM clause are required for all SELECT commands.

• THE WHERE clauses are permitted in all SELECT commands as a filter defining the criteria of rows to be selected.

• The WHERE clause of a subquery (i.e., subselect) may also contain nested subquery.

• Subquery cannot contain the UNION operator or an ORDER BY clause.

Page 61: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 61 ©Minder Chen, 1996-2011

Create a new query: Choose Create > Query Design

Highlight a table or a query, click Add; orDouble click on a table or a query.You may select more than one table when performing SQL JOIN

Page 62: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 62 ©Minder Chen, 1996-2011

Select Columns

• Field: Double click a column from the table to select it to the query design form column, or drag and drop it to the form (columns listed in the SQL SELECT clause);

• Table: A table or query from the database (SQL FROM Clause)

• Sort: Sorting the query result (SQL ORDER BY clause)

• Show: Whether to display the column’s value in the query result

• Criteria: Define criteria (filter) for rows in a table (SQL WHERE clause)

You may select a column and use it in a criteria or for sorting without show it’s value in the query result.

Page 63: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 63 ©Minder Chen, 1996-2011

SELECT COURSE.C_ID, COURSE.TITLE, COURSE.FEE

FROM COURSE

WHERE COURSE.FEE>250 And COURSE.FEE)<=350

ORDER BY COURSE.FEE DESC;

SQL Select and Query Design in Access

Page 64: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 64 ©Minder Chen, 1996-2011

Choose Design tab control under Query Tools. Click on View (not the Icon above it) from the Toolbar:

•Datasheet: See the result of the query, i.e., RUN the query•SQL View: Edit SQL statement directly•Design view: Create SQL via Query Design tool.

Page 65: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 65 ©Minder Chen, 1996-2011

SELECTSelecting All Columns:

EXAMPLE

SELECT * FROM STUDENT;

RESULTS_NO NAME ADDRESS CITY ST ZIP TEL_NO------------------ ---------------- ----------------- ---- --------- --------------5001 MARY 102 1ST ST FAIRFAX VA 12345 70377723115002 TOM 39 5th AVE ARLINGTON DC 22313 20211122225003 LINDA 1 ROCK RD ROCKVILLE MD 20852 30193809755004 JAMES 70397844445005 KATHY 2 KING LA FAIRFAX VA 12345 70377755345006 MIKE P.O.BOX 1 FAIRFAX VA 12345 7037771122

NULL values Null means that there is no data and it is different from empty string.

Page 66: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 66 ©Minder Chen, 1996-2011

SELECTSelecting some columns:

EXAMPLE

SELECT D_ID, DIV_NAME

FROM DIVISION;

RESULTD_ID DIV_NAME------- ---------------D010 ADMINISTRATIOND020 COMPUTER SCIENCED030 ACCOUNTINGD040 STATISTICSD050 MATHEMATICS

Page 67: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 67 ©Minder Chen, 1996-2011

SELECT with a calculated columnCreate a calculated column (Expression):

SELECT L_NAME, F_NAME, (SALARY-20000)*0.1 AS BONUS

FROM INSTRUCTOR;

RESULT

L_NAM F_NAME BONUS----- -------- ---------LEE PATRICK 5200STONE ALBERT 4000FLYNN BRUCE 2800LOU JEAN 200

SELECT L_NAME, F_NAME, ([SALARY]-20000)*0.1 AS [Annual BONUS]FROM INSTRUCTOR;

Page 68: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 68 ©Minder Chen, 1996-2011

SELECT CriteriaSelect some rows:

EXAMPLESELECT L_NAME, M, F_NAME

FROM INSTRUCTOR

WHERE DIV = 'D020';

RESULTL_NAM M F_NAME--------------- ------------LEE D PATRICKSTONE Y ALBERTFLYNN C BRUCE

NOTEIn a WHERE Clause, values to be compared with text data type must be enclosed in single quotation mark ( 'text' ).In Access you can use both single quotes or double quotes.

Page 69: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 69 ©Minder Chen, 1996-2011

SELECTFinding NULL Columns

EXAMPLE

SELECT S_NO, NAME

FROM STUDENT

WHERE ADDRESS IS NULL;

RESULT

S_NO NAME

--------- ----------

5004 JAMES

Page 70: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 70 ©Minder Chen, 1996-2011

SELECT Criteria -- Date formatLess Than, Greater Than, Equal: < > =

EXAMPLE

SELECT D_O_H, F_NAME, L_NAME

FROM INSTRUCTOR

WHERE D_O_H < '01-JAN-90'

ORDER BY D_O_H;

RESULTD_O_H F_NAME L_NAM

--------------- --------------- --------------08-MAR-83 PATRICK LEE02-SEP-88 JEAN LOU

#01/01/1990#

In Access SQL

Page 71: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 71 ©Minder Chen, 1996-2011

SELECT CriteriaLess Than, Greater Than, Equal: < > =

EXAMPLE

SELECT L_NAME, I_NO, ED

FROM INSTRUCTOR

WHERE ED <= 10;

RESULT

L_NAM I_NO ED

----------- --------- -----

FLYNN 21 10

LOU 52 08

Page 72: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 72 ©Minder Chen, 1996-2011

SELECT CriteriaMultiple Conditions: AND

EXAMPLE

SELECT I_NO, D_O_H, SALARY

FROM INSTRUCTOR

WHERE D_O_H < '31-DEC-90' AND SALARY < 26000;

RESULT

I_NO D_O_H SALARY

--------- --------------- ---------

52 02-SEP-88 22000

AND

Page 73: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 73 ©Minder Chen, 1996-2011

SELECT CriteriaMultiple Conditions: OR

EXAMPLE

SELECT I_NO, D_O_H, SALARY

FROM INSTRUCTOR

WHERE D_O_H < '31-DEC-90' OR SALARY < 26000;

RESULT I_NO D_O_H SALARY

--------- ------------ -------------

1 8-MAR-83 72000

52 02-SEP-88 22000

OR

Page 74: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 74 ©Minder Chen, 1996-2011

SELECT CriteriaMultiple Conditions: AND, OR

EXAMPLE

SELECT I_NO, D_O_H, SALARY

FROM INSTRUCTOR

WHERE D_O_H < '01-JAN-90'

AND (SALARY < 40000 OR ED < 11);

RESULT

I_NO D_O_H SALARY

--------- ------------- ------------

52 02-SEP-88 22000

Page 75: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 75 ©Minder Chen, 1996-2011

SELECT CriteriaSelecting All Rows Except ... : NOT, <>, ^=

EXAMPLESELECT D_ID, DIR

FROM DIVISION WHERE NOT (D_ID <= 'D010');

RESULT D_ID DIR

-------- -----D020 1D030 1D040 1D050 1

NOTE– The NOT keyword must precede the condition.

Page 76: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 76 ©Minder Chen, 1996-2011

Selecting Rows ...LIKE... SELECT NAME, CITY

FROM STUDENT WHERE CITY LIKE 'FAIR%'; - - match 'Fairlake'

SELECT NAME, CITY FROM STUDENT WHERE CITY LIKE 'FAIR_ _ _'; - - does not match 'Fairlake'

RESULT: Both query get same results.

NAME CITY---------- ----------MARY FAIRFAXKATHY FAIRFAXMIKE FAIRFAX

***NOTE***– Use a percent sign (%) to indicate any string of zero or more characters.

Use * in Access instead of %– Use an underscore (_) for any single character. (use ? In Access)– Use the LIKE keyword only with data type CHAR, VARCHAR not with

NUMERIC or DATE.

SELECT NAME, CITYFROM STUDENTWHERE CITY LIKE '%FAIR%';

- - match 'Fairlake' and 'Myfaircity'

SELECT NAME, CITYFROM STUDENTWHERE CITY LIKE '%FAIR%';

- - match 'Fairlake' and 'Myfaircity'

Page 77: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 77 ©Minder Chen, 1996-2011

SELECT Values Within a Range

EXAMPLE

SELECT D_ID, DIR FROM DIVISION WHERE D_ID BETWEEN 'D010' AND 'D030' ORDER BY D_ID;

- - WHERE D_ID >= 'D10' AND D_ID <= 'D030'

RESULTD_ID DIR------- ---------D010 52D020 1D030 1

Page 78: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 78 ©Minder Chen, 1996-2011

Selecting Values Within a Range

SELECT I_NO, SALARY

FROM INSTRUCTOR

WHERE SALARY NOT BETWEEN 30000 AND 50000;

- - WHERE SALARY < 30000 OR SALARY > 50000

RESULT

I_NO SALARY

--------- ------------

1 72000

19 60000

52 22000

Page 79: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 79 ©Minder Chen, 1996-2011

SELECT ORDER BY: Showing Values in Sequence

ORDER BY: (ASC or DESC) Ascending Order is the default. SELECT D_ID, DIR

FROM DIVISION ORDER BY D_ID;

RESULTD_ID DIR

------- ---------D010 52D020 1D030 1D040 1D050 1

NOTE: All columns named in the ORDER BY clause must be named in the SELECT clause.

(In Access the above statement is NOT TRUE. Sorting columns don’t have to be selected for display.)

Page 80: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 80 ©Minder Chen, 1996-2011

SELECT: ORDER BY clauseEXAMPLE: In Descending Order

SELECT D_ID, DIR FROM DIVISION

ORDER BY D_ID DESC; - - ASC (Ascending) is the default sorting order

- - The default order for character fields is a case sensitive ASCII sequence

RESULTD_ID DIR------- ---------D050 1D040 1D030 1D020 1D010 52

Page 81: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 81 ©Minder Chen, 1996-2011

SELECT: ORDER BY column numberEXAMPLE: Order by the first column

1 2

SELECT D_ID, DIR FROM DIVISION

ORDER BY 1;

RESULTD_ID DIR------- ---------D010 52D020 1D030 1D040 1D050 1

Page 82: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 82 ©Minder Chen, 1996-2011

Top N Rows

• TOP n [PERCENT]: Returns a certain number of records that fall at the top or the bottom of a range specified by an ORDER BY clause.

• In Access you need to add TOP N qualifier in SQL View

SELECT TOP 2 L_NAME,F_NAME, SALARY

FROM INSTRUCTOR

ORDER BY INSTRUCTOR.SALARY DESC;

Page 83: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 83 ©Minder Chen, 1996-2011

SELECT: ORDER BY sort-list (multiple columns)

INSERT INTO

INSTRUCTOR (I_NO, L_NAME, M, F_NAME, SALARY)

VALUES (60, 'SMITH', 'F', 'BOB', 60000); SELECT L_NAME, F_NAME, SALARY * 0.1 AS BONUS

FROM INSTRUCTOR ORDER BY Bonus DESC, L_NAME; - - primary order column is BONUS- - Secondary column is L_NAME

L_NAM F_NAME BONUS----- -------- ---------LEE PATRICK 7200SMITH BOB 6000STONE ALBERT 6000FLYNN BRUCE 4800LOU JEAN 2200

Access SQLAccess SQL: (cannot use alias column name in Order By clause)SELECT L_NAME, F_NAME, SALARY * 0.1 AS BONUS FROM INSTRUCTOR

ORDER BY 3 DESC, L_NAME;

Page 84: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 84 ©Minder Chen, 1996-2011

ORDER BY the Position of Columns

SELECT L_NAME, F_NAME, SALARY * 0.1

FROM INSTRUCTOR

ORDER BY 3 DESC, L_NAME;

L_NAM F_NAME SALARY*0.1

----- -------- ----------

LEE PATRICK 7200

SMITH BOB 6000

STONE ALBERT 6000

FLYNN BRUCE 4800

LOU JEAN 2200

Sort first by third column in descending order

Sort secondly by L_NAME (asc)

Page 85: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 85 ©Minder Chen, 1996-2011

SELECTConcatenation Operations ||

EXAMPLESELECT L_NAME | | ', ' | | F_NAME | | ' ' | | M AS NAME

FROM INSTRUCTOR;

RESULTNAME---------------------------LEE, PATRICK DSTONE, ALBERT YFLYNN, BRUCE CLOU, JEAN E

Access SQL: (use & instead of || for string concatenation)SELECT L_NAME & ', ' & F_NAME & ' ' & M AS NAME

FROM INSTRUCTOR;

A space character

Page 86: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 86 ©Minder Chen, 1996-2011

SELECT: INSelecting Value in or not in a List:EXAMPLE

SELECT D_ID, DIR FROM DIVISION

WHERE D_ID IN ('D010', 'D020', 'D040')ORDER BY D_ID;

RESULTD_ID DIR------- ---------D010 52D020 1D040 1

SELECT D_ID, DIRFROM DIVISIONWHERE D_ID NOT IN ('D010', 'D020', 'D040')ORDER BY D_ID;

SELECT D_ID, DIRFROM DIVISIONWHERE D_ID NOT IN ('D010', 'D020', 'D040')ORDER BY D_ID;

Page 87: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 87 ©Minder Chen, 1996-2011

SELECTExpressions in Conditions:

EXAMPLE

SELECT I_NO, L_NAME, SALARY

FROM INSTRUCTOR

WHERE SALARY > 800 * 52;

RESULT

I_NO L_NAM SALARY--------- ----- --------- 1 LEE 72000 19 STONE 60000 21 FLYNN 48000

Page 88: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 88 ©Minder Chen, 1996-2011

INSERTINSERT INTO [table-name | view-name][(column-name1, column-name2, …)] VALUES (value1, value2, …);

Adding one or more row(s) into an existing table. – Table with Foreign Keys

» Target (referenced column) of foreign key must exist» NULL value of the foreign key (referencing column)

allowed– CHECK Constraint

INSERT INTO DIVISION VALUES('D010',52,'ADMINISTRATION');

Page 89: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 89 ©Minder Chen, 1996-2011

INSERT Examples

INSERT INTO DIVISION

VALUES('D060',NULL,'MARKETING');

-- This does not work in Access

INSERT INTO DIVISION (DIV_NAME, D_ID)

VALUES('R&D', 'D070');

D_ID DIR DIV_NAME---- --------- ----------------D010 52 ADMINISTRATIOND020 1 COMPUTER SCIENCED030 1 ACCOUNTINGD040 1 STATISTICSD050 1 MATHEMATICSD060 MARKETINGD070 R&D

Page 90: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 90 ©Minder Chen, 1996-2011

Access Append Query (Insert)INSERT INTO DIVISION ( D_ID, DIV_NAME )SELECT 'D060' AS Expr1, 'Marketing' AS Expr2;

INSERT INTO DIVISION ( D_ID, DIV_NAME )VALUES ('D060', 'Marketing' );

Don’t select any tables from the Show Table dialog box

Page 91: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 91 ©Minder Chen, 1996-2011

INSERT Multiple Rows

INSERT INTO [table-name | view-name][column-name1, column-name2, …)] SELECT statement;

CREATE TABLE TEACHER1(I_NO NUMBER(4) NOT NULL,

F_NAME VARCHAR(8) NOT NULL,

L_NAME VARCHAR(5) NOT NULL,DIV CHAR(4));

INSERT INTO TEACHER1 (I_NO, F_NAME, L_NAME, DIV) SELECT I_NO, F_NAME, L_NAME, DIV FROM INSTRUCTOR

WHERE TITLE = 'TEACHER';

Page 92: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 92 ©Minder Chen, 1996-2011

UPDATE: Modify One or More Columns UPDATE [table-name | view-name] SET column-name1 = expression1, column-name2 = expression2, ...[WHERE clause]; - - Change the last name of the instructor (I_NO = 21) to 'WANG'

UPDATEUPDATE INSTRUCTOR SETSET L_NAME='WANG' WHEREWHERE I_NO = 21;--Give all the instructors in --D010 department a 10% raise. UPDATE INSTRUCTOR SET SALARY = SALARY * 1.1 WHERE DIV = 'D010';

I_NO F_NAME M L_NAM SALARY--------- ------------- --- ----------- ------------- 1 PATRICK D LEE 72000 19 ALBERT Y STONE 60000 21 BRUCE C WANG 48000 52 JEAN E LOU 24200

Click Run

Page 93: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 93 ©Minder Chen, 1996-2011

UPDATE

• You cannot update a view if the view's defining query contains one of the following constructs: –JOIN

–set operator

–GROUP BY clause

–group function

–DISTINCT operator

–Non-columns are used in SELECT clause.

Page 94: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 94 ©Minder Chen, 1996-2011

DELETE: Deleting One or More Rows

DELETE FROM table-name [WHERE clause];

EXAMPLE- - Delete instructor whose I_NO is 52 DELETE FROM INSTRUCTOR WHERE I_NO = 52;

- - delete students with 301 area code DELETE FROM STUDENT WHERE TEL_NO LIKE = '301*';

- - delete the whole table DELETE FROM DIVISION;

NOTES: DELETE command is a very powerful command, please use it with care.

Page 95: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 95 ©Minder Chen, 1996-2011

FUNCTIONS

AGGREGATE FUNCTIONS

– COUNT (*) or COUNT(DISTINT column)

– MAX

– MIN

– SUM

– AVG

Other Functions

– SUBSTR

– TRUNC

– Format

Page 96: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 96 ©Minder Chen, 1996-2011

COUNT

PURPOSE: Counts the number of rows in each group that satisfy the condition(s) specified.

EXAMPLE

SELECT COUNT(*) FROM STUDENT;

RESULT

COUNT(*)

---------------

6

Page 97: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 97 ©Minder Chen, 1996-2011

Count()

• How many students that we have from VA state? SELECT Count(*) AS [VA-Student-count]

FROM STUDENT

WHERE STUDENT.STATE='VA';

Page 98: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 98 ©Minder Chen, 1996-2011

Use Query Design View

SELECT Count(STUDENT.S_NO)

AS CountOfS_NO

FROM STUDENT

WHERE (((STUDENT.STATE)="VA"));

Tool Bar

Page 99: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 99 ©Minder Chen, 1996-2011

COUNT

EXAMPLE

SELECT COUNT(ADDRESS)

FROM STUDENT;

RESULT

COUNT(ADDRESS)

---------------------------

5

Page 100: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 100 ©Minder Chen, 1996-2011

MAX

PURPOSE

Selects the maximum value in each group of a column. Null values will be ignored.

EXAMPLE

SELECT MAX(SALARY)

FROM INSTRUCTOR;

RESULT

MAX(SALARY)

---------------------

72000

Page 101: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 101 ©Minder Chen, 1996-2011

MIN

PURPOSE

Selects the mininum value in each group of a column. Null values will be ignored.

EXAMPLE

SELECT MIN(SALARY)

FROM INSTRUCTOR;

RESULT

MIN(SALARY)

--------------------

22000

Page 102: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 102 ©Minder Chen, 1996-2011

SUM

PURPOSE

Adds up all the values in each group of a column. Null values will be ignored.

EXAMPLE

SELECT SUM(SALARY)

FROM INSTRUCTOR;

RESULT

SUM(SALARY)

---------------------

202000

Page 103: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 103 ©Minder Chen, 1996-2011

AVG

PURPOSE

Averages the values in each group of a column. This function is for numeric columns only. Null values will be ignored.

EXAMPLE

SELECT AVG(SALARY)

FROM INSTRUCTOR;

RESULT

AVG(SALARY)

--------------------

50500

Page 104: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 104 ©Minder Chen, 1996-2011

Use Several Functions Together

• More than one function can be used in a command.

SELECT COUNT(I_NO), AVG(SALARY), MIN(SALARY), MAX(SALARY)

FROM INSTRUCTOR; COUNT(I_NO) AVG(SALARY) MIN(SALARY) MAX(SALARY)

----------- ----------- ----------- -----------

4 50500 22000 72000

Page 105: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 105 ©Minder Chen, 1996-2011

SELECT with Distinct Values Selecting unique values in a

column:

EXAMPLE

SELECT DISTINCT ( TITLE )

FROM INSTRUCTOR;

RESULT

TITLE--------------CLERKDEANTEACHER

Selecting values in a column:

EXAMPLE

SELECT TITLE

FROM INSTRUCTOR;

RESULT

TITLE--------------DEANTEACHER TEACHER CLERK

Create a query to tell me “How many distinct titles we have?”

You can only create this query in Access SQL View

Page 106: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 106 ©Minder Chen, 1996-2011

Count and Distinct Statement Limitation

Oracle SQL:

SELECT COUNT(DISTINCT CITY) FROM STUDENT;-- Answer: 3 (exclude records that have NULL value

in their city column)

Access SQL (Include NULL value; cannot use distinct and Count together) You have to use the SQL view to enter the distinct keyword. It will not work in the Design view.

SELECT DISTINCT (CITY) FROM STUDENT;

Page 107: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 107 ©Minder Chen, 1996-2011

How to count distinct values

1

2

3

4 5

6

Create the first query using distinct and save it as DistinctTitles

Create the second query against the DistinctTitles query. Use count function in this second query.

Page 108: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 108 ©Minder Chen, 1996-2011

Access Report Wizard1

2

3

Page 109: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 109 ©Minder Chen, 1996-2011

Group By Control Break

Group By DIV (Division ID)

Aggregate Functions

4The GROUP BY statement is used in conjunction with the aggregate functions to group the result-set by one or more columns.

Page 110: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 110 ©Minder Chen, 1996-2011

Group By • SELECT clause contains both an aggregate function

and a column name are not allowed unless the result set is GROUP BY the same column.

SELECT TITLE, SUM (SALARY) FROM INSTRUCTOR

GROUP BY TITLE;

TITLE SUM(SALARY)-------- -----------CLERK 22000DEAN 72000TEACHER 108000

SELECT GB-column-name, aggregate_function(column_name)FROM table_nameWHERE column_name operator valueGROUP BY GB-column-name

Page 111: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 111 ©Minder Chen, 1996-2011

SELECT: Grouping RowsSummarize Group Values: Build-in functions (e.g., MAX, MIN)

can be applied to selected groups of rows in a table. GROUP BY produces one row in the returned set for each different value it finds in the GROUP BY column(s).

EXAMPLE SELECT DIV, MAX(SALARY), MIN(SALARY) FROM INSTRUCTOR GROUP BY DIV ORDER BY DIV;

RESULTDIV MAX(SALARY) MIN(SALARY)------- -------------------- --------------------D010 22000 22000D020 60000 48000

Page 112: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 112 ©Minder Chen, 1996-2011

Group By … Having ...

Use HAVING instead of WHERE clause after GROUP to qualify groups. Nested queries are permitted in the HAVING clause.

SELECT TITLE, AVG(SALARY)FROM INSTRUCTORGROUP BY TITLEHAVING COUNT(*) > 1;

TITLE AVG(SALARY)-------- -----------TEACHER 54000

Show me each title and average salary of the title which has more than one instructors with such title. This is for privacy purpose.

Page 113: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 113 ©Minder Chen, 1996-2011

SELECT Groups with Conditions Groups with Conditions:

EXAMPLE

SELECT DIV, ROUND(AVG(SALARY)/52, 2)

AS AVG_SAL

FROM INSTRUCTOR

GROUP BY DIV

HAVING COUNT(*) > 1

ORDER BY DIV;

RESULTDIV AVG_SAL---- ---------D020 1153.85

ROUND(n[,m]): Returns n rounded to m decimal places; if m is omitted, to 0 places.

Cannot use aggregate functions in WHERE clause!

Page 114: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 114 ©Minder Chen, 1996-2011

SUBSTR(char, m [,n])PURPOSE

Returns a portion of char, beginning at character m for n characters long.

EXAMPLESELECT SUBSTR(DIV_NAME,1,4) "SUBS"

FROM DIVISION;

RESULTSUBS--------ADMICOMPACCOSTATMATH

Access SQL: (use LEFT string function)SELECT Left(DIV_NAME,4) as SUBS FROM DIVISION;

Page 115: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 115 ©Minder Chen, 1996-2011

TRUNC(n, d)Truncates a number n and display d decimal positions.

EXAMPLESELECT I_NO,

TRUNC(MONTHS_BETWEEN(SYSDATE, D_O_B)/12, 0) AS AGEFROM INSTRUCTOR;

RESULT I_NO AGE--------- --------- 1 46 19 43 21 39 52 33•Assuming that the SYSDATE returns 10/4/1998.

Should you store “age” in the database instead of birthday?

Access SQL: (Date function)SELECT I_NO,

ROUND(DateDiff("m", D_O_B, Now)/12, 0) AS AGEFROM INSTRUCTOR;

Page 116: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 116 ©Minder Chen, 1996-2011

Advanced SQL Programming

• JOIN

• Correlated subquery

• Non-correlated subquery

• UNION

JOIN: A SQL join is used to query data from two or more tables, based on a relationship between certain columns in these tables. The common columns that are used to connect these tables are usually a foreign key-primary key pair.

Page 117: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 117 ©Minder Chen, 1996-2011

Join • Show all instructors from the Instructor table with the

following information:

– I_NO, L_Name, F_Name, plus DIV and DIV_Name where the instructor belongs.

Page 118: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 118 ©Minder Chen, 1996-2011

JOIN• Join condition: Join operation must based on one or

more columns from each of the two tables whose data values share a common domain.

• To get data from two or more tables resulting in a wide table, you need to name all tables in the FROM clause.

EXAMPLESELECT D_ID, L_NAME, F_NAME, DIV_NAME

FROM DIVISION, INSTRUCTOR

WHERE Division.DIR = Instructor.I_NO

ORDER BY D_ID;

Show me the Division ID, Last name, First Name of its Director, and the Division Name of all the Division and sorted it by Division ID

Page 119: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 119 ©Minder Chen, 1996-2011

JOIN

RESULT

D_ID L_NAM F_NAME DIV_NAME------- ------------- --------------- -------------------------------

D010 LOU JEAN ADMINISTRATION

D020 LEE PATRICK COMPUTER SCIENCE

D030 LEE PATRICK ACCOUNTING

D040 LEE PATRICK STATISTICS

D050 LEE PATRICK MATHEMATICS

NOTE– The FROM DIVISION, INSTRUCTOR clause shows this is

a join.

– The WHERE DIR = I_NO clause makes the connection between the two tables.

Page 120: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 120 ©Minder Chen, 1996-2011

JOIN: Access Query and SQL

SELECT INSTRUCTOR.I_NO, INSTRUCTOR.F_NAME,

INSTRUCTOR.L_NAME, DIVISION.DIV_NAME

FROM DIVISION INNER JOIN INSTRUCTOR

ON DIVISION.D_ID = INSTRUCTOR.DIV;

I_NOP

F_NAMEM

L_NAMEDIVF

D_O_HTITLE

EDSEX

D_O_BSALARY

INSTRUCTORD_IDP

DIRF

DIV_NAME

DIVISION

Page 121: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 121 ©Minder Chen, 1996-2011

Qualifying Column Names• If the same column name is used in more than one table, you

must qualify its name to show which table or view you mean. You can also qualify column names by correlation variables

SELECT TITLE, COURSE.C_ID, LOCATION, START_DATE

FROM COURSE, OFFERING

WHERE COURSE.C_ID = OFFERING.C_ID

ORDER BY TITLE;

or

SELECT TITLE, X.C_ID, LOCATION, START_DATE

FROM COURSE X, OFFERING Y

WHERE X.C_ID = Y.C_ID

ORDER BY TITLE;

X, Y are correlation variables or aliases.

C_IDP,F

O_NOP

START_DATELOCATIONI_NOF

OFFERING

C_IDP

TITLEDIVF

FEE

COURSE

Page 122: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 122 ©Minder Chen, 1996-2011

Qualifying Column Names

RESULTTITLE C_ID LOCATION START_DAT------------------- ------- ------------------- ------------------INTRO C++ C010 LOUDOUN 01-APR-97INTRO C++ C010 LOUDOUN 01-OCT-97INTRO C++ C010 ROCKVILLE 01-OCT-97INTRO PB C020 LOUDOUN 01-APR-97INTRO PB C020 LOUDOUN 01-OCT-97INTRO PB C020 ROCKVILLE 01-OCT-97RDBMS SQL C030 LOUDOUN 01-OCT-97WINDOWS NT C040 LOUDOUN 01-OCT-97

Page 123: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 123 ©Minder Chen, 1996-2011

JOIN and Aggregation Function Show students ID, name, and GPA (assuming all courses are 3 credits)

SELECT STUDENT.S_NO, STUDENT.NAME, Round(Avg(REGISTRATION.GRADE)*100)/100 AS AvgOfGRADE

FROM STUDENT.S_NO = REGISTRATION.S_NO

GROUP BY STUDENT.S_NO, STUDENT.NAME;

SQL: Format(Avg(GRADE), "###.00") AS GPA

Design View:

GPA: Format(Avg(GRADE), "###.00")

Don’t choose any table here!

Change this to expression

Page 124: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 124 ©Minder Chen, 1996-2011

Examples

• How many students in each section of the fall 1997 class assuming the START_DATE of the fall 1997 semester is #10/1/1997#?

Page 125: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 125 ©Minder Chen, 1996-2011

JOIN and Aggregation Function • Show the total fees generated by each course (with

multiple offering)

SELECT COURSE.C_ID, COURSE.TITLE, Sum(COURSE.FEE) AS SumOfFEEFROM (COURSE INNER JOIN OFFERING ON COURSE.C_ID = OFFERING.C_ID) INNER JOIN REGISTRATION ON (OFFERING.O_NO = REGISTRATION.O_NO) AND (OFFERING.C_ID = REGISTRATION.C_ID)GROUP BY COURSE.C_ID, COURSE.TITLEORDER BY Sum(COURSE.FEE) DESC;– How about fees generated in fall 1997 semester?_ How about top 2 courses that generate most fees

Page 126: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 126 ©Minder Chen, 1996-2011

Alternative Join Syntax

Oracle: (This works in Access as well)

SELECT TITLE, COURSE.C_ID, LOCATION, START_DATE

FROM COURSE, OFFERING

WHERE COURSE.C_ID = OFFERING.C_ID

ORDER BY TITLE;

Access SQL and SQL-92 Standard: (May not work in Oracle SQL*Plus)

SELECT Title, COURSE.C_ID, LOCATION, START_DATE

FROM COURSE INNER JOIN OFFERING

ON COURSE.C_ID = OFFERING.C_ID

ORDER BY TITLE;

Page 127: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 127 ©Minder Chen, 1996-2011

JOIN

Inner Join: SELECT INSTRUCTOR.I_NO, L_NAME, F_NAME, C_ID, O_NO

FROM INSTRUCTOR, OFFERING WHERE INSTRUCTOR.I_NO = OFFERING.I_NO;

I_NO L_NAM F_NAME C_ID O_NO--------- ----- -------- ---- --------- 21 FLYNN BRUCE C010 1 21 FLYNN BRUCE C010 10 19 STONE ALBERT C010 20 19 STONE ALBERT C020 1 19 STONE ALBERT C020 10 21 FLYNN BRUCE C020 20 19 STONE ALBERT C030 10 19 STONE ALBERT C040 10

• With inner join operation, only rows that satisfy the comparison used to create the join are included in the result. Instructors who do not have any offering entry in the OFFERING table will not be retrieved.

Page 128: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 128 ©Minder Chen, 1996-2011

Inner & Outer Joins

Inner Join

Left Outer Join

Right Outer Join

Page 129: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 129 ©Minder Chen, 1996-2011

Left Outer Join

SELECT INSTRUCTOR.I_NO, L_NAME, F_NAME, C_ID, O_NO FROM

INSTRUCTOR, OFFERING

WHERE INSTRUCTOR.I_NO = OFFERING.I_NO (+); I_NO L_NAM F_NAME C_ID O_NO--------- ----- -------- ---- --------- 1 LEE PATRICK 19 STONE ALBERT C010 20 19 STONE ALBERT C020 1 19 STONE ALBERT C030 10 19 STONE ALBERT C020 10 19 STONE ALBERT C040 10 21 FLYNN BRUCE C010 1 21 FLYNN BRUCE C010 10 21 FLYNN BRUCE C020 20 52 LOU JEAN

• When instructors from INSTRUCTOR table do not have any offering, they will be listed with NULL values in columns from OFFERING table.

• (+) qualifier in the WHERE clause indicate which table's columns should contain entries with NULL values when there is no matching value in the other column. (Oracle only)

NULL Values

Page 130: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 130 ©Minder Chen, 1996-2011

Outer Join Right Outer Join: • SELECT INSTRUCTOR.I_NO, L_NAME, F_NAME, C_ID, O_NO

FROM INSTRUCTOR, OFFERING WHERE INSTRUCTOR.I_NO (+) = OFFERING.I_NO;

• Alternative Notation (SQL-92 standard)SELECT INSTRUCTOR.I_NO, L_NAME, F_NAME, C_ID, O_NO FROM INSTRUCTOR, OFFERING,

INSTRUCTOR RIGHT OUTER JOIN OFFERINGON INSTRUCTOR.I_NO = OFFERING.I_NO;

Left Outer Join• SELECT INSTRUCTOR.I_NO, L_NAME, F_NAME, C_ID, O_NO

FROM INSTRUCTOR, OFFERING WHERE INSTRUCTOR.I_NO = OFFERING.I_NO (+);

• Alternative Notation (SQL-92 standard)SELECT INSTRUCTOR.I_NO, L_NAME, F_NAME, C_ID, O_NO FROM INSTRUCTOR, OFFERING,

INSTRUCTOR LETF OUTER JOIN OFFERINGON INSTRUCTOR.I_NO = OFFERING.I_NO;

Page 131: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 131 ©Minder Chen, 1996-2011

Multiway Join

This query joins six tables.

EXAMPLE

SELECT A.C_ID, B.TITLE, C.LOCATION, C.START_DATE,

D.DIV_NAME, E.L_NAME AS INSTR, F.NAME AS STUDENT

FROM REGISTRATION A, COURSE B,

OFFERING C, DIVISION D,

INSTRUCTOR E, STUDENT F

WHERE A.C_ID = 'C010'

AND A.C_ID = B.C_ID

AND(A.C_ID = C.C_ID AND A.O_NO = C.O_NO)

AND C.I_NO = E.I_NO

ANDB.DIV = D.D_ID

AND A.S_NO = F.S_NO;

Page 132: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 132 ©Minder Chen, 1996-2011

Multiway Join

RESULTC_ID TITLE LOCATION START_DAT DIV_NAME INSTR STUDENT

------- ---------------- --------------- ----------------- ------------------------------- ---------- --------------

C010 INTRO C++ LOUDOUN 01-APR-97 COMPUTER SCIENCE FLYNN MARY

C010 INTRO C++ LOUDOUN 01-APR-97 COMPUTER SCIENCE FLYNN TOM

C010 INTRO C++ LOUDOUN 01-OCT-97 COMPUTER SCIENCE FLYNN LINDA

C010 INTRO C++ LOUDOUN 01-OCT-97 COMPUTER SCIENCE FLYNN JAMES

C010 INTRO C++ LOUDOUN 01-OCT-97 COMPUTER SCIENCE FLYNN KATHY

Page 133: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 133 ©Minder Chen, 1996-2011

Server Generated Sequence Numbers• In some database servers such as Sybase, the system

maintains a sequence number for an identity column. It is special data type called AutoNumber is Access.

Create table employee ( id numeric(4, 0) identify, name char(20) not null, title char(50) not null); Insert into employee values ('Minder', 'Dean'); Insert into employee values ('Justin', 'Instructor');Result:id name title1 Minder Dean2 Justin Instructor

Page 134: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 134 ©Minder Chen, 1996-2011

Table

Query(View)

Form ReportDatabaseApplication

Basic DatabaseObjects

Relationships among Access Database Objects

• A saved SELECT query is officially called View in SQL. • QUERY in Access can be SELECT, INSERT, UPDATE, or

DELETE. • You can create a query against a table or a query.• You can create a form or report against a table or a query.

Page 135: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 135 ©Minder Chen, 1996-2011

Create Forms in Access

Page 136: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 136 ©Minder Chen, 1996-2011

Create a Simple Form

Page 137: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 137 ©Minder Chen, 1996-2011

Form Layout and Style

Page 138: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 138 ©Minder Chen, 1996-2011

Page 139: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 139 ©Minder Chen, 1996-2011

Detail Form in Datasheet Layout

Page 140: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 140 ©Minder Chen, 1996-2011

Page 141: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 141 ©Minder Chen, 1996-2011

Page 142: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 142 ©Minder Chen, 1996-2011

Page 143: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 143 ©Minder Chen, 1996-2011

LOCKLocking mechanism is used to prevent loss of data integrity in

reading and writing data to the database. The lock controls whether some other users can access (read or write) the database. Transaction requests and releases for locks are normally implicit.

Shared lock (S): Allow the lock owner to read the lock data, but not to change it. You can acquire a shared lock on data after other users also acquired a shared lock on the it.

Exclusive lock (X): Allow the lock owner to read and update the lock data. No other user can access the locked data or acquired locks on it while a exclusive lock is in effect.

Lock Compatibility

Page 144: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 144 ©Minder Chen, 1996-2011

LOCK

Permits users to explicitly acquire table locks.–Lock Objects

»Row»Page»Table»Table Space

–Lock Modes»Shared(S) Lock»Exclusive(X) Lock

Page 145: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 145 ©Minder Chen, 1996-2011

COMMIT & ROLLBACK

• COMMIT: Instructs the system to make all DML commands executed by a transaction permanent and releases the transaction's locks. You can also use this command to manually commit an in-doubt distributed transaction.

• ROLLBACK: Instructs the system to reverse all DML commands executed by a transaction. When the ROLLBACK command is issued, all changes caused by INSERT, UPDATE and DELETE commands of the transaction are backed out. All locks acquired during a transaction are released by the ROLLBACK command.

Page 146: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 146 ©Minder Chen, 1996-2011

Indexing & Performance: Retrieval vs. Update

All IndexedNo index

Fastest

Slowest

Retrieval speed

Updatespeed

Trade off between retrieval

and update

Consider the creation of indexes when faster retrieval performance is required.

Page 147: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 147 ©Minder Chen, 1996-2011

APPENDIX A. Sample Database Tables

I_NO F_NAME M L_NAM DIV D_O_H TITLE ED S D_O_B SALARY1 PATRICK D LEE D020 08-MAR-83 DEAN 12 M 03-NOV-51 72000

19 ALBERT Y STONE D020 22-DEC-94 TEACHER 11 M 01-AUG-55 6000021 BRUCE C FLYNN D020 14-JUN-97 TEACHER 10 M 18-APR-59 4800052 JEAN E LOU D010 02-SEP-88 CLERK 08 F 01-JAN-65 22000

1. Instructor Table

2. Student Table

3. Division Table

Page 148: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 148 ©Minder Chen, 1996-2011

4. Course Table

5. Offering Table

6. Registration Table

Page 149: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 149 ©Minder Chen, 1996-2011

Physical Data Model

Page 150: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 150 ©Minder Chen, 1996-2011

NormalizationFirst Normal Form A table is in the first normal form if it

contains no repeating value.Un-Normalized Relation:

Normalized Relation:

STUDENT COURSETom C102Sam C102Sam C103Sam C105

Ralph C102Ralph C105

Page 151: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 151 ©Minder Chen, 1996-2011

NormalizationSecond Normal Form A table is in the second normal form if

you remove any partial functional dependencies.

Un-normalized Relation:

Registration

Normalized Relation:

Registration

CourseSTUDENT_ID Course_ID Grade

COURSE_ID Cours Title Instructor_ID

Partial Functional Dependency

Page 152: Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU.

RDBMS&SQL - 152 ©Minder Chen, 1996-2011

NormalizationThird Normal Form A table is in the third normal

form if it contains no transitive functional dependencies.

Un-normalized Relation:

Course

Normalized Relation:Course

Instructor

COURSE Course Title Instructor_ID InstructorTel

Transitive Functional Dependencies


Recommended