+ All Categories
Home > Documents > Basic SQL

Basic SQL

Date post: 30-Dec-2015
Category:
Upload: gay-holt
View: 19 times
Download: 0 times
Share this document with a friend
Description:
Basic SQL. Joe Meehean. What we are going to Learn. How do we access the data stored in a DBMS? What happens when we access data in a DBMS? How do we add or modify data in a DBMS?. Structured Query Language (SQL). Often pronounced “sequel” Standardized interface for interacting with DBMSs - PowerPoint PPT Presentation
109
BASIC SQL Joe Meehean 1
Transcript
Page 1: Basic SQL

1

BASIC SQL

Joe Meehean

Page 2: Basic SQL

2

WHAT WE ARE GOING TO LEARN

How do we access the data stored in a DBMS?

What happens when we access data in a DBMS?

How do we add or modify data in a DBMS?

Page 3: Basic SQL

3

STRUCTURED QUERY LANGUAGE (SQL)

Often pronounced “sequel” Standardized interface for interacting

with DBMSs as standardized as any CS interface gets Oracle, DB2, SQL Server, MySQL, PostgreSQL,…

Used to create/define tables destroy tables look up data insert/modify data delete data

Page 4: Basic SQL

4

STRUCTURED QUERY LANGUAGE (SQL)

Declarative language states what answer should look like NOT how to compute it e.g. “Who are the students with GPAs < 2.0?”

Page 5: Basic SQL

5

QUERYING TABLES

Looking up information in relational tables Use the SQL SELECT statement SELECT <list of columns>

FROM table Result of a SELECT is another table

Page 6: Basic SQL

6

EXTRACTING COLUMNS

SELECT LastName, MajorFROM Students

StdNo Last Name

First Name

Major GPA

732 Arnett Will Theatre 3.74

967 Crumb Robert Art 2.3

764 Vogelzang

Anna Music 3.5

568 Park Phil CS 3.6

587 Park Anna CS 3.9

Students

Page 7: Basic SQL

7

EXTRACTING COLUMNS

SELECT LastName, MajorFROM Students

StdNo Last Name

First Name

Major GPA

732 Arnett Will Theatre 3.74

967 Crumb Robert Art 2.3

764 Vogelzang

Anna Music 3.5

568 Park Phil CS 3.6

587 Park Anna CS 3.9

Students

Page 8: Basic SQL

8

EXTRACTING COLUMNS

SELECT LastName, MajorFROM Students

Last Name

Major

Arnett Theatre

Crumb Art

Vogelzang

Music

Park CS

Park CS

Result

Page 9: Basic SQL

9

EXTRACTING COLUMNS

SELECT LastName, MajorFROM Students

Note the duplicate rows in the result

Last Name

Major

Arnett Theatre

Crumb Art

Vogelzang

Music

Park CS

Park CS

Result

Page 10: Basic SQL

10

EXTRACTING COLUMNS

SELECT DISTINCT LastName, MajorFROM Students

DISTINCT removes duplicate rows

Last Name

Major

Arnett Theatre

Crumb Art

Vogelzang

Music

Park CS

Result

Page 11: Basic SQL

11

GETTING ALL THE COLUMNS

SELECT * returns all columns

Student ID

LastName

FirstName GPA

S01 Daniels Rush 3.4

S02 Blem Emily 3.9

S03 Cook Matt 2.4

S04 Park Phil 3.5

SELECT *FROM Students

Students

Page 12: Basic SQL

12

GETTING ALL THE COLUMNS

SELECT * returns all columns

Student ID

LastName

FirstName GPA

S01 Daniels Rush 3.4

S02 Blem Emily 3.9

S03 Cook Matt 2.4

S04 Park Phil 3.5

SELECT *FROM Students

Result

Page 13: Basic SQL

13

CALCULATED FIELDS

Create new columns using arithmetic Can use +, −, *, /, ( ) Should name new column Use the AS keyword

Page 14: Basic SQL

14

CALCULATED FIELDS

SELECT PartNo, Pdesc, Pqty * Wholsale AS StockCostFROM Parts

PartsPartNo PQty PDesc Wholesale

P1 2 5mm bolt $0.55

P2 4 10mm nut $0.23

P3 2 5mm wrench $2.50

P4 4 8mm washer $0.67

Page 15: Basic SQL

15

CALCULATED FIELDS

SELECT PartNo, Pdesc, Pqty * Wholsale AS StockCostFROM Parts

ResultPartNo StockCost PDesc

P1 $1.10 5mm bolt

