sql prof. sin-min lee department of computer science san jose state university

67
SQL PROF. Sin-Min LEE Department of Computer Science San Jose State University

Post on 20-Dec-2015

215 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: SQL PROF. Sin-Min LEE Department of Computer Science San Jose State University

SQL

PROF. Sin-Min LEE

Department of Computer Science

San Jose State University

Page 2: SQL PROF. Sin-Min LEE Department of Computer Science San Jose State University

• What is SQL?

• Motivation

•How is it used

Page 3: SQL PROF. Sin-Min LEE Department of Computer Science San Jose State University

Non-procedural Language Data Definition Data Management Data Manipulation (Query)

Page 4: SQL PROF. Sin-Min LEE Department of Computer Science San Jose State University
Page 5: SQL PROF. Sin-Min LEE Department of Computer Science San Jose State University

Powerful

Easy to learn Flexible

ANSI/ISO Standard

Page 6: SQL PROF. Sin-Min LEE Department of Computer Science San Jose State University

Data DefinitionThe SQL Data Definition Language (DDL)

allows us to create and destroy database objects such as schemas, domains, tables, views, and indexes. The ISO standard also allows the creation of assertions,

character sets, collations

and translations.

Page 7: SQL PROF. Sin-Min LEE Department of Computer Science San Jose State University

The main SQL data definition language statements are: CREATE SCHEMA DROP SCHEMA CREATE DOMAIN ALTER DOMAIN DROP DOMAIN

Page 8: SQL PROF. Sin-Min LEE Department of Computer Science San Jose State University

CREATE TABLE ALTER TABLE DROP TABLE CREATE VIEW DROP VIEW

While CREATE INDEX and

DROP INDEX are provided

by DBMS

Page 9: SQL PROF. Sin-Min LEE Department of Computer Science San Jose State University
Page 10: SQL PROF. Sin-Min LEE Department of Computer Science San Jose State University

As a Data Definition Language

• Create the database and its table structure

• Create the tables - CREATE TABLE command

• Entity integrity• Referential integrity

• automatically enforced

Page 11: SQL PROF. Sin-Min LEE Department of Computer Science San Jose State University

CREATE TABLE Library ( 1 L_Code VCHAR(10) NOT NULL UNIQUE 2 L_City VCHAR(10) NOT NULL 3 L_Size INTEGER NOT NULL 4 B_Code INTEGER 5 6 PRIMARY KEY (L_Code), 7 FOREIGN KEY (B_Code ) );

CREATE TABLE Library ( 1 L_Code VCHAR(10) NOT NULL UNIQUE 2 L_City VCHAR(10) NOT NULL 3 L_Size INTEGER NOT NULL 4 B_Code INTEGER 5 6 PRIMARY KEY (L_Code), 7 FOREIGN KEY (B_Code ) );

Page 12: SQL PROF. Sin-Min LEE Department of Computer Science San Jose State University

Basic Data Management Commands

• INSERT Add Data to the Table • SELECT Check the Table Contents• COMMIT Save the Table Contents • UPDATE Make changes

• DELETE Delete Table Rows• ROLLBACK Restore Table Contents

Page 13: SQL PROF. Sin-Min LEE Department of Computer Science San Jose State University
Page 14: SQL PROF. Sin-Min LEE Department of Computer Science San Jose State University
Page 15: SQL PROF. Sin-Min LEE Department of Computer Science San Jose State University

SQL IDENTIFIERSQL Identifiers are used to

identify objects in the database. The characters that can be used in a userdefined SQL identifier must appear in a character test. The following restrictions are imposed on an identifier:

Page 16: SQL PROF. Sin-Min LEE Department of Computer Science San Jose State University

An identifier can be no longer than 128 characters (most dialects have a much lower limit than this ).

An identifier must start with a letter.

An identifier can not contain spaces.

Page 17: SQL PROF. Sin-Min LEE Department of Computer Science San Jose State University

The ISO SQL Data TypesThere are six SQL scalar data types defined in

the ISO standard, which are: character, bit, exact numeric, approximate numeric, datetime, and interval. Sometimes for manipulation and conversion purposes, the data types character and bit are collectively referred to as string data types, and exact numeric and approximate numeric are referred to as numeric data types, as they share similar properties.

