Date post: | 13-Dec-2015 |
Category: |
Documents |
Upload: | rohaizak-omar |
View: | 215 times |
Download: | 1 times |
Very Basic Retrieval in SQL
• How to retrieve all rows in a given table: Syntax: SELECT * FROM tablename SELECT * FROM EMPLOYEE SELECT * FROM DEPARTMENT SELECT * FROM DEPT_LOCATIONS SELECT * FROM PROJECT SELECT * FROM WORKS_ON SELECT * FROM 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
SELECT Fname, Lname, Address FROM EMPLOYEE, DEPARTMENT
WHERE Dname='Research' AND Dnumber=Dno;
join condition
selection condition
Basic SQL Queries with Join Conditions
SELECT Pnumber, Dnum, Lname, Address, Bdate FROM PROJECT, DEPARTMENT, EMPLOYEE WHERE Dnum=Dnumber AND Mgr_ssn=Ssn AND Plocation='Stafford';
Query 2: For every project in Stafford, list the project#, dept#, and dept. manager's name, address, and birth date
Query Exercise• List the names of all employees who have a
dependent with the same first name asthemselves.
• Retrieve the names of all employees inDepartment 5 who work more than 10 hoursper week on the ProductX project.
Query Exercise• List the names of all employees who have a
dependent with the same first name asthemselves.
• Retrieve the names of all employees inDepartment 5 who work more than 10 hoursper 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, FNAMEFROM EMPLOYEE, DEPENDENTWHERE SSN=ESSN AND FNAME=DEPENDENT_NAME
• Retrieve the names of all employees in Department 5who work more than 10 hours per week on theProductX project.SELECT LNAME, FNAMEFROM EMPLOYEE, WORKS_ON, PROJECTWHERE DNO=5 AND SSN=ESSN AND
PNO=PNUMBER AND PNAME='ProductX' ANDHOURS>10
Query Exercise• List the names of all employees who have a
dependent with the same first name as themselves.SELECT LNAME, FNAMEFROM EMPLOYEE, DEPENDENTWHERE SSN=ESSN AND FNAME=DEPENDENT_NAME
• Retrieve the names of all employees in Department 5who work more than 10 hours per week on theProductX project.SELECT LNAME, FNAMEFROM EMPLOYEE, WORKS_ON, PROJECTWHERE DNO=5 AND SSN=ESSN AND
PNO=PNUMBER AND PNAME='ProductX' ANDHOURS>10
Ambiguous Attribute Names
SELECT Fname, Lname, AddressFROM EMPLOYEE, DEPARTMENTWHERE Dname='Research' AND Dnumber=Dno;
Query 1: Retrieve name and address of all employees in the 'Research' department
Suppose some of the EMPLOYEE and DEPARTMENT attribute names were changed.
SELECT Fname, Name, AddressFROM EMPLOYEE, DEPARTMENTWHERE Name='Research' AND Dnumber=Dnumber;
Name
Name
Dnumber
becomes -->
x
x x
Ambiguous Attribute NamesQuery 1: Retrieve name and address of all employees in the 'Research' department
How to fix: remove ambiguity with qualified attribute namesSELECT Fname, Name, AddressFROM EMPLOYEE, DEPARTMENTWHERE Name='Research' AND Dnumber=Dnumber;
Name
Name
Dnumber
becomes -->
x
x x
SELECT Fname, Employee.Name, AddressFROM EMPLOYEE, DEPARTMENTWHERE 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
can be written as...
SELECT Employee.Fname, Employee.Lname, Employee.AddressFROM EMPLOYEE, DEPARTMENTWHERE Department.Dname='Research' AND Department.Dnumber=Employee.Dno;
SELECT Fname, Lname, AddressFROM EMPLOYEE, DEPARTMENTWHERE Dname='Research' AND Dnumber=Dno;
Another type of ambiguityQueries 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
SELECT Fname, Lname, Fname, LnameFROM EMPLOYEEWHERE ????;
SELECT E.Fname, E.Lname, S.Fname, S.LnameFROM EMPLOYEE AS E, EMPLOYEE AS SWHERE E.Super_ssn=S.Ssn;
This won't work...
Use aliases to define alternative relations (“copies”), E and S
Query Exercise• Find the names of all employees who are
directly supervised by 'Franklin Wong‘.
• For each department, retrieve thedepartment name, and the average salary ofemployees working in that department.
• Retrieve the average salary of all femaleemployees.
Query Exercise• Find the names of all employees who are
directly supervised by 'Franklin Wong‘.
• For each department, retrieve thedepartment name, and the average salary ofemployees working in that department.
• Retrieve the average salary of all femaleemployees.
Query Exercise• Find the names of all employees who are directly supervised by 'Franklin
Wong‘.SELECT LNAME, FNAMEFROM EMPLOYEEWHERE SUPERSSN IN ( SELECT SSNFROM EMPLOYEEWHERE FNAME='Franklin' AND LNAME='Wong' );
• For each department, retrieve the department name, and the averagesalary of employees working in that department.
SELECT DNAME, AVG (SALARY)FROM DEPARTMENT, EMPLOYEEWHERE DNUMBER=DNOGROUP BY DNAME;
• Retrieve the average salary of all female employees.SELECT AVG (SALARY)FROM EMPLOYEEWHERE SEX='F‘;
Query Exercise• Find the names of all employees who are directly supervised by 'Franklin
Wong‘.SELECT LNAME, FNAMEFROM EMPLOYEEWHERE SUPERSSN IN ( SELECT SSNFROM EMPLOYEEWHERE FNAME='Franklin' AND LNAME='Wong' );
• For each department, retrieve the department name, and the averagesalary of employees working in that department.
SELECT DNAME, AVG (SALARY)FROM DEPARTMENT, EMPLOYEEWHERE DNUMBER=DNOGROUP BY DNAME;
• Retrieve the average salary of all female employees.SELECT AVG (SALARY)FROM EMPLOYEEWHERE 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: SELECT Fname, Lname FROM EMPLOYEE WHERE Address LIKE '%Houston, TX%';
SELECT Fname, Lname FROM EMPLOYEE WHERE Ssn LIKE '__5_______';
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
SELECT D.Dname, E.Lname, E.Fname, P.PnameFROM DEPARTMENT D, EMPLOYEE E, WORKS_ON W, PROJECT PWHERE D.Dnumber=E.Dno AND E.Ssn=W.Essn AND W.Pno=P.PnumberORDER BY D.Dname, E.Lname, E.Fname
Query 15: List employees and their projects, ordered by dept name, and within dept, ordered alphabetically by last name, then first name
Ordering of Query Results
SELECT D.Dname, E.Lname, E.Fname, P.PnameFROM DEPARTMENT D, EMPLOYEE E, WORKS_ON W, PROJECT PWHERE D.Dnumber=E.Dno AND E.Ssn=W.Essn AND W.Pno=P.PnumberORDER BY D.Dname DESC, E.Lname ASC, E.Fname ASC
Query 15: List employees and their projects, ordered descending by dept name, and with dept, ordered ascending by last name, then first name
Functions
• A function is a simple to moderately complexoperation that the usual SQL commands don’tperform but that comes up often in practice. SQLprovides functions that perform tasks that theapplication code in the host language (withinwhich you embed your SQL statements) wouldotherwise need to perform.
• SQL has two main categories of functions: set(or aggregate) functions and value/scalarfunctions.
• A function is a simple to moderately complexoperation that the usual SQL commands don’tperform but that comes up often in practice. SQLprovides functions that perform tasks that theapplication code in the host language (withinwhich you embed your SQL statements) wouldotherwise need to perform.
• SQL has two main categories of functions: set(or aggregate) functions and value/scalarfunctions.
Create this table
COUNT• The COUNT function tells you how many
rows are in the table or how many rows inthe table meet certain conditions. Thesimplest usage of this function is asfollows:
SELECT COUNT (*)FROM FOODS ;
• The COUNT function tells you how manyrows are in the table or how many rows inthe table meet certain conditions. Thesimplest usage of this function is asfollows:
SELECT COUNT (*)FROM FOODS ;
SELECT COUNT(Carbohydrate)FROM FOODS ;
SELECT COUNT(DISTINCT Fat)FROM FOODS ;
AVG• The AVG function calculates and returns
the average of the values in the specifiedcolumn. Of course, you can use the AVGfunction only on columns thatcontain numeric data, as in the followingexample:
SELECT AVG (Fat)FROM FOODS ;
• The AVG function calculates and returnsthe average of the values in the specifiedcolumn. Of course, you can use the AVGfunction only on columns thatcontain numeric data, as in the followingexample:
SELECT AVG (Fat)FROM FOODS ;
SELECT AVG (Fat)FROM FOODSWHERE Food <> ‘Butter’ ;
MAX
• The MAX function returns the maximumvalue found in the specified column.
SELECT MAX (Fat)FROM FOODS ;SELECT MAX (Fat)FROM FOODS ;
MIN
• The MIN function returns the minimumvalue found in the specified column.
SELECT MIN(Carbohydrate)FROM FOODS ;
SELECT MIN(Carbohydrate)FROM FOODS ;
SUM
• The SUM function returns the sum of allthe values found in the specifiedcolumn.
SELECT SUM (Calories)FROM FOODS ;
Query Exercise1. 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 averagesalary of employees working in that department.
5. Retrieve the average salary of all female employees.
1. For each project, list the project name and the total hours per week (byall 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 averagesalary of employees working in that department.
5. Retrieve the average salary of all female employees.
Query ExerciseFor each project, list the project name and the total hours per week (by allemployees) spent on that project.SELECT PNAME, SUM (HOURS)FROM PROJECT, WORKS_ONWHERE PNUMBER=PNOGROUP BY PNAME
Retrieve the names of employees who work on every projectSELECT LNAME, FNAMEFROM EMPLOYEEWHERE NOT EXISTS ( SELECT PNUMBERFROM PROJECTWHERE NOT EXISTS ( SELECT *FROM WORKS_ONWHERE PNUMBER=PNO AND ESSN=SSN ) )
For each project, list the project name and the total hours per week (by allemployees) spent on that project.SELECT PNAME, SUM (HOURS)FROM PROJECT, WORKS_ONWHERE PNUMBER=PNOGROUP BY PNAME
Retrieve the names of employees who work on every projectSELECT LNAME, FNAMEFROM EMPLOYEEWHERE NOT EXISTS ( SELECT PNUMBERFROM PROJECTWHERE NOT EXISTS ( SELECT *FROM WORKS_ONWHERE PNUMBER=PNO AND ESSN=SSN ) )
Query ExerciseRetrieve the names of employees who do not work on any project.SELECT LNAME, FNAME
FROM EMPLOYEEWHERE NOT EXISTS ( SELECT *FROM WORKS_ONWHERE ESSN=SSN )
For each department, retrieve the department name, and the average salary ofemployees working in that department.
SELECT DNAME, AVG (SALARY)FROM DEPARTMENT, EMPLOYEEWHERE DNUMBER=DNOGROUP BY DNAME
Retrieve the average salary of all female employees.
SELECT AVG (SALARY)FROM EMPLOYEEWHERE SEX='F‘
Retrieve the names of employees who do not work on any project.SELECT LNAME, FNAME
FROM EMPLOYEEWHERE NOT EXISTS ( SELECT *FROM WORKS_ONWHERE ESSN=SSN )
For each department, retrieve the department name, and the average salary ofemployees working in that department.
SELECT DNAME, AVG (SALARY)FROM DEPARTMENT, EMPLOYEEWHERE DNUMBER=DNOGROUP BY DNAME
Retrieve the average salary of all female employees.
SELECT AVG (SALARY)FROM EMPLOYEEWHERE 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;