sql. components of sql data definition language (ddl) –to create database structures –to enforce...

61
SQL

Post on 19-Dec-2015

284 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: SQL. Components of SQL Data definition language (DDL) –To create database structures –To enforce constraints etc. Data manipulation language (DML) –To

SQL

Page 2: SQL. Components of SQL Data definition language (DDL) –To create database structures –To enforce constraints etc. Data manipulation language (DML) –To

Components of SQL

• Data definition language (DDL)– To create database structures– To enforce constraints etc.

• Data manipulation language (DML)– To access data

• Authorization language – To grant privileges to users

• SQL supports dynamic database definition– Structures can be modified easily

Page 3: SQL. Components of SQL Data definition language (DDL) –To create database structures –To enforce constraints etc. Data manipulation language (DML) –To

About SQL

• Its fairly standard across the all relational database management systems but…

• There are some differences in– Syntax– Data types– Functionality

• As a rule, Oracle is a better environment in which to learn SQL than Access… – But we will look at both, with an emphasis on

Oracle

Page 4: SQL. Components of SQL Data definition language (DDL) –To create database structures –To enforce constraints etc. Data manipulation language (DML) –To

DDL Commands

• CREATE TABLE

• CREATE INDEX

• ALTER TABLE

• RENAME TABLE

• DROP TABLE

• DROP INDEX

• CREATE VIEW

Page 5: SQL. Components of SQL Data definition language (DDL) –To create database structures –To enforce constraints etc. Data manipulation language (DML) –To

CREATE TABLECREATE TABLE base-table-name (colname datatype

[column constraints NULL/NOT NULL, DEFAULT…, UNIQUE, CHECK…, PRIMARY KEY],

[,colname datetype [column constraints …]]...

[table constraints PRIMARY KEY…, FOREIGN KEY…, UNIQUE…, CHECK…]

[storage specifications]);

Page 6: SQL. Components of SQL Data definition language (DDL) –To create database structures –To enforce constraints etc. Data manipulation language (DML) –To

Student Table

CREATE TABLE Student(stuId CHAR(6),lastName CHAR(20) NOT NULL,firstName CHAR(20) NOT NULL,major CHAR(10),credits SMALLINT DEFAULT 0,CONSTRAINT Student_stuId_pk PRIMARY KEY

(stuId),CONSTRAINT Student_credits_cc CHECK

(credits>=0 AND credits < 150));

Page 7: SQL. Components of SQL Data definition language (DDL) –To create database structures –To enforce constraints etc. Data manipulation language (DML) –To

Create Tables for University DBCREATE TABLE Student ( previous slide )CREATE TABLE Faculty (

facId CHAR(6),name CHAR(20) NOT NULL,department CHAR(20) NOT NULL,rank CHAR(10),CONSTRAINT Faculty_facId_pk PRIMARY KEY (facId));

CREATE TABLE Class(classNumber CHAR(8),facId CHAR(6) NOT NULL,schedule CHAR(8),room CHAR(6),CONSTRAINT Class_classNumber_pk PRIMARY KEY (classNumber),CONSTRAINT Class_facId_fk FOREIGN KEY (facId) REFERENCES Faculty (facId)) ;

CREATE TABLE Enroll (stuId CHAR(6),classNumber CHAR(8),grade CHAR(2),CONSTRAINT Enroll_classNumber_stuId_pk PRIMARY KEY (classNumber, stuId),CONSTRAINT Enroll_classNumber_fk FOREIGN KEY (classNumber) REFERENCES

Class (classNumber),CONSTRAINT Enroll_stuId_fk FOREIGN KEY (stuId) REFERENCES Student(stuId));

Page 8: SQL. Components of SQL Data definition language (DDL) –To create database structures –To enforce constraints etc. Data manipulation language (DML) –To

Rules for Identifiers

• No SQL keywords may be used

• Table name must be unique within the database

• Column names user must be unique within the table