Page 18: SQL PROF. Sin-Min LEE Department of Computer Science San Jose State University
Page 19: SQL PROF. Sin-Min LEE Department of Computer Science San Jose State University
Page 20: SQL PROF. Sin-Min LEE Department of Computer Science San Jose State University
Page 21: SQL PROF. Sin-Min LEE Department of Computer Science San Jose State University
Page 22: SQL PROF. Sin-Min LEE Department of Computer Science San Jose State University
Page 23: SQL PROF. Sin-Min LEE Department of Computer Science San Jose State University
Page 24: SQL PROF. Sin-Min LEE Department of Computer Science San Jose State University
Page 25: SQL PROF. Sin-Min LEE Department of Computer Science San Jose State University
Page 26: SQL PROF. Sin-Min LEE Department of Computer Science San Jose State University

Based on SELECT COMMAND * is wildcard character - gives “all rows” Use mathematical or logical operators to

restrict output Ordered lists with ORDER BY SQL numeric functions

COUNT, MIN, MAX, AVG, & SUM

Page 27: SQL PROF. Sin-Min LEE Department of Computer Science San Jose State University

•Partial Listing of Table Contents

SELECT <column(s)> FROM <table name>

WHERE <condition>

SELECT Tiger FROM ANIMAL WHERE A_class = Bengal

Page 28: SQL PROF. Sin-Min LEE Department of Computer Science San Jose State University

Logical Operators: AND, OR, & NOT

SELECT Tiger FROM ANIMAL WHERE A_class = Bengal OR A_class = Asian

Page 29: SQL PROF. Sin-Min LEE Department of Computer Science San Jose State University

BETWEEN - define range limits IS NULL - check if attribute value is null LIKE - check for similar character strings IN - check if attribute value matches a value

within a (sub)set of listed values EXISTS - check whether attribute has a

value

SPECIAL OPERATORS

Page 30: SQL PROF. Sin-Min LEE Department of Computer Science San Jose State University

DEFINITION

SQL(Structured Query Language) is the industry standard relational query language. It was first designed at IBM. There are several versions of SQL standards(SQL - 86, SQL - 89, X/Open, SQL - 92, SQL3). Each vendor also has its own extensions of the SQL language

DDL(Data Definition Language) are the commands that create a database schema

DML(Data Manipulation Language) are the commands that deal with data in a database(inserts, deletes, updates, and data retrieval)

Page 31: SQL PROF. Sin-Min LEE Department of Computer Science San Jose State University

Differences between Tables and Relations Tables typically allow duplicates Attributes names are ordered in a table Cannot always identify a candidate key or a primary

key in a table

Page 32: SQL PROF. Sin-Min LEE Department of Computer Science San Jose State University

Example relations:DEPT dname location

EECS Cory

Math Evans

DEPT2 dname location

EECS Cory

CS Soda

STUDENT name regno gpa level dept

Mike 1 3.5 3 EECS

Jenny 2 3.8 4 Math

COURSE cname cno dept

Database CS57 CS

Discrete Math Math55 Math

TAKE regno cno

1 CS57

1 Math 55

2 CS57

Page 33: SQL PROF. Sin-Min LEE Department of Computer Science San Jose State University

DDL Commands Create a table:

create table: table_name attributes_description

Example:

create table STUDENT

(name char(30) not null,

regno integer not null,

gpa float null,

level smallint default 1 not null,

dept varchar(20) null)

Page 34: SQL PROF. Sin-Min LEE Department of Computer Science San Jose State University

Cont. Where default specifies a default value for the

column, not null indicates that null values are not allowed for that attribute. If you do not specify null or not null SQL Server uses not null by default

Page 35: SQL PROF. Sin-Min LEE Department of Computer Science San Jose State University

SQL Server Data Types int, integer: 4 byte integer smallint: 2 byte integer tinyint: 1 byte integer float: 4 or 8 byte floating point number real: 4 byte floating point number double precision: 8 bype floating point number numeric, decimal(precision, scale): exact

numeric, 2 to 17 bytes. Only difference is that only numeric types with a scale of 0 can be used of the IDENTITY column.

Destroy a table: drop table table_name

Page 36: SQL PROF. Sin-Min LEE Department of Computer Science San Jose State University

SQL Server Data Types-cont. Char(length) : fixed length character string. 255 characters or less

varchar(length): variable length character string. 255 characters or less

nchar(length), nvarchar(length): for multibyte character sets

text: up to 2G bytes, storage is multiples of 2 K datetime: 8 bytes money: 8 bytes other data types: binary, varbinary, image, bit

Page 37: SQL PROF. Sin-Min LEE Department of Computer Science San Jose State University

Basic Insert: Inserting a Tuple into a Table

Insert one tuple into table:

insert into table_name[(column_list)] values(value_list) Ex: specify values for all attributes:

