Sei sulla pagina 1di 29

Very Basic Retrieval in SQL

How to retrieve all rows in a given table:


Syntax: SELECT * FROM tablename
SELECT
SELECT
SELECT
SELECT
SELECT
SELECT

*
*
*
*
*
*

FROM
FROM
FROM
FROM
FROM
FROM

EMPLOYEE
DEPARTMENT
DEPT_LOCATIONS
PROJECT
WORKS_ON
DEPENDENT

SELECT * is the simplest SQL query


Many variations, and can be complex

Basic SQL Queries


SELECT-FROM-WHERE structure
SELECT <attribute list>
FROM <table list>
WHERE <condition>;

Query 0
SELECT Bdate, Address
FROM EMPLOYEE
WHERE Fname='John' AND
Minit='B' AND
Lname='Smith';

Basic SQL Queries with Join Conditions


Query 1: Retrieve name and address of all Research dept employees
join condition
SELECT Fname, Lname, Address
FROM EMPLOYEE, DEPARTMENT
WHERE Dname='Research' AND Dnumber=Dno;
selection
condition

Basic SQL Queries with Join Conditions


Query 2: For every project in Stafford, list the project#, dept#,
and dept. manager's name, address, and birth date
SELECT Pnumber, Dnum, Lname, Address, Bdate
FROM
PROJECT, DEPARTMENT, EMPLOYEE
WHERE Dnum=Dnumber AND Mgr_ssn=Ssn AND
Plocation='Stafford';

Query Exercise
List the names of all employees who have a
dependent with the same first name as
themselves.

Retrieve the names of all employees in


Department 5 who work more than 10 hours
per week on the ProductX project.

Query Exercise
List the names of all employees who have a
dependent with the same first name as themselves.
SELECT LNAME, FNAME
FROM EMPLOYEE, DEPENDENT
WHERE SSN=ESSN AND FNAME=DEPENDENT_NAME
Retrieve the names of all employees in Department 5
who work more than 10 hours per week on the
ProductX project.
SELECT LNAME, FNAME
FROM EMPLOYEE, WORKS_ON, PROJECT
WHERE DNO=5 AND SSN=ESSN AND
PNO=PNUMBER AND PNAME='ProductX' AND
HOURS>10

Ambiguous Attribute Names


Suppose some of the EMPLOYEE and DEPARTMENT attribute
names were changed.
Name

x Dnumber

Name

Query 1: Retrieve name and address of all employees in the


'Research' department
SELECT Fname, Lname, Address
FROM EMPLOYEE, DEPARTMENT
WHERE Dname='Research' AND Dnumber=Dno;
becomes -->

SELECT Fname, Name, Address


FROM EMPLOYEE, DEPARTMENT
WHERE Name='Research' AND Dnumber=Dnumber;

Ambiguous Attribute Names


Query 1: Retrieve name and address of all employees in the
'Research' department
Name

x Dnumber

Name

How to fix: remove ambiguity with qualified attribute names


SELECT Fname, Name, Address
FROM EMPLOYEE, DEPARTMENT
WHERE Name='Research' AND Dnumber=Dnumber;

becomes -->

SELECT Fname, Employee.Name, Address


FROM EMPLOYEE, DEPARTMENT
WHERE Department.Name='Research' AND
Department.Dnumber=Employee.Dnumber;

Even if there is no ambiguity...


Query 1: Retrieve name and address of all employees in the
'Research' department
SELECT Fname, Lname, Address
FROM EMPLOYEE, DEPARTMENT
WHERE Dname='Research' AND Dnumber=Dno;
can be written as...
SELECT Employee.Fname,
Employee.Lname,
Employee.Address
FROM EMPLOYEE, DEPARTMENT
WHERE Department.Dname='Research' AND
Department.Dnumber=Employee.Dno;

Another type of ambiguity


Queries that reference the same relation twice
Query 8: For each employee, retrieve the employee's first and last
name, and the first and last name of their supervisor

This won't work...


SELECT Fname, Lname, Fname, Lname
FROM EMPLOYEE
WHERE ????;

Use aliases to define alternative relations (copies), E and S


SELECT E.Fname, E.Lname, S.Fname, S.Lname
FROM EMPLOYEE AS E, EMPLOYEE AS S
WHERE E.Super_ssn=S.Ssn;

Query Exercise
Find the names of all employees who are
directly supervised by 'Franklin Wong.
For each department, retrieve the
department name, and the average salary of
employees working in that department.
Retrieve the average salary of all female
employees.

Query Exercise
Find the names of all employees who are directly supervised by 'Franklin
Wong.
SELECT LNAME, FNAME
FROM EMPLOYEE
WHERE SUPERSSN IN ( SELECT SSN
FROM EMPLOYEE
WHERE FNAME='Franklin' AND LNAME='Wong' );
For each department, retrieve the department name, and the average
salary of employees working in that department.
SELECT DNAME, AVG (SALARY)
FROM DEPARTMENT, EMPLOYEE
WHERE DNUMBER=DNO
GROUP BY DNAME;
Retrieve the average salary of all female employees.
SELECT AVG (SALARY)
FROM EMPLOYEE
WHERE SEX='F;

Why WHERE clauses are (usually) important


WHERE clause determines which rows in a table are
selected for the query result
You may want all rows, as in SELECT * FROM EMPLOYEE
But, if you have more than one table specified in the

FROM clause, then the result is the cross product of the


tables
What is the result of SELECT * FROM EMPLOYEE, DEPARTMENT ?

Removing Duplicates in a Query Result


According to the relational model, a relation is a set and can
have no duplicate tuples
An SQL table represents a relation, but a table is not required
to have a key
In general, SQL tables do have keys and that is the
assumption we'll make for this class
However, the result of an SQL query may return duplicate
tuples (rows)
Example: SELECT Salary FROM EMPLOYEE
To remove duplicates:

SELECT DISTINCT Salary FROM EMPLOYEE

What other queries will produce results with duplicate values?

Using Pattern Matching in Queries


Create queries that compare only parts of a character
string, using LIKE comparison operator with % or _ to
specify partial strings
% replaces an arbitrary number of zero or more characters
_ replaces a single character

Examples:

In Access SQL, these are the


patterns that you can choose from
are:
* allows you to match any string of
any length (including zero length)

SELECT Fname, Lname


FROM EMPLOYEE
WHERE Address LIKE '%Houston, TX%'; ? allows you to match on a single
character

SELECT Fname, Lname


FROM EMPLOYEE
WHERE Ssn LIKE '__5_______';

# allows you to match on a single


numeric digit

Using Arithmetic, BETWEEN in Queries


Show resulting salaries if employees in Research
department received a 5% raise
SELECT Fname, Lname, 1.05 * Salary
FROM EMPLOYEE
WHERE Dno=5;

Retrieve all employees in Administration department with


salaries between 20000 and 30000
SELECT *
FROM EMPLOYEE
WHERE (Salary BETWEEN 20000 AND 30000) AND Dno=4;

same as...
SELECT *
FROM EMPLOYEE
WHERE (Salary >= 20000 AND Salary <= 30000) AND Dno=4;

Ordering of Query Results


Query 15: List employees and their projects, ordered by dept name,
and within dept, ordered alphabetically by last name, then first name
SELECT D.Dname, E.Lname, E.Fname, P.Pname
FROM DEPARTMENT D, EMPLOYEE E, WORKS_ON W, PROJECT P
WHERE D.Dnumber=E.Dno AND E.Ssn=W.Essn AND W.Pno=P.Pnumber
ORDER BY D.Dname, E.Lname, E.Fname

Ordering of Query Results


Query 15: List employees and their projects, ordered descending by dept
name, and with dept, ordered ascending by last name, then first name
SELECT D.Dname, E.Lname, E.Fname, P.Pname
FROM DEPARTMENT D, EMPLOYEE E, WORKS_ON W, PROJECT P
WHERE D.Dnumber=E.Dno AND E.Ssn=W.Essn AND W.Pno=P.Pnumber
ORDER BY D.Dname DESC, E.Lname ASC, E.Fname ASC

Functions
A function is a simple to moderately complex
operation that the usual SQL commands dont
perform but that comes up often in practice. SQL
provides functions that perform tasks that the
application code in the host language (within
which you embed your SQL statements) would
otherwise need to perform.
SQL has two main categories of functions: set
(or aggregate) functions and value/scalar
functions.

Create this table

COUNT
The COUNT function tells you how many
rows are in the table or how many rows in
the table meet certain conditions. The
simplest usage of this function is as
follows:
SELECT COUNT (*)
FROM FOODS ;
SELECT COUNT
(DISTINCT Fat)
FROM FOODS ;
SELECT COUNT
(Carbohydrate)
FROM FOODS ;

AVG
The AVG function calculates and returns
the average of the values in the specified
column. Of course, you can use the AVG
function only on columns that
contain numeric data, as in the following
example:
SELECT AVG (Fat)
FROM FOODS ;
SELECT AVG (Fat)
FROM FOODS
WHERE Food <> Butter ;

MAX
The MAX function returns the maximum
value found in the specified column.
SELECT MAX (Fat)
FROM FOODS ;

MIN
The MIN function returns the minimum
value found in the specified column.
SELECT MIN
(Carbohydrate)
FROM FOODS ;

SUM
The SUM function returns the sum of all
the values found in the specified
column.
SELECT SUM (Calories)
FROM FOODS ;

Query Exercise
1.

For each project, list the project name and the total hours per week (by
all employees) spent on that project.

2.

Retrieve the names of employees who work on every project.

3.

Retrieve the names of employees who do not work on any project.

4.

For each department, retrieve the department name, and the average
salary of employees working in that department.

5.

Retrieve the average salary of all female employees.

Query Exercise
For each project, list the project name and the total hours per week (by all
employees) spent on that project.
SELECT PNAME, SUM (HOURS)
FROM PROJECT, WORKS_ON
WHERE PNUMBER=PNO
GROUP BY PNAME
Retrieve the names of employees who work on every project
SELECT LNAME, FNAME
FROM EMPLOYEE
WHERE NOT EXISTS ( SELECT PNUMBER
FROM PROJECT
WHERE NOT EXISTS ( SELECT *
FROM WORKS_ON
WHERE PNUMBER=PNO AND ESSN=SSN ) )

Query Exercise

Retrieve the names of employees who do not work on any project.


SELECT LNAME, FNAME
FROM EMPLOYEE
WHERE NOT EXISTS ( SELECT *
FROM WORKS_ON
WHERE ESSN=SSN )
For each department, retrieve the department name, and the average salary of
employees working in that department.
SELECT DNAME, AVG (SALARY)
FROM DEPARTMENT, EMPLOYEE
WHERE DNUMBER=DNO
GROUP BY DNAME
Retrieve the average salary of all female employees.
SELECT AVG (SALARY)
FROM EMPLOYEE
WHERE SEX='F

INSERT, DELETE, and UPDATE


Insert a record for the new Sales department
INSERT INTO DEPARTMENT
VALUES ('Sales', 3, '8886655555', '1985-06-30');

Delete an employee

DELETE FROM EMPLOYEE


WHERE Ssn='123456789';

Update salaries in department 5


UPDATE EMPLOYEE
SET Salary = Salary * 1.1
WHERE Dno = 5;

Potrebbero piacerti anche