Page 9: SQL. Components of SQL Data definition language (DDL) –To create database structures –To enforce constraints etc. Data manipulation language (DML) –To

Data Types• Each column must have a data type specified

– Numeric, fixed and varying-length character strings, bit strings, and user-defined types

• Data types vary by rdbms– See text and mysql documentation

Page 10: SQL. Components of SQL Data definition language (DDL) –To create database structures –To enforce constraints etc. Data manipulation language (DML) –To

User-defined Data Types

• We can declare our own domains and set constraints at the domain level:

CREATE DOMAIN creditValues INTEGER DEFAULT 0 CHECK (VALUE >=0 AND VALUE <150);

• This domain (data) type can then be used in defining columns:– In Student, can write credits creditValues – And we can use creditValues to define other data

Page 11: SQL. Components of SQL Data definition language (DDL) –To create database structures –To enforce constraints etc. Data manipulation language (DML) –To

Constraints

• These can be defined at:– column level– table level

• Column-level constraints– NULL/NOT NULL – UNIQUE– PRIMARY KEY– CHECK – DEFAULT – Written immediately after column name or

datatype

Page 12: SQL. Components of SQL Data definition language (DDL) –To create database structures –To enforce constraints etc. Data manipulation language (DML) –To

Table-level constraints• PRIMARY KEY

– For composite keys (simple ones at column level)

• FOREIGN KEY– Requires that the referenced table has already been

created

• UNIQUE– Specifies values in a combination of columns that must

be unique – Used to specify candidate keys

• ON DELETE / ON UPDATE for foreign keys– CASCADE / SET NULL/ SET DEFAULT / NO ACTION;

• Constraints can be given a name– This can be useful for disabling them at times

Page 13: SQL. Components of SQL Data definition language (DDL) –To create database structures –To enforce constraints etc. Data manipulation language (DML) –To

Indexes

• We can create any number of indexes for a given table– They facilitate fast retrieval of records with specific

values in a column– They don’t always return unique values

• Overhead is involved– The rdbms must maintain the index

• Tree data structures used to order values on index

Page 14: SQL. Components of SQL Data definition language (DDL) –To create database structures –To enforce constraints etc. Data manipulation language (DML) –To

CREATE INDEX

CREATE [UNIQUE] INDEX indexname ON basetablename (colname [order] [,colname [order]]...) [CLUSTER] ;

CREATE INDEX Student_lastName_firstName_ndx ON Student (lastName, firstName);

• UNIQUE enforces unique values for indexed column or combination of columns– The column need not be unique– Order is ASC (default) or DESC

• CLUSTER specification keeps records with same value for indexed field together (only one per table)

Page 15: SQL. Components of SQL Data definition language (DDL) –To create database structures –To enforce constraints etc. Data manipulation language (DML) –To

ALTER TABLE

• To add a new columnALTER TABLE basetablename ADD columnname datatype;ALTER TABLE Student ADD COLUMN birthdate DATETYPE;

• To drop a columnALTER TABLE basetablename DROP COLUMN columnname;ALTER TABLE Student DROP COLUMN major;

• To add a constraintALTER TABLE basetablename ADD CONSTRAINT constraint_defn;

• To drop a constraintALTER TABLE basetablename DROP CONSTRAINT constraint_name;

Page 16: SQL. Components of SQL Data definition language (DDL) –To create database structures –To enforce constraints etc. Data manipulation language (DML) –To

Other Changes to Tables

• Renaming a table:RENAME TABLE old-table-name TO new-table-name;

RENAME TABLE FACULTY TO TEACHERS;

• Dropping a table:DROP TABLE basetablename;

DROP TABLE CLASS;

• Dropping an index:DROP INDEX indexname;

DROP INDEX Student_lastName_fristName_ndx;

Page 17: SQL. Components of SQL Data definition language (DDL) –To create database structures –To enforce constraints etc. Data manipulation language (DML) –To

SQL DML

• Non-procedural, declarative language

• Can be – interactive– embedded in host language– stand-alone (SQL/PSMs)

