45
SQL SQL (Structured Query Language) is used to define, query, and modify relational databases Every relational database system understands SQL SQL is standard: the same SQL statements can be executed without modifications on many database systems

SQL SQL (Structured Query Language) is used to define, query, and modify relational databases Every relational database system understands SQL SQL is standard:

  • View
    247

  • Download
    1

Embed Size (px)

Citation preview

Page 1: SQL SQL (Structured Query Language) is used to define, query, and modify relational databases Every relational database system understands SQL SQL is standard:

SQL

SQL (Structured Query Language) is used to define, query, and modify relational databasesEvery relational database system understands SQLSQL is standard: the same SQL statements can be executed without modifications on many database systems

Page 2: SQL SQL (Structured Query Language) is used to define, query, and modify relational databases Every relational database system understands SQL SQL is standard:

History of SQL

Developed by IBM as SEQUEL in early 70s (Structured English Query Language)

Renamed SQL (Structured Query Language)SQL-86 (ANSI, ISO)SQL-89SQL-92 (SQL2)SQL:1999 (SQL3)

Here: SQL 2

Page 3: SQL SQL (Structured Query Language) is used to define, query, and modify relational databases Every relational database system understands SQL SQL is standard:

The simple Select statement

The Select statement in SQL combines many relational algebra operations. Syntax:

SELECT <attribute_list> FROM <table_list> WHERE <condition>

SELECT clause specifies the attributes that go in the results table.

FROM clause specifies the source tables that the database will access in order to execute the query.

WHERE clause specifies the selection conditions, including the join condition

Page 4: SQL SQL (Structured Query Language) is used to define, query, and modify relational databases Every relational database system understands SQL SQL is standard:

Roles of Select

The basic Select statement includes many of the relational algebra operators combined

Project Customer on lastName, firstName (where is empty)

SELECT lastName, firstName

FROM Customer

Project Customer on lastName, firstName without duplicates

SELECT DISTINCT lastName, firstName

FROM Customer

Page 5: SQL SQL (Structured Query Language) is used to define, query, and modify relational databases Every relational database system understands SQL SQL is standard:

Roles of Select …

Retrieve the employees whose last name is ‘Doe’

SELECT * FROM Customer WHERE lastName = 'Doe‘

select from Customer the accountId, last name, and first name of the employees whose last name is ‘Doe’ and live in IllinoisSELECT accountid, lastname, firstname

FROM Customer WHERE lastname = 'Doe‘ and state = ‘IL’

Page 6: SQL SQL (Structured Query Language) is used to define, query, and modify relational databases Every relational database system understands SQL SQL is standard:

Roles of Select …

join Employee and TimeCard based on equality of ssn

SELECT * FROM Employee, TimeCard WHERE Employee.ssn = TimeCard.ssn

SELECT * FROM Employee JOIN TimeCard

ON Employee.ssn = TimeCard.ssn

Remark. The attribute names are preceded by the table names to remove confusion

Page 7: SQL SQL (Structured Query Language) is used to define, query, and modify relational databases Every relational database system understands SQL SQL is standard:

Outer Join

Outer joins add rows that have no match Left join adds all rows from left input table that do not match any row of right table. Similarly of right outer join. No full outer join is provided bySQL-2

Ex:SELECT * FROM Employee LEFT OUTER JOIN TimeCard ON Employee.ssn = TimeCard.ssn

Page 8: SQL SQL (Structured Query Language) is used to define, query, and modify relational databases Every relational database system understands SQL SQL is standard:

Examples

List the SSNs of all managersList the names of all projectsList the names of all employees working for the research department.List the names of all departments managed by somebody with a salary less than 30.000.List employees with names of dependentsList the salaries of all employees working in Houston.

Page 9: SQL SQL (Structured Query Language) is used to define, query, and modify relational databases Every relational database system understands SQL SQL is standard:

Pattern Matching

Suppose we want to list all the movies containing the word Pinochio in their title!

SELECT * FROM Movie WHERE title LIKE '%Pinochio%‘

Suppose we want to list all the movies whose title does not start with ‘The’

SELECT * FROM Movie WHERE title NOT LIKE 'The %‘

Suppose we want to list all employees whose ssn contains 44 in the middle

SELECT * FROM Employee WHERE ssn LIKE '___-44-____‘

Page 10: SQL SQL (Structured Query Language) is used to define, query, and modify relational databases Every relational database system understands SQL SQL is standard:

Ordering the output