P2 $0.92 10mm nut

P3 $5.00 5mm wrench

P4 $2.68 8mm washer

Page 16: Basic SQL

16

EXTRACTING SPECIFIC ROWS

Add the WHERE clause to the SELECT SELECT <columns,…>

FROM <table>WHERE <condition>

WHERE conditions similar to C++ conditions

Page 17: Basic SQL

17

EXTRACTING SPECIFIC ROWS

Student ID

LastName

FirstName GPA

S01 Daniels Rush 3.4

S02 Blem Emily 3.9

S03 Cook Matt 2.4

S04 Park Phil 3.5

Students

Page 18: Basic SQL

18

EXTRACTING SPECIFIC ROWS

Student ID

LastName

FirstName GPA

S01 Daniels Rush 3.4

S02 Blem Emily 3.9

S03 Cook Matt 2.4

S04 Park Phil 3.5

SELECT LastName, FirstNameFROM StudentsWHERE GPA >= 3.5

Students

Page 19: Basic SQL

19

EXTRACTING SPECIFIC ROWS

Student ID

LastName

FirstName GPA

S01 Daniels Rush 3.4

S02 Blem Emily 3.9

S03 Cook Matt 2.4

S04 Park Phil 3.5

SELECT LastName, FirstNameFROM StudentsWHERE GPA >= 3.5

Students

Page 20: Basic SQL

20

EXTRACTING SPECIFIC ROWS

Student ID

LastName

FirstName GPA

S01 Daniels Rush 3.4

S02 Blem Emily 3.9

S03 Cook Matt 2.4

S04 Park Phil 3.5

SELECT LastName, FirstNameFROM StudentsWHERE GPA >= 3.5

Students

Page 21: Basic SQL

21

EXTRACTING SPECIFIC ROWS

LastName

FirstName

Blem Emily

Park Phil

SELECT LastName, FirstNameFROM StudentsWHERE GPA >= 3.5

Result

Page 22: Basic SQL

22

EXTRACTING SPECIFIC ROWS

SQL supports following comparison operators = : equals <, <= : less than, less than or equal to >, >= : greater than, greater than or equal to <> : not equal

Combination of conditions OR: inclusive AND NOT

Page 23: Basic SQL

23

EXTRACTING SPECIFIC ROWS

SELECT PartNo, Pdesc, PqtyFROM PartsWHERE PDesc = ‘5mm wrench’ OR Pdesc = ‘10mm nut’

PartsPartNo PQty PDesc Wholesale

P1 2 5mm bolt $0.55

P2 4 10mm nut $0.23

P3 2 5mm wrench $2.50

P4 4 8mm washer $0.67

Page 24: Basic SQL

24

EXTRACTING SPECIFIC ROWS

SELECT PartNo, Pdesc, PqtyFROM PartsWHERE PDesc = ‘5mm wrench’ OR Pdesc = ‘10mm nut’

ResultPartNo PQty PDesc

P2 4 10mm nut

P3 2 5mm wrench

Page 25: Basic SQL

25

EXTRACTING SPECIFIC ROWS

LIKE operator used for inexact string matching like regular expressions % wild card for any series of characters

e.g., ‘CS%’ matches strings prefixed with CS e.g., ‘%Algebra%’ matches strings that contain Algebra

_ matches a single character e.g., ‘CS24_’ matches CS241 and CS242, but not

CS242A

Page 26: Basic SQL

26

EXTRACTING SPECIFIC ROWS

SELECT PartNo, Pdesc, PqtyFROM PartsWHERE PDesc LIKE ‘5mm %’

PartsPartNo PQty PDesc Wholesale

P1 2 5mm bolt $0.55

P2 4 10mm nut $0.23

P3 2 5mm wrench $2.50

P4 4 8mm washer $0.67

Page 27: Basic SQL

27

EXTRACTING SPECIFIC ROWS

SELECT PartNo, Pdesc, PqtyFROM PartsWHERE PDesc LIKE ‘5mm %’

ResultPartNo PQty PDesc

P1 2 5mm bolt

P3 2 5mm wrench

Page 28: Basic SQL

28

EXTRACTING SPECIFIC ROWS

Matching a range e.g., parts that cost between $0.50 and $1.00 use the BETWEEN-AND operator

SELECT *FROM PartsWHERE Wholesale BETWEEN 0.50 AND 1.00

PartsPartNo PQty PDesc Wholesale

P1 2 5mm bolt $0.55

P2 4 10mm nut $0.23