insert into STUDENT values(‘Mike’, 1, 3.8, 3, ‘CS’) Ex: specify values for only some attributes:

insert into STUDENT(name, regno, level)

values (‘Jenny’, 2, 1) NOTE: in SQL, strings are surrounded by single quote, not double

quote. Double quotes surround identifiers that contain special characters. To include a single quote in the string use two single quotes (eg.,’it’’s good’)

Page 38: SQL PROF. Sin-Min LEE Department of Computer Science San Jose State University

Basic Select: Retrieving Data from One Table Names of all students:

select name

from STUDENT use distinct to eliminate duplicates:

select distinct name

from STUDENT

Page 39: SQL PROF. Sin-Min LEE Department of Computer Science San Jose State University

Basic Select - cont use built-in function(SQL Server specific):

select getdate()

select datename(month, getdate())

select user

NOTE: the from clause is required in the SQL standard

have expression in the select list(convert gps to 5.0 scale):

select regno, gpa / 4.0 * 5.0

from STUDENT default type conversion between all numeric data types and

money

Page 40: SQL PROF. Sin-Min LEE Department of Computer Science San Jose State University

Basic Select - cont.

Select all attributes of a table:

select *

from STUDENT Select a subset of tuples(CS seniors):

select name, regno

from STUDENT

where dept = ‘CS’ and level = 4

Page 41: SQL PROF. Sin-Min LEE Department of Computer Science San Jose State University

Basic Select - cont.

Sort the results of a select. All students in ascending order of name. For students with the same name, sort in descending order of regno. Ascending is the default sor order

select name, regno

from STUDENT

order by name asc, regno desc

NOTE: order by cannot used inside a subquery

Page 42: SQL PROF. Sin-Min LEE Department of Computer Science San Jose State University

Joins: Select Condition Involving Multiple Tables All students taking CS 57

select s.*

from STUDENT s, TAKE t

where s.regno = t.regno and t.cno = ‘cs57’

s and t in the from clause are called correlation names Departments located in the same building

select distinct d1.name, d2.name

from DEPT1 d1, DEPT d2

where d1.location = d2.location

Page 43: SQL PROF. Sin-Min LEE Department of Computer Science San Jose State University

Joins: cont. Get rid of combination of same attributes values:

select d1.name, d2.name

from DEPT d1, DEPT d2

where d1.location = d2.location and d1.name > d2.name

Avoid duplicate attributes names by renaming attributes

select d1.name as name1, d2.name as name2

from DEPT d1, DEPT d2 All employees who make more than their manager

table: EMP (name, salary, manager)

select e.name, m.name

where e.manager = m.name and e.salary > m.salary

Page 44: SQL PROF. Sin-Min LEE Department of Computer Science San Jose State University

Joins: cont. Join 3 tables: all student taking cs classes

select distinct s.*

from STUDENT s, TAKE t, COURSE c

where s.regno = t.regno and t.cno = c.no and c.dept = ‘CS’

All students taking classes from their own department

select distinct s.*

from STUDENT s, TAKE t, COURSE c

where s.regno = t.regno and t.cno = c.cno and c.dept = s.dept

Page 45: SQL PROF. Sin-Min LEE Department of Computer Science San Jose State University

Joins: cont.Join 4 tables: all students taking classes offered by departments located in Evans.

select distinct s.*from STUDENT s, TAKE t, COURSE c,

DEPT dwhere s.regno = t.regno and t.cno = c.cno and

c.dept = d.dname and d.location = ‘Evans’

All students taking CS classes: their names, regno, and the CS classes they take

select s.name, s.regno, c.cnofrom STUDENT s, TAKE t, COURSE cwhere s.regno = t.regno and t.cno = c.cno and

c.dept = ‘CS’ order by s.regno, s.name, c.cno

Page 46: SQL PROF. Sin-Min LEE Department of Computer Science San Jose State University

Outer Join All students and their department location

select s.name, d.location

from STUDENT s, DEPT d

where s.dept *= d.dname

*= includes all rows from the first table

=* includes all rows from the second table:

select s.name, d.location

from STUDENT s, DEPT d

where d.dname = *s.dept

Page 47: SQL PROF. Sin-Min LEE Department of Computer Science San Jose State University

Aggregate Functions There are five of them : count, sum, avg, max, min Count number of student names

select count (distinct name) from STUDENT Count number of students

select count (*) from STUDENT Count distinct names of senior student in CS

select count(distinct name)

