Вы находитесь на странице: 1из 26

Agenda

• Relational Constraints
• Keys
• Relational Algebra
• Structured Query Language (SQL)
Relational Constraints

• Three Basic Integrity Constraints


– Constraints that are built into the relational data model
– Can be enforced by Data Definition Language (DDL) in
most systems
• Primary Key Constraint
– Uniqueness & Minimality
• Entity Constraint
– The Primary Key of a relation cannot be null
• Referential Integrity Constraint
– The value of a Foreign Key, if not null, must exist in the original
relation
Relational Constraints

• Application-Dependent Constraints

– Domain constraints (range, min/max, enumerated


values)
• Enforced by using the CHECK clause in SQL
– Semantic constraints
• Enforced by triggers, stored procedures, and programs
Keys

• Primary Key (PK)


– Uniqueness: uniquely identify each tuple (i.e. row) in a
relation
– Minimality: the least amount of attributes to uniquely
identify each tuple
• Foreign Key (FK)
– An attribute which is a PK in another relation
• Composite Key or Concatenated Key
– A PK that consists of multiple attributes
Keys

• Candidate Key (CK)


– A set of attributes which can be used as a PK
– Example
• Doctor(SSN, Name, License#, DriverL#, Specialty, Age, School)
• CKs = {SSN, License#, DriverL#}
• Alternate Key
– A candidate key that was not designated as the PK
– Example
• If SSN is the PK, then all of the other CKs are alternate keys
Keys

• Secondary key
– An attribute that is used for an index
• Search key
– An attribute that is used in a query
Relational Algebra
• A basis for implementation of any relational query language
• A procedural language
Relations for Examples
• Set-at-a-time language Emp1 eno name Emp2 eno name Work eno dept

• Unary Operations 1
2
JOHN
TOM
3
5
JOHN
MARY
1
4
SALES
SALES
– SELECT 3 JOHN 5 TOY
4 BOB
• Extracts tuples (rows) that satisfy a condition
• Notation  condition(relation name)
• Example:
– Find all employees in the SALES department
» dept=“SALES”(Work) Work eno dept
1 SALES
– Find all employees that do not work for the TOY department and whose eno
4
isSALES
greater
than 2
» (eno>2) and (dept “TOY”)(Work)
– Can use any of the comparison operators (=, , <, , >, ) and
Work eno logical
dept operators (AND, OR,
NOT) 4 SALES
Relational Algebra
Relations for Examples

• Unary Operations Emp1 eno name


1 JOHN
Emp2 eno name
3 JOHN
Work eno
1
dept
SALES
2 TOM 5 MARY 4 SALES
– PROJECT 3 JOHN 5 TOY
4 BOB
• Extracts attributes (columns) from a relation
• After projection, duplicate rows are removed
• Notation  condition(relation name)
• Example
– Find all employee names from emp1
– name(Emp1) name
JOHN
TOM
JOHN
BOB
SQL: Overview
• What is SQL?
– Structured Query Language
– Developed at IBM’s San Jose research lab in early 1970s
– First called “Sequel”, then later renamed “SQL”
– SQL is descriptive (what to get), not a procedural language
(how to get)
– It is a SET-based language
– It is the real world implementation of Relational Algebra
SQL: Overview (continued)
• What is SQL?
– Currently SQL-92 is the most implemented
standard by most vendors.

– SQL-99, which includes Object-Oriented Data


Management, and some procedural commands is
being implemented in vendor’s own flavors
SQL: Language Subsets
• SQL
– DDL: Data Definition Language
• Create, Alter, Drop

– DCL: Data Control Language


• Grant and Revoke

– DML: Data Manipulation Language


• Select, Insert, Update, Delete
SQL: DDL

• SQL  DDL  is  used  for  creating  and  destroying  DB  objects:  – 
Domains, Tables, Views, Indexes…
– Main SQL DDL statements are:

CREATE TABLE/ALTER TABLE DROP TABLE
CREATE VIEW DROP VIEW
CREATE INDEX DROP INDEX
Example:
CREATE TABLE Student (
sid CHAR(2),
firstName VARCHAR(15) ,
lastName VARCHAR(20) ,
login VARCHAR(7),
dob DATE
);
SQL

• Enforcement of basic constraints in SQL


– Primary Key
• PRIMARY KEY clause
– Entity constraint
• NOT NULL keywords
– Referential integrity constraint
• FOREIGN KEY…REFERENCES clause
– Alternate key
• UNIQUE clause

• Application-dependent constraints
– Domain constraint
• CHECK clause
SQL
• Another Example
create table employee(
employeeID number(5),
ssn char(9),
fName varchar(15)
lName varchar(15),
deptID number not null,
gender char(1),
constraint employee_pk primary key(employeeID),
constraint employee_fk1 foreign key (deptID) references
department(deptID) on delete restrict on update cascade,
constraint employee_uq1 unique (ssn),
constraint employee_ck1 check (gender IN (‘M’, ‘m’, ‘F’, ‘f’)));
SQL: DDL

• Examples for ALTER TABLE


ALTER TABLE Student MODIFY (
lastName VARCHAR(25));

ALTER TABLE Student ADD(


gpa NUMBER(3,2));

• Example for DROP TABLE


DROP TABLE Student;
SQL: DCL
• Syntax
GRANT {PrivilegeList | ALL PRIVILEGES}
ON ObjectName
TO {AuthorizationIdList | PUBLIC}
[WITH GRANT OPTION]

• Examples
a) Give Manager full privileges to Staff table.
GRANT ALL PRIVILEGES
ON Staff
TO Manager WITH GRANT OPTION;
b) Give Personnel and Director SELECT and UPDATE on column salary of Staff.
GRANT SELECT, UPDATE (salary)
ON Staff
TO Personnel, Director;
c) Permit SELECT and UPDATE access privileges to all users
GRANT SELECT, UPDATE ON employee, project TO PUBLIC;
SQL: DML