P3 2 5mm wrench $2.50

P4 4 8mm washer $0.67

Page 29: Basic SQL

29

EXTRACTING SPECIFIC ROWS

Matching a range e.g., parts that cost between $0.50 and $1.00 use the BETWEEN-AND operator

SELECT *FROM PartsWHERE Wholesale BETWEEN 0.50 AND 1.00

ResultPartNo PQty PDesc Wholesale

P1 2 5mm bolt $0.55

P4 4 8mm washer $0.67

Page 30: Basic SQL

30

EXTRACTING SPECIFIC ROWS

Testing for null IS NULL IS NOT NULL

SectionNo

<CourseNo> Term Faculty ID

A CS242 Spring null

B CS242 Spring F01

A CS370 Fall F03

A CS375 Fall F02

Offering

SELECT CourseNo, SectionNoFROM OfferingWHERE CourseNo = ‘CS242’

AND FacultyID IS NOT NULL

Page 31: Basic SQL

31

EXTRACTING SPECIFIC ROWS

Testing for null IS NULL IS NOT NULL

SectionNo

<CourseNo>

B CS242

Result

SELECT CourseNo, SectionNoFROM OfferingWHERE CourseNo = ‘CS242’

AND FacultyID IS NOT NULL

Page 32: Basic SQL

32

QUESTIONS?

Page 33: Basic SQL

33

SORTING THE RESULTS

Want sorted results ORDER BY clause Ascending order by default Add DESC for descending order More than 1 column

sorts by 1st column, then 2nd, 3rd, etc…

Page 34: Basic SQL

34

SORTING THE RESULTS

Student ID

LastName FirstName GPA Major Class

S01 Daniels Rush 3.4 CS JR

S02 Blem Emily 3.9 Math JR

S03 Cook Matt 2.4 Math SR

S04 Park Phil 3.5 Math JR

Students

SELECT LastName, GPAFROM StudentsORDER BY GPA

Page 35: Basic SQL

35

SORTING THE RESULTS

LastName GPA

Cook 2.4

Daniels 3.4

Park 3.5

Blem 3.9

Results

SELECT LastName, GPAFROM StudentsORDER BY GPA

Page 36: Basic SQL

36

SORTING THE RESULTS

Student ID

LastName FirstName GPA Major Class

S01 Daniels Rush 3.4 CS JR

S02 Blem Emily 3.9 Math JR

S03 Cook Matt 2.4 Math SR

S04 Park Phil 3.5 Math JR

Students

SELECT LastName, GPAFROM StudentsORDER BY GPA DESC

Page 37: Basic SQL

37

SORTING THE RESULTS

LastName GPA

Blem 3.9

Park 3.5

Daniels 3.4

Cook 2.4

Results

SELECT LastName, GPAFROM StudentsORDER BY GPA DESC

Page 38: Basic SQL

38

SORTING THE RESULTS

Student ID

LastName FirstName GPA Major Class

S01 Daniels Rush 3.4 CS JR

S02 Blem Emily 3.9 Math JR

S03 Cook Matt 2.4 Math SR

S04 Park Phil 3.5 Math JR

Students

SELECT Major, GPAFROM StudentsORDER BY Major, GPA DESC

Page 39: Basic SQL

39

SORTING THE RESULTS

Major GPA

CS 3.4

Math 3.9

Math 3.5

Math 2.4

Students

SELECT Major, GPAFROM StudentsORDER BY Major, GPA DESC

Page 40: Basic SQL

40

DATA AGGREGATION

Summarizing data e.g., average GPA of all students called data aggregation

COUNT(*) computes the total number of rows

COUNT(column) counts the non-null values in a column counts duplicates

COUNT( DISTINCT column) counts the non-null unique values in a column

Page 41: Basic SQL

41

DATA AGGREGATION

AVG computes the average of a numeric column excludes null values adding DISTINCT computes average of unique

column values SUM

computes the sum of a numeric column excludes null values adding DISTINCT computes sum of unique

column values

Page 42: Basic SQL

42

DATA AGGREGATION

MIN finds the smallest value works on both numeric and string columns

MAX finds the largest value works on both numeric and string columns

Page 43: Basic SQL

43

DATA AGGREGATION

Student ID

LastName

FirstName GPA

S01 Daniels Rush 3.4

S02 Blem Emily 3.9

S03 Cook Matt 2.4

S04 Park Phil 3.5

Students

SELECT AVG(GPA) AS AvgGPAFROM Students

Page 44: Basic SQL

44

DATA AGGREGATION

