L16.SQL Querying.long
Click here to load reader
-
Upload
daniel-kwon -
Category
Documents
-
view
213 -
download
1
Transcript of L16.SQL Querying.long
Introduction to SQL: Intro to Querying
William Hendrix
EECS 317, Spring 2014
Lecture 16
Today
• Modifying tables: ALTER TABLE, DROP TABLE
• Adding data: INSERT
• Querying: the SELECT statement
– Basic queries
– NULL values
– Quantifiers
– Set operations
– Joins
2
CREATE TABLE exercise
Create tables for the following schema in SQL.
• BoughtBy(CustName, PubCode)
– Foreign keys: CustName (Customer), PubCode (Publication)
• Customer(Name, Street, City, State, Zip)
• Department(ID, Name, Manager)
– Foreign key: Manager (Employee)
• Employee(ID, Name, Salary, DeptID)
– Foreign key: DeptID (Department)
• Publication(Code, Title, DeptID, StartDate)
– Foreign key: DeptID (Department, not NULL)
• Topic-Area(PubCode, TopicCode, Name)
– Foreign key: PubCode (Publication, deletes)
In what order should the tables be created? 3
Changing your mind
• Deleting or renaming a table
– DROP TABLE TableName [CASCADE];
– CASCADE drops foreign keys pointing to this table (error otherwise)
• Changing a table specification
– ALTER TABLE TableName <Changes...>;
– Renaming table
• RENAME TO NewName
– Adding columns
• ADD ColName Domain ...
– Removing columns
• DROP COLUMN ColName
– Adding constraints
• ADD (PRIMARY KEY(Att1, ...))
– Removing constraints
• DROP FOREIGN KEY(Att1) REFERENCES TableName
• DROP CONSTRAINT Cname
– MODIFY: Many ways to use
4
Table modification example
• Suppose that we incorrectly constructed a Mayors table:
• CREATE TABLE Mayors(City VARCHAR(20), Election INTEGER,
Mayor VARCHAR(50), CONSTRAINT pk PRIMARY KEY(City,
Election))
• CREATE TABLE Cities(City VARCHAR(20) PRIMARY KEY
REFERENCES Mayors, State CHAR(2))
Problem
• Same city in different states (Springfield, IL and Springfield, MA)
5
Solution
1. Drop the Cities table: DROP TABLE Cities;
2. Add State to the Mayors table:
– ALTER TABLE Mayors ADD State CHAR(2);
3. Fix the primary key to include city and state:
– ALTER TABLE Mayors DROP CONSTRAINT pk;
– ALTER TABLE Mayors ADD CONSTRAINT pk PRIMARY
KEY (City, State, Election));
Populating tables
• Most database management software (DBMS) have utilities for importing information from text files, Excel, etc.
• Accomplished in SQL with INSERT command
• Syntax: INSERT INTO Table (Attributes) VALUES (Values);
– Attributes can be specified in any order
– Unspecified attributes become NULL or default value
– Not needed if specifying all attributes in order
• INSERT can also add data from other tables
• Syntax: INSERT INTO Table (Attributes) (SELECT ...);
– Useful for creating copies of data
– Analogous to renaming operation in relational algebra
6
Querying tables
• SELECT statement
• Usage: SELECT Attrib(s) FROM Table WHERE Condition(s);
– WHERE clause is optional (retrieves all tuples if omitted)
– Use * to retrieve all attributes
• SELECT * FROM Employees;
– Separate multiple attributes with commas
• SELECT Fname, Lname FROM Employees;
• Criteria construction
– Basic relational operators: =, <>, <, <=, >, >=
• Compares strings alphabetically, dates temporally
• Oracle: punctuate strings and dates with single quotes
• SELECT * FROM Employees WHERE Employees.Salary >=
60000;
– Logical connectives: NOT, AND, OR
• SELECT * FROM Employees WHERE NOT (Employees.Lname =
‘Smith’);
7
Comparing NULL values
• NULL values in the database represent data with unknown values
• Induces 3-valued logic: TRUE, FALSE, UNKNOWN (NULL)
– NULL = ‘James’? NULL >= ‘01-01-1900’?
• We don’t know: NULL
–
• Also unknown (NULL)
– Most comparisons with NULL are NULL except:
•
• Use Attrib IS NULL to identify NULL values
• NVL(Attrib, Value) can replace NULL with Value
– Sometimes called IFNULL or ISNULL
8
T F N
T T T T
F T F N
N T N N
T F N
T T F N
F F F F
N N F N
Table and column aliasing
• Aliasing
– Analogous to renaming in relational algebra
– Can alias table and attribute names
– Performed with AS keyword
• SELECT E.Lname AS Family FROM Employees AS E WHERE
E.Lname < ‘Johnson’;
– Renaming tables is very useful with multi-table queries
• Attributes must be specified by their table if query involves multiple tables with same attribute
• Not necessary if unambiguous
– Note: renaming tables happens before WHERE clause, renaming
attributes happens afterwards
• Wrong: SELECT Lname AS Family FROM Employees WHERE Family < `Johnson’;
– AS keyword can be omitted
• SELECT Lname Family FROM Employees WHERE Lname <
‘Johnson’; 9
Advanced criteria constructions
• Between: BETWEEN, NOT BETWEEN
– SELECT * FROM Employees WHERE Fname BETWEEN
‘George’ AND ‘Martha’;
– Different DBMSs include or exclude boundaries
• Oracle BETWEEN is inclusive
• String similarity: LIKE, NOT LIKE
– Use % to represent “anything”
– First names that start with J: Fname LIKE ‘J%’
– Last names that end with son: Lname LIKE ‘%son’
– Names that do not have a t in them: Name NOT LIKE ‘%t%’
• Set comparison: IN, NOT IN
– SELECT * FROM Musicians WHERE Fname NOT IN
(‘John’, ‘Paul’, ‘George’, ‘Ringo’);
– SELECT * FROM Musicians M WHERE Lname IN
(SELECT Fname FROM M);
10
Quantifiers
• Existential Quantifier
– Usage: EXISTS (Set or SELECT query)
– Example
• SELECT * FROM Musicians M WHERE EXISTS (SELECT
Fname FROM Musicians WHERE Fname = M.Lname);
– Alternative: ANY, SOME (Set or SELECT query)
– Example
• SELECT * FROM Musicians WHERE Fname <> ANY
(‘John’, ‘Paul’, ‘George’, ‘Ringo’);
• Universal quantifiers
– Usage: ALL (Set or SELECT query)
– Can be converted to NOT EXISTS expression (DeMorgan’s Law)
– Example
• SELECT * FROM Employees WHERE Salary >= ALL
(SELECT Salary FROM Employees);
11
Set operations and quantifiers
• Cartesian product
– Use commas to separate tables
• SELECT * FROM Employees, Departments;
– Attributes from different tables not required to be distinct
– Can be used to perform theta-joins
• Set union, intersection, and difference
– Combine results from two queries
– Attributes do not need to be identical, just compatible
– UNION, INTERSECT, MINUS (or EXCEPT)
– Examples
Emp(SSN, Name, Salary), Mgr(SSN, Benefits)
• SELECT Salary FROM Emp UNION SELECT Benefits FROM Mgr;
• SELECT Name FROM Emp MINUS SELECT Name FROM Emp, Mgr
WHERE Emp.SSN = Mgr.SSN;
12
Table joins
• Joins
– Use JOIN keyword, with NATURAL, FULL, LEFT, or RIGHT
• May use INNER JOIN if not using FULL, LEFT, or RIGHT
• FULL, LEFT, and RIGHT may be followed by OUTER
– Specify join as table value • SELECT * FROM Employee NATURAL JOIN Dept;
• SELECT * FROM Employee NATURAL FULL OUTER JOIN Dept;
– Need to specify ON Condition if join is not NATURAL
• SELECT * FROM Students S JOIN HasTaken H ON
S.NetID = H.Student;
• Equivalent to: SELECT * FROM Students S, HasTaken H WHERE S.NetID = H.Student;
• SELECT * FROM STUDENTS S LEFT JOIN HasTaken H ON
S.NetID = H.Student;
• Equivalent to: SELECT * FROM Students S, HasTaken H WHERE S.NetID = H.Student OR S.NetID IS NULL;
13
Coming up
• UPDATE, DELETE statements
• Aggregation
• Hardware considerations and indexing
• Recommended readings
– Sections 7.1-3
14