+ All Categories
Home > Documents > Tutorial 2 & 3 Update

Tutorial 2 & 3 Update

Date post: 13-Dec-2015
Category:
Upload: rohaizak-omar
View: 215 times
Download: 1 times
Share this document with a friend
Description:
Tutorial on SQL
29
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
Transcript
Page 1: Tutorial 2 & 3 Update

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

Page 2: Tutorial 2 & 3 Update

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';

Page 3: Tutorial 2 & 3 Update

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

Page 4: Tutorial 2 & 3 Update

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

Page 5: Tutorial 2 & 3 Update

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.

Page 6: Tutorial 2 & 3 Update

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

Page 7: Tutorial 2 & 3 Update

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

Page 8: Tutorial 2 & 3 Update

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;

Page 9: Tutorial 2 & 3 Update

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;

Page 10: Tutorial 2 & 3 Update

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

Page 11: Tutorial 2 & 3 Update

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.

Page 12: Tutorial 2 & 3 Update

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‘;

Page 13: Tutorial 2 & 3 Update

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 ?

Page 14: Tutorial 2 & 3 Update

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?

Page 15: Tutorial 2 & 3 Update

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_______';

User
Typewritten text
User
Typewritten text
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) ? allows you to match on a single character # allows you to match on a single numeric digit
Page 16: Tutorial 2 & 3 Update

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;

Page 17: Tutorial 2 & 3 Update

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

Page 18: Tutorial 2 & 3 Update

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

Page 19: Tutorial 2 & 3 Update

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.

Page 20: Tutorial 2 & 3 Update

Create this table

Page 21: Tutorial 2 & 3 Update

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 ;

Page 22: Tutorial 2 & 3 Update

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’ ;

Page 23: Tutorial 2 & 3 Update

MAX

• The MAX function returns the maximumvalue found in the specified column.

SELECT MAX (Fat)FROM FOODS ;SELECT MAX (Fat)FROM FOODS ;

Page 24: Tutorial 2 & 3 Update

MIN

• The MIN function returns the minimumvalue found in the specified column.

SELECT MIN(Carbohydrate)FROM FOODS ;

SELECT MIN(Carbohydrate)FROM FOODS ;

Page 25: Tutorial 2 & 3 Update

SUM

• The SUM function returns the sum of allthe values found in the specifiedcolumn.

SELECT SUM (Calories)FROM FOODS ;

Page 26: Tutorial 2 & 3 Update

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.

Page 27: Tutorial 2 & 3 Update

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 ) )

Page 28: Tutorial 2 & 3 Update

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‘

Page 29: Tutorial 2 & 3 Update

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;


Recommended