AvgGPA

3.3

Result

SELECT AVG(GPA) AS AvgGPAFROM Students

Page 45: Basic SQL

45

DATA AGGREGATION

Student ID

LastName

FirstName GPA

S01 Daniels Rush 3.4

S02 Blem Emily 3.9

S03 Cook Matt 2.4

S04 Park Phil 3.5

Students

SELECT MAX(GPA) AS MaxGPAFROM Students

Page 46: Basic SQL

46

DATA AGGREGATION

MaxGPA

3.9

Result

SELECT MAX(GPA) AS MaxGPAFROM Students

Page 47: Basic SQL

47

DATA AGGREGATION

OfferID <CourseNo>

SectionNo

Term Faculty ID

O1 CS242 A Spring null

O2 CS242 B Spring F01

O3 CS370 A Spring F03

O4 CS375 A Fall F02

Offering

SELECT COUNT(*) AS NumOfferings,COUNT(DISTINCT CourseNo) AS NumCourse

FROM OfferingWHERE Term = ‘Spring’

Page 48: Basic SQL

48

DATA AGGREGATION

Result

SELECT COUNT(*) AS NumOfferings,COUNT(DISTINCT CourseNo) AS NumCourses

FROM OfferingWHERE Term = ‘Spring’

NumOfferings

NumCourses

3 2

Page 49: Basic SQL

49

JOINING TABLES

Combining multiple tables into a single query Join

most common way to query multiple tables combines related rows across several tables rows combined must have common value in

column

OfferingCourseNo

CourseDesc

CS242 DataStructures II

CS370 Databases

CS375 Digital Systems

CourseOfferID

<CourseNo>

SectionNo

Term Faculty ID

O1 CS242 A Spring null

O2 CS242 B Spring F01

O3 CS370 A Spring F03

O4 CS375 A Fall F02

Page 50: Basic SQL

50

JOINING TABLES

Combining multiple tables into a single query Join

most common way to query multiple tables combines related rows across several tables rows combined must have common value in

column

OfferID

CourseNo

SectionNo

Term Faculty ID

CourseDesc

O1 CS242 A Spring null DataStructures II

O2 CS242 B Spring F01 DataStructures II

O3 CS370 A Fall F03 Databases

O4 CS375 A Fall F02 Digital Systems

Result

Page 51: Basic SQL

51

JOINING TABLES

Joining tables in the WHERE clause Table1.column = Table2.column both tables must be in FROM clause

Joining tables in the FROM clause more explicit option uses JOIN and ON keywords

FROM Table1 JOIN Table2 ON Table1.column = Table2.column

or JOIN and USING keywords only if both columns have the same name FROM Table1 JOIN Table2 USING column

Page 52: Basic SQL

52

JOINING TABLES

Using syntactic sugar to introduce brevity Can rename a table in the FROM clause

From Table1 t1, Table2 t2 Then use that name later

WHERE t1.column = t2.column FROM Table1 t1, Table2 t2

ON t1.column = t2.column

Page 53: Basic SQL

53

JOINING TABLESOffering

CourseNo

CourseDesc

CS242 DataStructures II

CS370 Databases

CS375 Digital Systems

Course

SELECT CourseNo, SectionNo, CourseDescFROM Offering o, Course cWHERE Term = ‘Spring’

AND CourseDesc LIKE ‘%Structures%’AND o.CourseNo = c.CourseNo

OfferID

<CourseNo>

SectionNo

Term Faculty ID

O1 CS242 A Spring null

O2 CS242 B Spring F01

O3 CS370 A Spring F03

O4 CS375 A Fall F02

Page 54: Basic SQL

54

JOINING TABLES

SectionNo CourseNo CourseDesc

A CS242 DataStructures II

B CS242 DataStructures II

Result

SELECT CourseNo, SectionNo, CourseDescFROM Offering o, Course cWHERE Term = ‘Spring’

AND CourseDesc LIKE ‘%Structures%’AND o.CourseNo = c.CourseNo

Page 55: Basic SQL

55

JOINING TABLES

SELECT CourseNo, SectionNo, CourseDescFROM Offering JOIN Course USING CourseNoWHERE Term = ‘Spring’

AND CourseDesc LIKE ‘%Structures%’

OfferingCourseNo

CourseDesc

CS242 DataStructures II

CS370 Databases

CS375 Digital Systems

CourseOfferID

<CourseNo>

SectionNo

Term Faculty ID

O1 CS242 A Spring null

O2 CS242 B Spring F01