from STUDENT s where s.level = 4 and s.dept = ‘CS’ All aggregate functions always return one value. If the table is empty, count

returns 0, the other return null. Get aggregates of groups by using group by: get every dept’s gpa average

select dept, avg(gpa)

from STUDENT group by dept

Each expression in the target list must be grouping columns or aggregates

Page 48: SQL PROF. Sin-Min LEE Department of Computer Science San Jose State University

Aggregate Functions-cont Get gpa average of each dept and level

select dept, level, avg(gpa)

from STUDENT group by dept, level Get seniors average gpa for each dept

select dept, avg(gpa)

from STUDENT s where s.level = 4

group by s.dept Restrict aggregate values of groups by using having: get all depts with more

than 40 senior student

select dept

from STUDENT s

where s.level = 4

group by s.dept

having count(*) > 40

When there is no group by, the entire table is considered a group

Page 49: SQL PROF. Sin-Min LEE Department of Computer Science San Jose State University

Nested Queries All students who is in a dept located in Evans

select s.*

from student s

where dept in

(select d.dname

from dept d

where d.location = ‘Evan’

Conceptually, the inner subquery is evaluated first to get all the depts located in Evans. Then the outer query is evaluated. This query can also be formulated using join

Page 50: SQL PROF. Sin-Min LEE Department of Computer Science San Jose State University

[not]exists Exists returns true if its argument set is not empty, and false

otherwise. Not exists is particularly useful for a certain type of queries.

Courses taken by any CS seniors(at least one CS senior taking the courses)

select c.*

from COURSE c

where exists

(select s.*

from STUDENT s, TAKE t

where s.level = 4 and s.dept = ‘CS’ and s.regno = t.regno and t.cno = c.cno)

Page 51: SQL PROF. Sin-Min LEE Department of Computer Science San Jose State University

ANY, ALLa >= any (select query) : true if a >= x for any x where x

is a value returned by the subquerya >= all (select query) : true if a >= x for all x where x is

a value returned by the subqueryThe subquery must have exactly one element in its

target list. Result of the subquery is a set of values Students who are in a department located in Evans

select s.*from student swhere s.dept = any (select d.name from DEPT

d where d.location = ‘Evan’) Students having the best gpa

select s.*from student swhere s.gpa >= all(select s1.gpa from student

s1)

Page 52: SQL PROF. Sin-Min LEE Department of Computer Science San Jose State University

UNIONGive the union of the results of multiple subqueries. Duplicates are always eliminated. But if you say union all, duplicates are not removed. If you say union all once, you must say it for all unions within one statement. All subselects must have the same number of columns with matching types. Columns of numeric types cannot be matched with columns of character types

Students who are seniors, or have gpa better than 3.0, or are taking cs57

select s.name, s.regno

from STUDENT s

where s.level = 4

union

select s.name, s.regno

from STUDENT s

where s.gpa > 3.0

Page 53: SQL PROF. Sin-Min LEE Department of Computer Science San Jose State University

UNION - contunion

select s.name, s.regno

from STUDENT s, TAKE t

where s.regno = t.regno and t.cno = ‘cs57’ Note: union cannot be used inside a subquery

Page 54: SQL PROF. Sin-Min LEE Department of Computer Science San Jose State University

UPDATEBasic form is:

update table_name

set column_name = {expression | select_stmt}

[, column_name = {expression | select_stmt}]…

[from table_name [,table_name]…]

[where search_condition] The expression in the set clause can contain constants, column values from

the table being updated, or column values from tables in the from clause. If a column value of the table being updated appears in an expression, it refers to the old value.

NOTE: the select_stmt in the set clause is Sybase SQL Server specific, the [from…] clause is Sybase SQL Server specific

All students whose gpa is better than or equal to 2.0 can move up one level:

update student

set level = level + 1

where gpa >= 2.0

Page 55: SQL PROF. Sin-Min LEE Department of Computer Science San Jose State University

UPDATE Give all managers who make less than someone working for

them a 5% raise:

update EMP

set salary = salary * 1.05

where salary < any (select e.salary from EMP e where e.manage = e.name)

Page 56: SQL PROF. Sin-Min LEE Department of Computer Science San Jose State University

DELETE Basic form is:

delete from tablename

[where search_condition]

The delete statement removes rows that satisfy the search_condition from tablename

Expel all students who have been around for more than 20 years

delete from student

where level > 0 Fire all employees who make more than their managers

delete from EMP

where salary > (select e.salary from EMP e where e.name = e.manager)

Page 57: SQL PROF. Sin-Min LEE Department of Computer Science San Jose State University

INSERT from the results of a subselectCan insert the result of a select query into another table Suppose there is a table WAITING(regno, cno) for the

class waiting list. Add all CS seniors on the CS 57 waiting list to the CS 57 enrollment list

insert into TAKE select distinct w.regno, w.cno

from WAITING w, STUDENT s

where w.cno = ‘cs57’ and s.regno = w.regno

and s.dept = ‘CS’ and s.level = 4 Create a new table for the results of a select:

select distinct w.regno, w.cno

into TAKE

from WAITING w, STUDENT s

where w.cno = ‘cs57’ and s.regno = w.regno

and s.dept = ‘CS’ and s.level = 4

Page 58: SQL PROF. Sin-Min LEE Department of Computer Science San Jose State University

More Example:DEPT (dname, location)dname location

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

CS Soda

EECS Cory

Math Evans

Music Morrison

Economic Evans

Page 59: SQL PROF. Sin-Min LEE Department of Computer Science San Jose State University

Example cont.EMP (name, emp_no, salary, dname, start_date, leave_date)name emp_no salary dname start_date leave_date

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

YDWang 1 80000.000000 CS Jan1 89 12:00AM NULL

George 2 100200.000000 CS Apr 5 92 12:00AM NULL

Ben Ling 3 85000.000000 CS De14 79 12:00AM NULL

Jennifer 4 90000.000000 CS Jul 2078 12:00AM NULL

Mark 5 70000.000000 EECS Jun11 81 12:00AM NULL

Page 60: SQL PROF. Sin-Min LEE Department of Computer Science San Jose State University

Diane 6 60000.000000 CS

Jan 1 1994 12:00AM NULL

Cary 7 80000.000000 CS

Nov 3 1976 12:00AM NULL

Geena 8 100000.000000 Music

Apr 25 1991 12:00AM Aug 25 1994 12:00AM

Nino 9 61000.000000 Math

May 1 1992 12:00AM Jan 10 1994 12:00AM

Goodman 10 70500.000000 Math

Feb 15 1994 12:00AM NULL

Johnny 11 100.000000 Math

Mar 18 1994 12:00AM Jan 5 1995 12:00AM

Andre 12 200.000000 Music

Aug 23 1994 12:00AM NULL

Debi 13 40000.000000 Math

May 20 1992 12:00AM NULL

Francis 14 12000.000000 EECS

Jul 30 1982 12:00AM NULL

Page 61: SQL PROF. Sin-Min LEE Department of Computer Science San Jose State University

Basic Query StructureSelect A1, A2,………….., An

from r1, r2 , r3…………… rm

where P

This is equivalent to

π A1, A2,…… An( σ P (r1 x r2 x……..x rm))

if no where clause, P =TRUE if A1, A2………. An are replaced by *, then all

attributes of r1, r2……. rm are retrieved

ri.* retrieves all attributes of ri

Page 62: SQL PROF. Sin-Min LEE Department of Computer Science San Jose State University

Basic Query Structure(cntd) In practice, SQL systems convert a

SELECT statement to a form suitable for efficient implementation (don’t really do a X product).

Page 63: SQL PROF. Sin-Min LEE Department of Computer Science San Jose State University

Example - a Vet clinic

customer

owns

pet

name

typebirthyr

treated

Is primary provider

vet

name

office

Ph#datediscussion

Page 64: SQL PROF. Sin-Min LEE Department of Computer Science San Jose State University

Table scheme & a query

Customer(cno, name, addr, ph#)

pet(pno, name, type, birthyr, vno, cno)

vet(vno, name, office, ph#)

treated(vno, pno, date, discussion)

Find pet named “Fluffy”

select *

from pet

where name = “Fluffy”

Page 65: SQL PROF. Sin-Min LEE Department of Computer Science San Jose State University

Queries (cntd.)

Find owner name and ph# for Fluffy

select customer.name, ph#

from customer, pet

where customer.cno = pet.cno

and pet.name = “Fluffy”

Page 66: SQL PROF. Sin-Min LEE Department of Computer Science San Jose State University

Queries (cntd.) Find all primary providers for pets owned

by “Solange”

select vet.name

from vet, pet, customer

where customer.cno = pet.cno

and pet.vno = vet.vno

and customer.name = “Solange”

Page 67: SQL PROF. Sin-Min LEE Department of Computer Science San Jose State University

Quiz Give SQL query for:

Find the vet named Bob. Find the name of each customer, pet and vet

where the customer’s pet was treated by that vet on “5/18/98”.