Ordering results in SQL:suppose we want to output the employees sorted by lastname then firstnameSELECT * FROM Customer ORDER BY lastName, firstName

Page 11: SQL SQL (Structured Query Language) is used to define, query, and modify relational databases Every relational database system understands SQL SQL is standard:

Ordering …

Suppose we want to output the accountid of the customers in descending order

SELECT * FROM Customer ORDER BY accountId

DESC

Similarly, we can use ASC for ascending

Page 12: SQL SQL (Structured Query Language) is used to define, query, and modify relational databases Every relational database system understands SQL SQL is standard:

Renaming

If necessary we can rename relations or attributes

SELECT FNAME AS First_NameFROM Customer

Page 13: SQL SQL (Structured Query Language) is used to define, query, and modify relational databases Every relational database system understands SQL SQL is standard:

Expressions

SELECT lastName, firstName, Employee.ssn, date, (endTime-startTime) AS timeworkedFROM Employee, TimeCard

WHERE Employee.ssn = TimeCard.ssn

Creates a table with 5 attributes5th attribute of an output row is calculated from the endTime and startTime attributes of the input row

Page 14: SQL SQL (Structured Query Language) is used to define, query, and modify relational databases Every relational database system understands SQL SQL is standard:

Aggregate functions

Aggregates functions include: count(), avg(), minimum(), maximum, …

Example 1: SELECT count(*) FROM Rental WHERE accountId = 101 Example 2:

SELECT count(DISTINCT lastName) FROM Customer

Page 15: SQL SQL (Structured Query Language) is used to define, query, and modify relational databases Every relational database system understands SQL SQL is standard:

Grouping in aggregate functions

Suppose we want to count for every video how many times it was previously rented and the average cost of all the rentals

SELECT videoId, avg(cost) AS averageCost, count(*) as numRentalsFROM PreviousRental

GROUP BY videoId

Page 16: SQL SQL (Structured Query Language) is used to define, query, and modify relational databases Every relational database system understands SQL SQL is standard:

Grouping …

Suppose we want to display all the movies that were rented at least twice before SELECT title, genre, count(*) as numRentals, FROM Movie, Video, PreviousRentalWHERE Movie.movieId = Video.movieId

AND Video.videoId = PreviousRental.videoidGROUP BY Movie.movieId, title, genreHAVING count(*)>1

A group with count(*) [number of rows in group] <=1 does not produce an output row

Page 17: SQL SQL (Structured Query Language) is used to define, query, and modify relational databases Every relational database system understands SQL SQL is standard:

Examples

Find for the research department the minimum salary and the maximum salary of its employees For each department with at least 10 employees, list the department name and its number of employees

Page 18: SQL SQL (Structured Query Language) is used to define, query, and modify relational databases Every relational database system understands SQL SQL is standard:

Solution

SELECT max(salary) as Highest_Salary, min(salary) as Lowest_Salary

FROM employee, departmentWHERE dno = dnumber AND dname=‘Research

SELECT Dname, count(*) as Number_Of_EmployeesFROM employee, departmentWHERE dno = dnumber GROUP BY dno, DnameHAVING Count(*) > 9

Page 19: SQL SQL (Structured Query Language) is used to define, query, and modify relational databases Every relational database system understands SQL SQL is standard:

The IN Operator

Conditions can contain IN for “element of”

SELECT pnameFROM projectWHERE pnumber IN (1,2,4,5)

SELECT pnameFROM projectWHERE plocation IN (‘Houston’, ‘Stafford’)

SELECT pnameFROM projectWHERE pnumber NOT IN (1,2)

Page 20: SQL SQL (Structured Query Language) is used to define, query, and modify relational databases Every relational database system understands SQL SQL is standard:

Nested select statements

List the names of the employees with no dependents

SELECT lastname, fnameFROM employeeWHERE ssn NOT IN (SELECT essn

FROM dependent)

Page 21: SQL SQL (Structured Query Language) is used to define, query, and modify relational databases Every relational database system understands SQL SQL is standard:

The ALL operator

ALL: the condition should hold for all rows

Ex: List the names of employees whose salary is higher than all employees in department number 5

SELECT fname, lnameFROM employeeWHERE salary > ALL (SELECT salary FROM employee WHERE dno = 5)

Page 22: SQL SQL (Structured Query Language) is used to define, query, and modify relational databases Every relational database system understands SQL SQL is standard:

More examples on nested queries with IN