O3 CS370 A Spring F03

O4 CS375 A Fall F02

Page 56: Basic SQL

56

JOINING TABLESResultSectionNo CourseNo CourseDesc

A CS242 DataStructures II

B CS242 DataStructures II

SELECT CourseNo, SectionNo, CourseDescFROM Offering JOIN Course USING CourseNoWHERE Term = ‘Spring’

AND CourseDesc LIKE ‘%Structures%’

Page 57: Basic SQL

57

JOINING TABLES

SELECT CourseNo, SectionNo, CourseDescFROM Offering o JOIN Course c

ON o.CourseNo = c.CourseNoWHERE Term = ‘Spring’

AND CourseDesc LIKE ‘%Structures%’

OfferingCourseNo

CourseDesc

CS242 DataStructures II

CS370 Databases

CS375 Digital Systems

CourseOfferID

<CourseNo>

SectionNo

Term Faculty ID

O1 CS242 A Spring null

O2 CS242 B Spring F01

O3 CS370 A Spring F03

O4 CS375 A Fall F02

Page 58: Basic SQL

58

JOINING TABLES

SectionNo

CourseNo CourseNo CourseDesc

A CS242 CS242 DataStructures II

B CS242 CS242 DataStructures II

Result

SELECT CourseNo, SectionNo, CourseDescFROM Offering o JOIN Course c

ON o.CourseNo = c.CourseNoWHERE Term = ‘Spring’

AND CourseDesc LIKE ‘%Structures%’

Page 59: Basic SQL

QUESTIONS?

59

Page 60: Basic SQL

60

SUMMARIZING DATA BY CATEGORY

e.g., average GPA for each major GROUP BY statement

columns in SELECT must be in GROUP BY OR part of the data aggregation

GROUP BY multiple columns comma separated list

GROUP BY joined tables join happens first then the grouping

Page 61: Basic SQL

61

SUMMARIZING DATA BY CATEGORY

Student ID

LastName FirstName GPA Major Class

S01 Daniels Rush 3.4 CS JR

S02 Blem Emily 3.9 Math JR

S03 Cook Matt 2.4 Math SR

S04 Park Phil 3.5 Math JR

Students

SELECT Major, AVG(GPA) AS AvgGPAFROM StudentsGROUP BY Major

Page 62: Basic SQL

62

SUMMARIZING DATA BY CATEGORY

Major AvgGPA

Math 3.3

CS 3.4

Result

SELECT Major, AVG(GPA) AS AvgGPAFROM StudentsGROUP BY Major

Page 63: Basic SQL

63

SUMMARIZING DATA BY CATEGORY

Student ID

LastName FirstName GPA Major Class

S01 Daniels Rush 3.4 CS JR

S02 Blem Emily 3.9 Math JR

S03 Cook Matt 2.4 Math SR

S04 Park Phil 3.5 Math JR

Students

SELECT LastName, Major, AVG(GPA) AS AvgGPAFROM StudentsGROUP BY Major

Page 64: Basic SQL

64

SUMMARIZING DATA BY CATEGORY

Student ID

LastName FirstName GPA Major Class

S01 Daniels Rush 3.4 CS JR

S02 Blem Emily 3.9 Math JR

S03 Cook Matt 2.4 Math SR

S04 Park Phil 3.5 Math JR

Students

SELECT LastName, Major, AVG(GPA) AS AvgGPAFROM StudentsGROUP BY Major

LastName is not an aggregate or in GROUP BY

ERROR

Page 65: Basic SQL

65

SUMMARIZING DATA BY CATEGORY

Student ID

LastName FirstName GPA Major Class

S01 Daniels Rush 3.4 CS JR

S02 Blem Emily 3.9 Math JR

S03 Cook Matt 2.4 Math SR

S04 Park Phil 3.5 Math JR

Students

SELECT Major, Class, AVG(GPA) AS AvgGPAFROM StudentsGROUP BY Major, Class

Page 66: Basic SQL

66

SUMMARIZING DATA BY CATEGORY

Major Class AvgGPA

Math JR 3.7

Math SR 2.4

CS JR 3.4

Result

SELECT Major, Class, AVG(GPA) AS AvgGPAFROM StudentsGROUP BY Major, Class

Page 67: Basic SQL

67

SUMMARIZING DATA BY CATEGORY

SELECT Faculty.LastName, COUNT(*) AS ClassesFROM Offering JOIN Faculty USING FacultyIDGROUP BY Faculty.LastName

OfferingFacultyID

LastName

F01 Miller