• SQL DML allows users to pose queries and to insert, delete


and modify data
– SELECT, INSERT, UPDATE and DELETE

• SELECT
– THE most important statement in the language, with
maximum options/variations to it.
– Implements 3 relational algebra operations
• Selection, Projection, Join
SQL: DML  SELECT

• Parts of SELECT statement


– SELECT clause : For Selection
– FROM clause : Which ‘Relation/Relations’ to use
– WHERE clause : For Join conditions, and Filtering
(i.e. search condition)
– ORDER BY : For sorting the output
– GROUP BY : For creating ‘data buckets’
– HAVING : For ‘filtering’ the ‘data buckets’
SQL: DML  SELECT
• WHERE (used to specify search conditions)
– Comparison
• =, >, <, <>, NOT, AND, OR
– Range Search
• BETWEEN, NOT BETWEEN
– Set Membership search
• IN, NOT IN
– Pattern match search condition
• LIKE, NOT LIKE
– NULL search conditions
• IS NULL, IS NOT NULL
SQL: DML  SELECT
• AGGREGATE FUNCTIONS (i.e. COLUMN FUNCTIONS)
– COUNT
– SUM
– AVG
– MIN
– MAX

• Examples:
a) SELECT AVG(e.age) FROM Employee e;

b) SELECT pnumber, pname, count(*)


FROM project, work_on
WHERE project.pnumber=work_on.pno
GROUP BY pnumber, pname
HAVING count(*) >2
ORDER BY pname;
SQL: DML  INSERT

• INSERT – 2 formats
– INSERT INTO tablename[(column_list)]…..VALUES (value_list)…..
– INSERT INTO tablename[(column_list)]…..AS SELECT…..

• Examples
a) INSERT INTO Student(sid, name, login, age, gpa) VALUES (53688, ‘SMITH’,
‘SMITH@EE’, 18, 3.2);
b) INSERT INTO project VALUES(1234, ‘PERFECT PROJECT’, NULL, ‘JOHN’);

TIP: Insert values in capital letters.


SQL: DML  UPDATE

• Syntax
UPDATE tablename SET fieldname=VALUE
[WHERE fieldname comparisonOperator VALUE];

– If WHERE clause is specified, then only those rows that satisfy the
condition will be updated
– If WHERE clause is NOT specified, then ALL rows will be updated
• Examples:

UPDATE student s SET UPDATE project SET


s.age=s.age +1 WHERE budget=1.1*budget
sid=53688; WHERE projno>1000;
SQL: DML  DELETE

• Syntax
DELETE FROM tablename
[WHERE fieldname comparisonOperator VALUE];

– If WHERE clause is specified, then only those rows that satisfy the
condition will be deleted
– If WHERE clause is NOT specified, then ALL rows will be deleted
• Examples:

DELETE FROM project DELETE FROM student;


WHERE manager =‘JOHN’;
SQL

• The result of a SQL query is a relation, but…


– Does not automatically eliminate redundant tuples
– To remove redundant records from the result set, then use
the keyword DISTINCT immediately after the keyword
SELECT
– Set operations (UNION, INTERSECTION and MINUS) do
remove redundant tuples
– Attributes are stored by the sequence in which they are
listed in the CREATE command
– Tuples are not ordered

• SELECT in SQL is the same as PROJECT in the


relational algebra
SQL

• Convention for NULL values in SQL


– Null value is allowed as the default
– Use keywords NOT NULL, if you don’t want null values
– SUM, MIN, MAX, AVG, COUNT DISTINCT do not include
null values
– COUNT includes null values
– Null values do not participate in comparisons
– Null values are not included in an index
Creating Script Files

• It is best to write your SQL statements in a script file. A


script file is a text file that has the file extension sql (e.g.
test.sql). You can use any text editor (e.g. NotePad) to
create the script file. We will use Textpad.

Вам также может понравиться