1
BASIC SQL
Joe Meehean
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?
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
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?”
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
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
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
8
EXTRACTING COLUMNS
SELECT LastName, MajorFROM Students
Last Name
Major
Arnett Theatre
Crumb Art
Vogelzang
Music
Park CS
Park CS
Result
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
10
EXTRACTING COLUMNS
SELECT DISTINCT LastName, MajorFROM Students
DISTINCT removes duplicate rows
Last Name
Major
Arnett Theatre
Crumb Art
Vogelzang
Music
Park CS
Result
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
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
13
CALCULATED FIELDS
Create new columns using arithmetic Can use +, −, *, /, ( ) Should name new column Use the AS keyword
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
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
16
EXTRACTING SPECIFIC ROWS
Add the WHERE clause to the SELECT SELECT <columns,…>
FROM <table>WHERE <condition>
WHERE conditions similar to C++ conditions
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
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
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
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
21
EXTRACTING SPECIFIC ROWS
LastName
FirstName
Blem Emily
Park Phil
SELECT LastName, FirstNameFROM StudentsWHERE GPA >= 3.5
Result
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
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
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
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
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
27
EXTRACTING SPECIFIC ROWS
SELECT PartNo, Pdesc, PqtyFROM PartsWHERE PDesc LIKE ‘5mm %’
ResultPartNo PQty PDesc
P1 2 5mm bolt
P3 2 5mm wrench
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
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
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
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
32
QUESTIONS?
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…
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
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
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
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
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
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
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
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
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
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
44
DATA AGGREGATION
AvgGPA
3.3
Result
SELECT AVG(GPA) AS AvgGPAFROM Students
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
46
DATA AGGREGATION
MaxGPA
3.9
Result
SELECT MAX(GPA) AS MaxGPAFROM Students
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’
48
DATA AGGREGATION
Result
SELECT COUNT(*) AS NumOfferings,COUNT(DISTINCT CourseNo) AS NumCourses
FROM OfferingWHERE Term = ‘Spring’
NumOfferings
NumCourses
3 2
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
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
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
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
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
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
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
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%’
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
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%’
QUESTIONS?
59
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
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
62
SUMMARIZING DATA BY CATEGORY
Major AvgGPA
Math 3.3
CS 3.4
Result
SELECT Major, AVG(GPA) AS AvgGPAFROM StudentsGROUP BY Major
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
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
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
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
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
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
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
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
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
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
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
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
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
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
QUESTIONS?
77
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
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
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
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
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
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
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
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
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
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
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
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’
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
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
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
QUESTIONS?
93
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
)
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
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
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
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)
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
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
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
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
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
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,)
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
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
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”)
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,
)
QUESTIONS?
109