F02 DeWitt

F03 Turing

FacultyOfferID

<CourseNo>

SectionNo

Term <Faculty ID>

O1 CS242 A Spring

F01

O2 CS242 B Spring

F01

O3 CS370 A Spring

F03

O4 CS375 A Fall F02

Page 68: Basic SQL

68

SUMMARIZING DATA BY CATEGORY

SELECT Faculty.LastName, COUNT(*) AS ClassesFROM Offering JOIN Faculty USING FacultyIDGROUP BY Faculty.LastName

Result

LastName Classes

Miller 2

DeWitt 1

Turing 1

Page 69: Basic SQL

69

SUMMARIZING DATA BY CATEGORY

Limiting the groups that are included like WHERE, but for groups e.g., Majors with an avg GPA >= 3.4

HAVING clause selects groups created by GROUP BY GROUP BY clause musts be listed first

Different from WHERE WHERE removes rows HAVING removes whole groups

Page 70: Basic SQL

70

SUMMARIZING DATA BY CATEGORY

Student ID

LastName FirstName GPA Major Class

S01 Daniels Rush 3.4 CS JR

S02 Blem Emily 3.9 Math JR

S03 Cook Matt 2.4 Math SR

S04 Park Phil 3.5 Math JR

Students

SELECT Major, AVG(GPA) AS AvgGPAFROM StudentsGROUP BY MajorHAVING AvgGPA >= 3.4

Page 71: Basic SQL

71

SUMMARIZING DATA BY CATEGORY

SELECT Major, AVG(GPA) AS AvgGPAFROM StudentsGROUP BY MajorHAVING GPA >= 3.4

Result

Major AvgGPA

Math 3.3

CS 3.4

Page 72: Basic SQL

72

SUMMARIZING DATA BY CATEGORY

SELECT Major, AVG(GPA) AS AvgGPAFROM StudentsGROUP BY MajorHAVING GPA >= 3.4

Major AvgGPA

Math 3.3

CS 3.4

Result

Page 73: Basic SQL

73

SUMMARIZING DATA BY CATEGORY

Student ID

LastName FirstName GPA Major Class

S01 Daniels Rush 3.4 CS JR

S02 Blem Emily 3.9 Math JR

S03 Cook Matt 2.4 Math SR

S04 Park Phil 3.5 Math JR

Students

SELECT Major, AVG(GPA) AS AvgGPAFROM StudentsWHERE GPA >= 3.4GROUP BY Major

Page 74: Basic SQL

74

SUMMARIZING DATA BY CATEGORY

Student ID

LastName FirstName GPA Major Class

S01 Daniels Rush 3.4 CS JR

S02 Blem Emily 3.9 Math JR

S03 Cook Matt 2.4 Math SR

S04 Park Phil 3.5 Math JR

Students

SELECT Major, AVG(GPA) AS AvgGPAFROM StudentsWHERE GPA >= 3.4GROUP BY Major

Page 75: Basic SQL

75

SUMMARIZING DATA BY CATEGORY

SELECT Major, AVG(GPA) AS AvgGPAFROM StudentsWHERE GPA >= 3.4GROUP BY Major

Major AvgGPA

Math 3.7

CS 3.4

Result

Page 76: Basic SQL

76

CONCEPTUAL QUERY EVALUATION

1. FROM tables (with joins)2. exclude rows using WHERE clause3. aggregate rows using GROUP BY4. exclude groups using the HAVING clause5. sort resulting rows by ORDER BY6. remove columns not listed in SELECT

Page 77: Basic SQL

QUESTIONS?

77

Page 78: Basic SQL

78

EFFECTS OF NULL ON QUERIES

WHERE clause includes rows that evaluate true rows evaluating false or null are excluded

Simple conditions conditions without AND, OR, or NOT operators e.g., Salary > 20,000 null values cause simple conditions to evaluate

null

Page 79: Basic SQL

79

EFFECTS OF NULL ON QUERIES

Compound conditions conditions with AND, OR, or NOT operators e.g., Salary > 20,000 AND LastName LIKE “Mc%” null will cause part of condition to be null

Page 80: Basic SQL

80

EFFECTS OF NULL ON QUERIES

Compound conditions conditions with AND, OR, or NOT operators e.g., Salary > 20,000 AND LastName LIKE “Mc*” null will cause part of condition to be null

AND True False Null

True True False Null

False False False False

Null Null False Null

Page 81: Basic SQL

81

EFFECTS OF NULL ON QUERIES

