chapter 9 structured query language david m. kroenke database processing © 2000 prentice hall
TRANSCRIPT
Chapter 9Structured Query Language
David M. Kroenke
Database Processing
© 2000 Prentice Hall
Chapter 9
© 2000 Prentice Hall
SQL
“Structured Query Language; standard language for relational data manipulation”DB2, SQL/DS, OracleINGRES, SYBASE, SQL ServerdBase/Win, Paradox, Access
Page 217
Chapter 9
© 2000 Prentice Hall
Introduction to SQL
• IBM in the mid-1970s as SEQUEL• SQ92 = 1992 ANSI standard• data access language that is
embedded in application programs• result of an SQL statement is a
relation
Page 217
Sample Data
Figure 9-2 © 2000 Prentice Hall
Chapter 9
© 2000 Prentice Hall
Projection
SELECT SID, Name, MajorFROM STUDENT
Page 219
Chapter 9
© 2000 Prentice Hall
Selection
SELECT SID, Name, Major, GradeLevel, Age
FROM STUDENTWHERE Major = ‘MATH’
Page 220
Chapter 9
© 2000 Prentice Hall
Selection
SELECT *FROM STUDENTWHERE Age Between 19 and 30
Page 222
Chapter 9
© 2000 Prentice Hall
Sorting
SELECT Name, Major, AgeFROM STUDENTWHERE Major = ‘ACCOUNTING’ORDER BY Name
Page 223
Chapter 9
© 2000 Prentice Hall
SQL Built-In Functions
SELECT COUNT(Major)FROM STUDENT
Page 223
Chapter 9
© 2000 Prentice Hall
Grouping
SELECT Major, COUNT(*)FROM STUDENTGROUP BY MajorHAVING COUNT(*) > 1
Page 224
Chapter 9
© 2000 Prentice Hall
Querying Multiple Tables
• Retrieval Using Subquery• Joining with SQL
Page 226
Chapter 9
© 2000 Prentice Hall
Subquery (the second SELECT)
SELECT NameFROM STUDENTWHERE SID IN
(SELECT StudentNumber FROM ENROLLMENT WHERE ClassName = ‘BD445’)
Page 226
Chapter 9
© 2000 Prentice Hall
Joining with SQL
SELECT STUDENT.SID, STUDENT.Name, ENROLLMENT.ClassName
FROM STUDENT, ENROLLMENTWHERE STUDENT.SID =
ENROLLMENT.StudentNumber
Page 227
Chapter 9
© 2000 Prentice Hall
Outer Join
SELECT Name, ClassNameFROM STUDENT LEFT JOIN
ENROLLMENT ON SID = StudentNumber;
(note semicolon notation)
Page 230
Chapter 9
© 2000 Prentice Hall
Exists and Not Exists
“Logical operators whose value is either true or false depending on the presence or absence of rows that fit the qualifying conditions”
Page 230
Chapter 9
© 2000 Prentice Hall
Exist
SELECT DISTINCT StudentNumberFROM ENROLLMENT AWHERE EXISTS
(SELECT *FROM ENROLLMENT BWHERE A.StudentNumber = B.StudentNumberAND A.ClassName NOT = B.ClassName)
Page 230
Chapter 9
© 2000 Prentice Hall
Changing Data
• Inserting DataINSERT INTO ENROLLMENT
VALUES (400, ‘BD445’, 44)
• Deleting DataDELETE STUDENTWHERE STUDENT.SID = 100
• Modifying DataUPDATE ENROLLMENTSET PositionNumber = 44WHERE SID = 400
Page 232