40
1 IT420: Database Management and Organization SQL - Data Manipulation Language 27 January 2006 Adina Crăiniceanu www.cs.usna.edu/~adina

1 IT420: Database Management and Organization SQL - Data Manipulation Language 27 January 2006 Adina Crăiniceanu adina

Embed Size (px)

Citation preview

1

IT420: Database Management and Organization

SQL - Data Manipulation Language27 January 2006

Adina Crăiniceanuwww.cs.usna.edu/~adina

2

Last Time

SQL: Data Definition Language CREATE, DROP, ALTER

3

Today

More SQL: Data Manipulation Language

4

Creating Tables CREATE TABLE table_name(

column_name1 column_type1 [constraints1],…,[[CONSTRAINT constraint_name] table_constraint]

)

Table constraints: PRIMARY KEY (columns) UNIQUE (columns) CHECK (conditions) FOREIGN KEY (local_columns) REFERENCE foreign_table

(foreign_columns) [ON DELETE action_d ON UPDATE action_u]

Specify surrogate key:column_name int_type IDENTITY (seed, increment)

5

CREATE TABLE Example

CREATE TABLE Students(StudentNumber integer NOT NULL,StudentLastName char(18) NOT NULL,StudentFirstName char(18) NOT NULL,Email char(50),PhoneNumber char(18),MajorDepartmentName char(18),PRIMARY KEY (StudentNumber),UNIQUE (Email) )

6

Modifying Tables

ALTER TABLE table_name clause

Clauses:

ADD COLUMN column_name column_type [constraints]

DROP COLUMN column_name

ALTER COLUMN / MODIFY – DBMS specific!

ADD CONSTRAINT constraint

DROP CONSTRAINT constraint_name

7

ALTER TABLE Examples

ALTER TABLE Students ADD COLUMN BirthDate datetime NULL

ALTER TABLE Students DROP COLUMN BirthDate

ALTER TABLE Student ADD CONSTRAINT DepartmentFK FOREIGN KEY (MajorDepartmentName)REFERENCES Departments (DepartmentName) ON DELETE NO ACTIONON UPDATE CASCADE

8

Removing Tables

DROP TABLE table_nameDROP TABLE Departments;

If there are constraints: Remove constraints Drop table

ALTER TABLE Students

DROP CONSTRAINT DepartmentFK;

DROP TABLE Departments;

9

SQL DML

Data manipulation language (DML) statements.

Used for queries and data modification INSERT DELETE UPDATE SELECT

10

INSERT Statement