Compound conditions conditions with AND, OR, or NOT operators e.g., Salary > 20,000 AND LastName LIKE “Mc*” null will cause part of condition to be null

OR True False Null

True True True True

False True False Null

Null True Null Null

Page 82: Basic SQL

82

EFFECTS OF NULL ON QUERIES

Compound conditions conditions with AND, OR, or NOT operators e.g., Salary > 20,000 AND LastName LIKE “Mc*” null will cause part of condition to be null

NOT True False Null

False True Null

Page 83: Basic SQL

83

EFFECTS OF NULL ON QUERIES

Aggregation COUNT

COUNT(*) counts all rows (even ones with nulls) COUNT(column) counts non-null rows

SUM, AVG, MIN, MAX discard nulls

Expressions including a null are null 500 + null = null

Therefore SUM(C1) + SUM(C2) ≠ SUM(C1 + C2) if C2 has nulls it can make C1 + C2 null

Page 84: Basic SQL

84

EFFECTS OF NULL ON QUERIES

GROUP BY All null values are placed into 1 group

blank value represents null e.g., Get # of classes each faculty is teaching

SELECT FacultyNo, COUNT(*) AS NumRowsFROM OfferingGROUP BY FacultyNo

FacultyNo NumRows

5

F5 6

F12 1

F3 2

F4 3

Page 85: Basic SQL

85

MODIFYING DATA

Database data is modified using: INSERT

adds a new row to the database UPDATE

changes column(s) in one or more rows DELETE

remove one or more rows from database

Page 86: Basic SQL

86

INSERT STATEMENT

Adding a single row INSERT INTO table_name

(column1, column2, column3, …)VALUES (value1, value2, value3, …)

e.g., add a new faculty member INSERT INTO Faculty

(FacultyNo, FirstName, LastName, Department)VALUES( ‘F346’, ‘Joe’, ‘Meehean’, ‘CS’)

Formatting for literals in VALUES is different for every DBMS check your own DBMS documentation

Page 87: Basic SQL

87

INSERT STATEMENT

Adding a set of rows uses a nested SELECT

INSERT INTO table_nameSELECT column1, column2, …FROM other_tableWHERE condition

e.g., adding students to an honor student table HnrStudents and Students have same columns INSERT INTO HnrStudents

SELECT * FROM Students WHERE GPA >= 3.5

Page 88: Basic SQL

88

UPDATE STATEMENT

Updating a single column UPDATE table_name

SET column = expressionWHERE conditions

e.g., Updating vacation time for employees with over 2 years of employment UPDATE Employees

SET VacationDays = VacationDays + 14WHERE Years > 2

Page 89: Basic SQL

89

UPDATE STATEMENT

Updating a multiple columns UPDATE table_name

SET column1 = expr1, column2 = expr2WHERE conditions

e.g., Change Phil Parks major and class UPDATE Student

SET Major = ‘CS’, Class = ‘SO’WHERE FirstName = ‘Phil’ AND LastName = ‘Park’

Page 90: Basic SQL

90

DELETE STATEMENT

Delete selected rows DELETE FROM table

WHERE condition e.g., remove all the non-honor students from

the honor students table DELETE FROM HnrStudents

WHERE GPA < 2.0

Page 91: Basic SQL

91

DELETE STATEMENT

Delete all rows DELETE FROM table e.g., remove all of the honor students from

the honor students table DELETE FROM HnrStudents

Page 92: Basic SQL

92

DELETE STATEMENT

Delete using a join DELETE table1.*

FROM table1 JOIN table2 ON join_conditionWHERE condition

e.g., remove failing athletes from Athletes(StudentId, TeamId) DELETE Athletes.*

FROM Students s JOIN Athletes a ON s.StudentId = a.StudentIdWHERE Students.GPA < 2.0

Page 93: Basic SQL

QUESTIONS?

93

Page 94: Basic SQL

94

CREATING TABLES

Relational database consists of tables: data organized into rows and columns integrity constraints: rules limiting data

Create tables using CREATE TABLE statement need to give each table a unique name need to give each column a name and data type

CREATE TABLE TableName(column1 data_type1,column2 data_type2,column3 data_type3

)

Page 95: Basic SQL

95

DATA TYPES

CHAR (L) fixed L-length strings used for strings of known length e.g., zip codes, state abbreviations full length is allocated even if unused

VARCHAR (L) variable length strings up to L in size, many DBs limit to 255 allocation length is determined by data stored

Page 96: Basic SQL

96

DATA TYPES

INTEGER integers, whole numbers