• Basic commandsSELECT

UPDATE

INSERT

DELETE

Page 18: SQL. Components of SQL Data definition language (DDL) –To create database structures –To enforce constraints etc. Data manipulation language (DML) –To

SELECT Statement

SELECT [DISTINCT] col-name [AS newname], [,col-name..]…

FROM table-name [alias] [,table-name]…

[WHERE predicate]

[GROUP BY col-name [,col-name]…[HAVING predicate]

or …

[ORDER BY col-name [,col-name]…];

Page 19: SQL. Components of SQL Data definition language (DDL) –To create database structures –To enforce constraints etc. Data manipulation language (DML) –To

UniversityDB

stuID

lastName

firstName

major

credits

classNo

schedule

room

facID

facID

name

dept

rank

stuID

classNo

grade

Student Enroll Class Faculty

Page 20: SQL. Components of SQL Data definition language (DDL) –To create database structures –To enforce constraints etc. Data manipulation language (DML) –To

Get names & ids of all Math majors

SELECT lastname, firstname, stuID

FROM Student

WHERE major = ‘Math’;

Page 21: SQL. Components of SQL Data definition language (DDL) –To create database structures –To enforce constraints etc. Data manipulation language (DML) –To

Get all info about CSC faculty

SELECT *

FROM Faculty

WHERE dept = ‘CSC’;

Page 22: SQL. Components of SQL Data definition language (DDL) –To create database structures –To enforce constraints etc. Data manipulation language (DML) –To

Get the course numbers for all courses with enrollment

SELECT DISTINCT classNum

FROM Enroll;

Page 23: SQL. Components of SQL Data definition language (DDL) –To create database structures –To enforce constraints etc. Data manipulation language (DML) –To

Display the Student table

SELECT *

FROM Student;

Page 24: SQL. Components of SQL Data definition language (DDL) –To create database structures –To enforce constraints etc. Data manipulation language (DML) –To

Get names & ID’s of all faculty, listed alphabetically

SELECT name, facID

FROM Faculty

ORDER BY name;

SELECT name, facIDFROM FacultyORDER BY name, facID;

Page 25: SQL. Components of SQL Data definition language (DDL) –To create database structures –To enforce constraints etc. Data manipulation language (DML) –To

Get names of all math majors with > 30 credits

SELECT lastName, firstName

FROM Student

WHERE major = ‘MATH’

AND credits > 30;

Page 26: SQL. Components of SQL Data definition language (DDL) –To create database structures –To enforce constraints etc. Data manipulation language (DML) –To

Find ID’s and names of all students in ART 103A

SELECT Student.stuID, lastName, firstName

FROM Student, Enroll

WHERE Student.stuID = Enroll.stuID;

(Joining two tables)

Page 27: SQL. Components of SQL Data definition language (DDL) –To create database structures –To enforce constraints etc. Data manipulation language (DML) –To

Find ID’s (in ascending order) and grades of all students taking a

course with faculty ‘F110’

SELECT stuID, gradeFROM Class, EnrollWHERE Class.classNumber =

Enroll.classNumberAND facID = ‘F110’

ORDER BY stuID;

Page 28: SQL. Components of SQL Data definition language (DDL) –To create database structures –To enforce constraints etc. Data manipulation language (DML) –To

Find class #’s, names & majors of all students taking a course with

faculty ‘F110’

SELECT Enroll.classNumber, lastName, firstName, major

FROM Class, Enroll, StudentWHERE Class.classNumber = Enroll.classNumber

AND Enroll.stuID = Student.stuIDAND facID = ‘F110’

ORDER BY stuID;

Page 29: SQL. Components of SQL Data definition language (DDL) –To create database structures –To enforce constraints etc. Data manipulation language (DML) –To

Find class #’s of all of classes that meet in the same room

SELECT C1.classNumber, C2.classNumber

FROM Class C1, Class C2

WHERE C1.room = C2.room

AND C1.classNumber <> C2.classNumber

Must compare the Class table with itself – requires aliases.

This example works on the assumption that a maximum of two classes will meet in the same room

Page 30: SQL. Components of SQL Data definition language (DDL) –To create database structures –To enforce constraints etc. Data manipulation language (DML) –To

Subqueries

• These are queries within queries

SELECT columnName(s)

FROM tableName(s)

WHERE someColumnName = or IN(SELECT columnName(s)

FROM tableName(s)

WHERE someCondition);

The subquery executes FIRST

Page 31: SQL. Components of SQL Data definition language (DDL) –To create database structures –To enforce constraints etc. Data manipulation language (DML) –To

Find all class #’s for Byrne of the Math Dept

SELECT classNumber

FROM Class

WHERE facID =

(SELECT facID

FROM Faculty

WHERE name = ‘Byrne’

AND dept = ‘Math’);

Page 32: SQL. Components of SQL Data definition language (DDL) –To create database structures –To enforce constraints etc. Data manipulation language (DML) –To

Aggregate functions

• COUNT

• SUM

• MAX

• MIN

• AVG

Page 33: SQL. Components of SQL Data definition language (DDL) –To create database structures –To enforce constraints etc. Data manipulation language (DML) –To

How many students are in ART 103A?

SELECT COUNT (DISTINCT stuID)

FROM ENROLL

WHERE classNumber = ‘ART103A’;

Page 34: SQL. Components of SQL Data definition language (DDL) –To create database structures –To enforce constraints etc. Data manipulation language (DML) –To

Find the ID of the student with the most credits

SELECT stuID

FROM Student

WHERE credits =

(SELECT MAX(credits)

FROM Student);

Must use subquery

Page 35: SQL. Components of SQL Data definition language (DDL) –To create database structures –To enforce constraints etc. Data manipulation language (DML) –To

List each class# along with its enrollment

SELECT classNumber, COUNT(stuID)

FROM Enroll

GROUP BY classNumber;

Page 36: SQL. Components of SQL Data definition language (DDL) –To create database structures –To enforce constraints etc. Data manipulation language (DML) –To

Recap SQL commands so far

• SELECT is basic– * is the ‘wildcard’ or list column names

• WHERE for all conditions– Including joins

• ORDER BY for sorting• AND, OR, NOT logical operations• AS for aliases

– good for using same table twice• Subqueries• Aggregate functions (Example 18 is excellent)

– COUNT, SUM, MAX, MIN, AVG– GROUP BY

Page 37: SQL. Components of SQL Data definition language (DDL) –To create database structures –To enforce constraints etc. Data manipulation language (DML) –To

Some new SQL DML

• Nested subqueries• EXISTS / NOT EXISTS• UNION• Formatting query results• HAVING with GROUP BY• LIKE • NULL• Updating operators

Page 38: SQL. Components of SQL Data definition language (DDL) –To create database structures –To enforce constraints etc. Data manipulation language (DML) –To

Nested queries

• Get an alphabetical list of names & id’s of all students in any class taught by F110

SELECT lastName, firstName, stuIDFROM StudentWHERE stuID IN (SELECT stuID FROM Enroll WHERE classNumber IN (SELECT classNumber FROM Class WHERE facID = 'F110'))ORDER BY lastName, firstName;

1

2

3

Page 39: SQL. Components of SQL Data definition language (DDL) –To create database structures –To enforce constraints etc. Data manipulation language (DML) –To

EXISTS / NOT EXISTSCorrelated subqueries

• Names of all students enrolled in CSC201A

• Also, NOT EXISTS

SELECT lastName, firstName FROM StudentWHERE EXISTS (SELECT * FROM Enroll WHERE Enroll.stuID = Student.stuID

AND classNumber = ‘CSC201A’;

Page 40: SQL. Components of SQL Data definition language (DDL) –To create database structures –To enforce constraints etc. Data manipulation language (DML) –To

UNION

• Can be used instead of OR in a condition if the condition

SELECT facIDFROM FacultyWHERE department = 'History'

UNION SELECT facIDFROM ClassWHERE room = 'H221';

One query

Page 41: SQL. Components of SQL Data definition language (DDL) –To create database structures –To enforce constraints etc. Data manipulation language (DML) –To

Formatting query results

• List the student id and # courses each student has taken.– Uses an expression, a string constant and an

alias for a column name.

SELECT stuID, 'Number of courses =', credits/3 AS CoursesFROM Student;

Page 42: SQL. Components of SQL Data definition language (DDL) –To create database structures –To enforce constraints etc. Data manipulation language (DML) –To

HAVING

• HAVING : GROUP BY as WHERE : SELECT

• Find all courses with fewer than 3 students

SELECT className FROM EnrollGROUP BY classNameHAVING COUNT(*) < 3;

Page 43: SQL. Components of SQL Data definition language (DDL) –To create database structures –To enforce constraints etc. Data manipulation language (DML) –To

LIKE

• For pattern matching

• List the names of all Math classes

SELECT *FROM ClassWHERE classNumber LIKE 'MTH*';

In Access, use *

Page 44: SQL. Components of SQL Data definition language (DDL) –To create database structures –To enforce constraints etc. Data manipulation language (DML) –To

NULL

• Find the stuID & classes of all students with missing grades.

SELECT stuID, classNumberFROM EnrollWHERE grade IS NULL;

Can’t use = here

Page 45: SQL. Components of SQL Data definition language (DDL) –To create database structures –To enforce constraints etc. Data manipulation language (DML) –To

Updating operators

• UPDATE

• INSERT

• DELETE

Page 46: SQL. Components of SQL Data definition language (DDL) –To create database structures –To enforce constraints etc. Data manipulation language (DML) –To

UPDATE Operator

UPDATE tablename

SET columnname = expression

[columnname = expression]... [WHERE predicate];

• Used for changing values in existing records• Can update one or many records in a table

– All that meet the WHERE condition will be changed

• For null value, use SET columnname = NULL• Can use a sub-query to identify records to be updated

Page 47: SQL. Components of SQL Data definition language (DDL) –To create database structures –To enforce constraints etc. Data manipulation language (DML) –To

UPDATE examples

• See hand-out, pp. 323-325– Examples 1-6

Page 48: SQL. Components of SQL Data definition language (DDL) –To create database structures –To enforce constraints etc. Data manipulation language (DML) –To

INSERT Operator

INSERTINTO tablename [(colname [,colname]...)]VALUES (constant [,constant]...);

• Used for inserting new records into database, one at a time

• Not necessary to name columns if values are supplied for all columns, in proper order

• To insert null value for a column, specify only the other columns or write null as the value

• Can specify values for some columns, in any order, as long as values match order

Page 49: SQL. Components of SQL Data definition language (DDL) –To create database structures –To enforce constraints etc. Data manipulation language (DML) –To

INSERT examples

• See hand-out, 326-327– Examples 1-4

Page 50: SQL. Components of SQL Data definition language (DDL) –To create database structures –To enforce constraints etc. Data manipulation language (DML) –To

DELETE Operator

DELETEFROM tablenameWHERE predicate;

• Used to remove records from a table• Can delete one or many records at a time• Operation may not work if it would violate

referential integrity• Can use a sub-query to target records to be

deleted• If you delete all records from a table, its structure

still remains, and you can insert into it later

Page 51: SQL. Components of SQL Data definition language (DDL) –To create database structures –To enforce constraints etc. Data manipulation language (DML) –To

DELETE examples

• See hand-out, pp. 328-329– Examples 1-4

Page 52: SQL. Components of SQL Data definition language (DDL) –To create database structures –To enforce constraints etc. Data manipulation language (DML) –To

Exercises

• Use the ASSIGNS DDL commands to create an Access database– Code the SQL commands for

• Hand-out, pp. 355-356, problems 6.3-6.9; 6.11-6.21

– Code the SQL commands for• Hand-out, pp. 357-358, Lab Exercise 6.2c

Page 53: SQL. Components of SQL Data definition language (DDL) –To create database structures –To enforce constraints etc. Data manipulation language (DML) –To

Active Databases

• DBMS monitors database to prevent illegal states– Constraints – Triggers

Page 54: SQL. Components of SQL Data definition language (DDL) –To create database structures –To enforce constraints etc. Data manipulation language (DML) –To

Constraints

• Constraints– Specified when table is created, or later– IMMEDIATE MODE

• constraint checked when each INSERT, DELETE, UPDATE is performed

– DEFERRED MODE – see pp. 329-330• postpones constraint checking to end of transaction

SET CONSTRAINT name DEFERRED

– Can use DISABLE CONSTRAINT name, ENABLE CONSTRAINT name

Page 55: SQL. Components of SQL Data definition language (DDL) –To create database structures –To enforce constraints etc. Data manipulation language (DML) –To

Triggers

• ECA model:– Event

• some change made to the database– Condition

• a logical predicate – Action

• a procedure done when the event occurs and the condition is true, also called firing the trigger

Page 56: SQL. Components of SQL Data definition language (DDL) –To create database structures –To enforce constraints etc. Data manipulation language (DML) –To

Triggers

• Can be fired before or after – Insert– Update– Delete

• It accesses values it needs as :OLD. and :NEW.– :OLD refers to values being deleted or replaced – :NEW refers to the values just inserted or those

replacing old values• Can specify how many times a trigger fires

– once for each triggering statement, or – for each row that is changed by the statement

Page 57: SQL. Components of SQL Data definition language (DDL) –To create database structures –To enforce constraints etc. Data manipulation language (DML) –To

Trigger Syntax

CREATE TRIGGER trigger_name[BEFORE/AFTER] [INSERT/UPDATE/DELETE]

ON table_name[FOR EACH ROW] [WHEN condition]BEGIN

trigger bodyEND;

• Can ALTER TRIGGER name DISABLE;• ALTER TRIGGER name ENABLE;• DROP TRIGGER name;• See examples in Figure 6.5

Page 58: SQL. Components of SQL Data definition language (DDL) –To create database structures –To enforce constraints etc. Data manipulation language (DML) –To

Relational Views

• Can be subsets of base tables, subsets of joins, or contain calculated data

• Many reasons for views – Allow different users to see the data in

different forms– Provide a simple authorization control device– Free users from complicated DML operations– If database is restructured, view can keep the

user's model constant

Page 59: SQL. Components of SQL Data definition language (DDL) –To create database structures –To enforce constraints etc. Data manipulation language (DML) –To

Create ViewCREATE VIEW viewname [(viewcolname(s)…]

AS SELECT colname(s)...

FROM basetablename(s)…

WHERE condition(s);

• Value-independent view– A vertical subset of a table, with no WHERE,

• Value-dependent view– Choose only certain rows, using WHERE

• Join view• Can use functions in SELECT

Page 60: SQL. Components of SQL Data definition language (DDL) –To create database structures –To enforce constraints etc. Data manipulation language (DML) –To

Using Views• Views can be queried

– SELECT colname(s) FROM viewname– Views can be used to create other views

• Views can be updated – The primary key must be in the view– An INSTEAD OF trigger is used to update base

table(s), and the change is reflected in the view

CREATE TRIGGER InsertStuVw2INSTEAD OF INSERT ON StudentVw2FOR EACH ROWBEGIN

INSERT INTO StudentVALUES (:NEW.stuId, :NEW.lastName, :NEW.firstName,

:NEW. Credits);

END;

Page 61: SQL. Components of SQL Data definition language (DDL) –To create database structures –To enforce constraints etc. Data manipulation language (DML) –To

Ending Transactions

• COMMIT makes permanent changes in the current transaction

• ROLLBACK undoes changes made by the current transaction