INSERT command:INSERT INTO Students (StudentNumber, StudentLastName,

StudentFirstName)VALUES (190, ‘Smith', ‘John’)

INSERT INTO Students VALUES(190, ‘Smith’, ‘John’, ‘[email protected]’, ‘410-431-3456’, ‘ComSci’)

Bulk INSERT:INSERT INTO Students (StudentNumber, StudentLastName,

StudentFirstName, Email, PhoneNumber, MajorDepartmentName)SELECT *FROM Second_Class_Students;

11

UPDATE Statement UPDATE command:

UPDATE StudentsSET PhoneNumber = ‘410-123-4567’WHERE StudentNumber = 673;

BULK UPDATE command:UPDATE Students

SET PhoneNumber = ‘410-123-4567’WHERE StudentLastName = ‘Doe’;

Student

Number

Student

LastName

Student

FirstName

Email PhoneNumber MajDeptName

190 Smith John [email protected] 410-431-3456 ComSci

673 Doe Jane [email protected] ComSci

312 Doe Bob [email protected] 443-451-7865 Math

12

DELETE Statement

DELETE command:DELETE FROM Students

WHERE StudentNumber = 190;

If you omit the WHERE clause, you will delete every row in the table!

Another example:DELETE FROM Departments

WHERE DepartmentName = ‘ComSci’

Integrity constraints!

13

The SQL SELECT Statement

Basic SQL Query: SELECT [DISTINCT] column_name(s)

FROM table_name(s)

[WHERE conditions]

14

Selecting All Columns: The Asterisk (*) KeywordSELECT *

FROM Students;

Student

Number

Student

LastName

Student

FirstName

Email PhoneNumber MajDeptName

190 Smith John [email protected] 410-431-3456 ComSci

673 Doe Jane [email protected] ComSci

312 Doe Jane [email protected] 443-451-7865 Math

15

Specific Columns and Rows from One TableSELECT StudentNumber,

StudentLastName, StudentFirstName

FROM StudentsWHERE MajDeptName = ‘ComSci’;

Student

Number

Student

LastName

Student

FirstName

190 Smith John

673 Doe Jane

16

The DISTINCT Keyword

SELECT SName

FROM Students;

StudentLastName

Smith

Doe

Doe

SELECT DISTINCT SName

FROM Students;

StudentLastName

Smith

Doe

17

Conceptual Evaluation Strategy

Semantics of an SQL query defined in terms of the following conceptual evaluation strategy: Compute the cross-product of table_names Discard resulting rows if they fail condition Delete columns that are not in column_names If DISTINCT is specified, eliminate duplicate rows

This strategy is probably the least efficient way to compute a query! An optimizer will find more efficient strategies to

compute the same answers.

18

Students, Courses, Enrolled

SNb SName Email

190 Smith [email protected]

673 Doe [email protected]

312 Doe [email protected]

Cid CName CDept

IT420 Databases ComSci

IT340 Networks ComSci

SM121 Calculus1 Math

SNb Cid Semester

190 IT340 Spring2006

312 IT420 Fall2005

SELECT SNameFROM Students S, Enrolled EWHERE S.Snb = E.SNb AND E.Cid = ‘IT420’

19

Example Conceptual Evaluation

S.SNb SName Email E.SNb Cid Semester

190 Smith [email protected] 190 IT340 Spring2006

190 Smith [email protected] 312 IT420 Fall2005

673 Doe [email protected] 190 IT340 Spring2006

673 Doe [email protected] 312 IT420 Fall2005

312 Doe [email protected] 190 IT340 Spring2006

312 Doe [email protected] 312 IT420 Fall2005

SELECT SNameFROM Students S, Enrolled EWHERE S.Snb = E.SNb AND E.Cid = ‘IT420’

20

Example Conceptual Evaluation

S.SNb SName Email E.SNb Cid Semester

190 Smith [email protected] 190 IT340 Spring2006

190 Smith [email protected] 312 IT420 Fall2005

673 Doe [email protected] 190 IT340 Spring2006

673 Doe [email protected] 312 IT420 Fall2005

312 Doe [email protected] 190 IT340 Spring2006

312 Doe [email protected] 312 IT420 Fall2005

SELECT SNameFROM Students S, Enrolled EWHERE S.Snb = E.SNb AND E.Cid = ‘IT420’

21

Example Conceptual Evaluation

S.SNb SName Email E.SNb Cid Semester

190 Smith [email protected] 190 IT340 Spring2006

190 Smith [email protected] 312 IT420 Fall2005

673 Doe [email protected] 190 IT340 Spring2006

673 Doe [email protected] 312 IT420 Fall2005

312 Doe [email protected] 190 IT340 Spring2006

312 Doe [email protected] 312 IT420 Fall2005

SELECT SNameFROM Students S, Enrolled EWHERE S.Snb = E.SNb AND E.Cid = ‘IT420’

SName

Doe

22

Modified Query

SELECT SNb

FROM Students S, Enrolled E

WHERE S.Snb = E.SNb AND E.Cid =‘IT420’

Would the result be different with DISTINCT?

23

Class Exercise

Students(SNb, SName, Email) Courses(Cid,CName, Dept) Enrolled(SNb,Cid, Semester)

Find the student number and name for each student enrolled in ‘Spring2006’ semester

Find the names of all students enrolled in ‘ComSci’ courses

24

Sorting the Results

SELECT …FROM …[WHERE …]ORDER BY column_name(s) [ASC/DESC]

Example:SELECT SNb, SNameFROM StudentsORDER BY SName ASC, SNb DESC

25

WHERE Clause Options

AND, OR IN, NOT IN, BETWEEN

SELECT SNb

FROM Students S, Enrolled E

WHERE S.SNb = E.Nb AND

E.Cid NOT IN (‘ComSci’, ‘Math’)

26

LIKE and Wildcards

SELECT *

FROM Students

WHERE SNb LIKE ‘_9_%’

SQL 92 Standard (SQL Server, Oracle, etc.): _ = Exactly one character % = Any set of one or more characters

MS Access ? = Exactly one character * = Any set of one or more characters

27

Calculations in SQL

Simple arithmetic Five SQL Built-in Functions:

COUNT SUM AVG MIN MAX

28

Simple Arithmetic

SELECT NbHours* HourlyRate AS Charge

FROM FlightEvents

SELECT SFirstName + ‘ ’ + SLastName

FROM Students

29

Aggregate Operators

SELECT COUNT(*)FROM Students

SELECT COUNT(DISTINCT SName)FROM StudentsWHERE SNb > 700

SELECT AVG(Age)FROM Students, EnrolledWHERE Stundents.SNb=Enrolled.SNb

30

Aggregate Operators Limitations

Return only one row Not in WHERE clause

31

Select oldest students and their age SELECT S.SName, MAX (Age)

FROM Students S

Illegal!

32

Select oldest students and their age SELECT S.SName, S.Age

FROM Students S

WHERE S.AGE = (SELECT MAX(Age)

FROM Students)

33

Select students with age higher than average SELECT *

FROM Students

WHERE Age > AVG(Age)

Illegal!

34

Select students with age higher than average SELECT *

FROM Students

WHERE Age > (SELECT AVG(Age)

FROM Students)

35

Aggregate Operators (cont)

So far, we’ve applied aggregate operators to all (qualifying) rows

Sometimes, we want to apply them to each of several groups of rows

Consider: Find the age of the youngest student for each class

If class values go from 1 to 4 we can write 4 queries that look like this:

SELECT MIN (S.Age)FROM Students SWHERE S.Class = i

36

GROUP-BY Clause

SELECT [DISTINCT] column_name(s)FROM table_name(s)[WHERE conditions]GROUP BY grouping_columns

SELECT MIN(Age)FROM StudentsGROUP BY Class

37

Conceptual Evaluation

Semantics of an SQL query defined as follows: Compute the cross-product of table_names Discard resulting rows if they fail conditions Delete columns that are not in column_names Remaining rows are partitioned into groups by the

value of the columns in grouping-columns One answer row is generated per group

Note: Does not imply query will actually be evaluated this way!

38

HAVING Clause

SELECT [DISTINCT] column_name(s)FROM table_name(s)[WHERE conditions]GROUP BY grouping_columnsHAVING group_conditions

HAVING restricts the groups presented in the result

39

Example

SELECT MIN(Age)

FROM Students

WHERE MajDeptName = ‘ComSci’

GROUP BY Class

HAVING Class > 2

40

Class Exercise