FLOAT (P) decimal values with P significant digits most DBMSs have an upper limit on P e.g., 2.75

DECIMAL (W,R) decimal values with W significant digits R to the right of the decimal point data with fixed precision e.g., $, GPA

Page 97: Basic SQL

97

DATA TYPES

BOOLEAN true/false or yes/no

DATE/TIME not standard across DBMSs commonly support DATE, TIME, and TIMESTAMP TIMESTAMP is combined date and time

Page 98: Basic SQL

98

CREATING TABLES

CREATE TABLE Student( StdNo VARCHAR(50), StdFirstName VARCHAR(50), StdLastName VARCHAR(50), StdState CHAR(2), StdGPA DECIMAL(3,2), StdEnrollDate DATE, StdProbation BOOLEAN)

Page 99: Basic SQL

99

REPRESENTING RELATIONSHIPS

Represented relationships by having the same column in two tables e.g., Part(pid, pname, color) & Catalog(sid, pid,

cost) Connect 1 row from table A to one or more

rows from table B put primary key column from A into table B primary key of A is a foreign key in B

Page 100: Basic SQL

100

REPRESENTING RELATIONSHIPS

Customer#

Name Address

C1 Phil 112 Forest

C2 Emily 56 Lawn

C3 Tom 84 Lynn

C4 Erica 96 5th Ave

Customer

Order#

<Customer#>

Total

O1 C1 56.94

O2 C2 1.59

O3 C3 65.39

O4 C4 153.58

O5 C1 14.87

Order

Page 101: Basic SQL

101

INTEGRITY CONSTRAINTS

Must tell DBMS about rules governing data which columns should be unique which columns are primary keys which columns are foreign keys which columns should never be null

Use SQL CONSTRAINT key word table constraints govern keys and uniqueness row constraints govern nulls should provide a name for each constraint

CONSTRAINT ConstraintName ConstraintType

Page 102: Basic SQL

102

KEY CONSTRAINTS

PRIMARY KEY (columns) list of columns that define the primary key for a

table no two rows can contain same data in these

columns columns can be a comma separated list goes at the end of table definition

UNIQUE (columns) list of columns that must be unique no two rows can contain same data in these

columns candidate key goes at the end of table definition

Page 103: Basic SQL

103

KEY CONSTRAINTS

FOREIGN KEY (column) REFERENCES table column contains either null OR a primary key from table goes at the end of table definition

NOT NULL a column cannot contain a null value mandatory relationships require this goes right after data type of column

Page 104: Basic SQL

104

KEY CONSTRAINTS

CREATE TABLE Order( OrderNo INTEGER, CustomerNo INTEGER

CONSTRAINT CustomerRequired NOT NULL,

OrderTotal DECIMAL(10,2),

CONSTRAINT PKOrder PRIMARY KEY (OrderNo), CONSTRAINT FKCustNo FOREIGN KEY (CustumerNo) REFERENCES Customer,)

Page 105: Basic SQL

105

MAINTAINING INTEGRITY CONSTRAINTS

Recall we need to take special care when a FK is modified/deleted in its own table two separate cases: update and delete e.g., CustomerNo is deleted in Customer table what to do with CustomerNo in Order table

4 possible actions restrict: do not allow if reference exists cascade: perform same action for referencing

rows nullify: replace foreign key with null default: replace foreign key with default

Page 106: Basic SQL

106

MAINTAINING INTEGRITY CONSTRAINTS

Update ON UPDATE clause goes at end of FOREIGN KEY constraint

Delete ON DELETE clause goes at end of FOREIGN KEY constraint

4 options restrict is default, no need to make a clause CASCADE SET NULL SET DEFAULT

Page 107: Basic SQL

107

MAINTAINING INTEGRITY CONSTRAINTS

Default values DEFAULT DefaultValue clause goes at the end of the column definition

CREATE TABLE Customer( CustomerName VARCHAR(50) DEFAULT “Phil”)

Page 108: Basic SQL

108

MAINTAINING KEY CONSTRAINTSCREATE TABLE Order( OrderNo INTEGER, CustomerNo INTEGER

CONSTRAINT CustomerRequired NOT NULL, OrderTotal DECIMAL(10,2),

CONSTRAINT PKOrder PRIMARY KEY (OrderNo), CONSTRAINT FKCustNo FOREIGN KEY (CustumerNo) REFERENCES Customer

ON UPDATE CASCADEON DELETE CASCADE,

)

Page 109: Basic SQL

QUESTIONS?

109


Recommended