•List the Names of all supervisors.•List the Names of all employees that have a dependent spouse.•List the SSNs of employees that on some project work the same time as `John Smith’

Page 23: SQL SQL (Structured Query Language) is used to define, query, and modify relational databases Every relational database system understands SQL SQL is standard:

Renaming tables

Remark. If attributes have the same name we can rename the tables to clarify the scope of each attribute

Ex: List the names of all supervisors

Page 24: SQL SQL (Structured Query Language) is used to define, query, and modify relational databases Every relational database system understands SQL SQL is standard:

Nesting Queries with ALL: Examples

•List the names of employees that make the maximum salary

•List the names of employees that make a salary that is different from everybody else’s salary

Page 25: SQL SQL (Structured Query Language) is used to define, query, and modify relational databases Every relational database system understands SQL SQL is standard:

Existence

Tests that a set is nonempty

SELECT fname, lnameFROM employeeWHERE EXISTS (SELECT *

FROM dependentWHERE ssn = essn);

SELECT fname, lnameFROM employeeWHERE NOT EXISTS (SELECT *

FROM dependentWHERE ssn = essn);

Page 26: SQL SQL (Structured Query Language) is used to define, query, and modify relational databases Every relational database system understands SQL SQL is standard:

Set Intersection using EXISTS

Example: Employees with dependents

SELECT fname, lnameFROM employeeWHERE EXISTS (SELECT *

FROM dependentWHERE ssn = essn);

•Mangers that are also supervisors

Page 27: SQL SQL (Structured Query Language) is used to define, query, and modify relational databases Every relational database system understands SQL SQL is standard:

Set Difference using NOT EXISTS

SELECT fname, lnameFROM employeeWHERE NOT EXISTS (SELECT *

FROM dependentWHERE ssn = essn);

Example: Employees without dependents

•Employees which are not managers•Projects on which nobody works 20 hours or more

Page 28: SQL SQL (Structured Query Language) is used to define, query, and modify relational databases Every relational database system understands SQL SQL is standard:

Unique Existence

Tests that a set contains one element

SELECT fname, lnameFROM employeeWHERE UNIQUE (SELECT *

FROM dependentWHERE ssn = essn);

Page 29: SQL SQL (Structured Query Language) is used to define, query, and modify relational databases Every relational database system understands SQL SQL is standard:

Existence Examples

•List the names of managers that have a dependent

•List the names of employees that work on all department 4 projects

Page 30: SQL SQL (Structured Query Language) is used to define, query, and modify relational databases Every relational database system understands SQL SQL is standard:

Set Operations: Union

Union operation: retrieve all videos that have been rented at least once (SELECT * FROM Rental) UNION (SELECT * FROM PreviousRental)

Page 31: SQL SQL (Structured Query Language) is used to define, query, and modify relational databases Every relational database system understands SQL SQL is standard:

Set Operations: Intersection

Retrieve videos that are currently rented and were previously rented

(SELECT videoId FROM Rental)

INTERSECT (SELECT videoId

FROM PreviousRental)

Page 32: SQL SQL (Structured Query Language) is used to define, query, and modify relational databases Every relational database system understands SQL SQL is standard:

Set Operations: Difference

Retrieve videotapes that are currently rented for the first time

(SELECT videoId FROM Rental)

EXCEPT (SELECT videoId

FROM PreviousRental)

Page 33: SQL SQL (Structured Query Language) is used to define, query, and modify relational databases Every relational database system understands SQL SQL is standard:

Creating tables

A create table statement specifies a table name and a list of attributes and constraints for a new tableExample with no constraints CREATE TABLE Customer (accountId

int, lastName varchar(32), firstName varchar(32), street varchar(100), city varchar(32), state char(2), zipcode varchar(9), balance real)

Page 34: SQL SQL (Structured Query Language) is used to define, query, and modify relational databases Every relational database system understands SQL SQL is standard:

Creating tables …

Add a primary key constraint CREATE TABLE Customer (accountId

int primary key, lastName varchar(32), firstName varchar(32), street varchar(100), city varchar(32), state char(2), zipcode varchar(9), balance real)

Page 35: SQL SQL (Structured Query Language) is used to define, query, and modify relational databases Every relational database system understands SQL SQL is standard:

Creating tables …

Add primary key constraint as separate clause

CREATE TABLE Store (storeId int, street varchar(100), city varchar(32), state char(2), zipcode varchar(9), primary key storeId, manager int references Employee)

Add foreign key constraints and specify other keys and multiple-attribute key

CREATE TABLE Rental (accountId int, videoId varchar(10) unique, dateRented datetime, dateDue datetime, cost real, primary key (accountId, videoId), foreign key (accountId) references Customer(accountId) foreign key (videoId) references Video(videoId))

Page 36: SQL SQL (Structured Query Language) is used to define, query, and modify relational databases Every relational database system understands SQL SQL is standard:

Inserting into tables

Either specify all values:INSERT INTO Customer VALUES (555, 'Yu', 'Jia','540 Magnolia Hall',

'Tallahassee', 'FL', '32306', 0.00)

Or the value that need to be inserted, the others will be set to NULL

INSERT INTO Customer (firstName, lastName, accountId)VALUES ('Jia', 'Yu', 555)

Page 37: SQL SQL (Structured Query Language) is used to define, query, and modify relational databases Every relational database system understands SQL SQL is standard:

Inserting by SELECT

We can insert from select statement INSERT INTO <table> <select statement>

Remark. Fields of SELECT must match fields INSERT in order and type

Ex: Suppose we have created a table called Comedy_Movies with the same attributes as Movie except for genre which is omitted. To populate the table:

INSERT INTO Comedy_Movies (movieId, title, length, rating)SELECT movieId, title, length, rating FROM MovieWHERE genre = ‘comedy’

Page 38: SQL SQL (Structured Query Language) is used to define, query, and modify relational databases Every relational database system understands SQL SQL is standard:

Updating a table

General form of update statement UPDATE <table> SET <attribute>=<value> ...

WHERE <selection condition>

Ex: Update to mark every timecard as paidUPDATE TimeCard SET paid = true WHERE paid = false

Page 39: SQL SQL (Structured Query Language) is used to define, query, and modify relational databases Every relational database system understands SQL SQL is standard:

Updating tables …

Ex: Update to give every employee a 10% raise of the average salary

UPDATE Employee SET salary =salary +0.1 (select

avg(salary) from

Employee)

Page 40: SQL SQL (Structured Query Language) is used to define, query, and modify relational databases Every relational database system understands SQL SQL is standard:

Delete operation

Each delete statement deletes from one table according to some selection clause(deletion propagates in case of referential constraints)

Ex: Delete every row from table DELETE FROM Employee

Ex: Delete all employees that live in IllinoisDELETE FROM EmployeeWHERE state = ‘IL’

Page 41: SQL SQL (Structured Query Language) is used to define, query, and modify relational databases Every relational database system understands SQL SQL is standard:

Examples …

Ex: Delete all employees with no

dependentsDELETE FROM EmployeeWHERE NOT EXISTS (SELECT * FROM Dependent

WHERE essn = ssn)

Page 42: SQL SQL (Structured Query Language) is used to define, query, and modify relational databases Every relational database system understands SQL SQL is standard:

Altering tables and attributes

An ALTER TABLE statement changes the definition of a table

Modify and drop table constraints and

drop an attribute ALTER TABLE Video

MODIFY (storeId NOT NULL)DROP constraint (primary key

videoId) DROP (movieId)

Page 43: SQL SQL (Structured Query Language) is used to define, query, and modify relational databases Every relational database system understands SQL SQL is standard:

Dropping a table

Drop a table: completely destroys table and all contentsDROP TABLE Employee

What happens when table contains keys and foreign keys?

Cascade characteristic tells server to delete all rows of other tables that have foreign keys to the dropped tableDROP TABLE video cascade

Restrict characteristic tells server to block the delete operation if additional rows would have to be deleted

DROP TABLE movie restrict

Page 44: SQL SQL (Structured Query Language) is used to define, query, and modify relational databases Every relational database system understands SQL SQL is standard:

Examples

List everybody who makes more than $30000.List names of everybody working for the research department.List employees with a dependent.List employees that have a daughter.List employees without dependents.List employees working on a project in Houston.List all supervisors.List names of all managers.List names of managers with at least one dependent

Page 45: SQL SQL (Structured Query Language) is used to define, query, and modify relational databases Every relational database system understands SQL SQL is standard:

Examples …

For every project located in ‘Chicago’, list the project number, the controlling department number, the department manager’s last name, address, and birthdate.Make a list of project numbers for projects involving an employee whose first name is `Pinochio’ either as a worker on the project, or as a manager of the department that controls the project. Find the names of all employees who are directly supervised by `Isaac Newton’For each department, retrieve the department name and average salary of its employees.Retrieve the average salary of all female employeesFor each project, list the project name and the total number of hours spent on the project.