Databasetechlecture 9

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 10

8/19/2014

Outline
• Introduction to SQL
• Basic structure of SQL
commands
• Data Definition
• Data Manipulation
• Aggregation

Introduction to Introduction to
SQL SQL
• SQL is a transform-oriented • SQL does not contain flow control
language with two major components. commands.
• the DDL for defining the database • must be implemented using a
structure and programming or job-control
• the DML for retrieving and updating language,
data. • or interactively by the decisions of
the user.

Introduction to Introduction to
SQL SQL
• SQL is relatively easy to learn. • An ISO standard exists for SQL,
• SQL is a nonprocedural language, • making it both the formal and de
• you specify what information you facto standard language for
require, relational databases.
• rather than how to get it. • The most popular and widely
implemented is referred to as
SQL2 or SQL/92.

1
8/19/2014

Basic structure of Basic structure of


SQL commands SQL commands
• SQL statement consists of reserved • Most components of an SQL
words and user-defined words.
statement are case insensitive
• Reserved words are a fixed part of
SQL and must be spelt exactly as
required and cannot be split across • SQL statements are more
lines. readable with indentation and
• User-defined words are made up by lineation.
user and represent names of various
database objects such as relations,
columns and views.

TABLE DEFINITION-
TABLE DEFINITION- example
• The syntax for creating a table • CREATE TABLE Employee
consists of an ordered set of (
attributes and a (possibly empty) RegNo CHARACTER(6) PRIMARY
set of constraints. KEY,
• CREATE TABLE table_name FirstName CHARACTER(20)
(col_name data_type [NULL | NOT NULL,
NOT NULL] [,...]) Surname CHARACTER(20) NOT
NULL,

TABLE DEFINITION-
CONT DROP DEFINITION
Dept CHARACTER (15) REFERENCES • A Table can be deleted from a
Department(DeptName) ON DELETE
database using the command
SET NULL
ON UPDATE CASCADE,
“drop”.
Salary NUMERIC(9) DEFAULT 0, • The following syntax is used.
City CHARACTER(15), – DROP TABLE name [RESTRICT
UNIQUE (Surname,FirstName) | CASCADE ];
)

2
8/19/2014

DROP DEFINITION
CONT: ALTER DEFINITION
• With RESTRICT (default), Table • ALTER (alter domain ..., alter table
must be empty or operation fails. …)
• With CASCADE, SQL drops all • For example the commande:
dependent objects — and objects
ALTER TABLE Department
dependent on these objects
ADD COLUMN NoOfOffices
NUMERIC(4);

Data Manipulation
Data Manipulation
• A query in SQL can consist of up FROM table_name [alias] [, ...]
to six clauses, [WHERE condition]
• but only the first two are [GROUP BY column_list]
mandatory.
• SELECT [DISTINCT | ALL] [HAVING condition]
{* | [column_expression [AS [ORDER BY column_list]
new_name]] [,...] }

Data Manipulation CONT: Data Manipulation CONT:


• SELECT specifies which columns • GROUP BY forms groups of
are to appear in output. rows with same column value.
• FROM specifies table(s) to be
used. • HAVING filters groups
• WHERE filters rows. subject to some condition.
• ORDER BY specifies the
order of the output.

3
8/19/2014

Example 1 -All Columns, All


Employee Table Rows
• List full details of all staff.
– SELECT staffNo, fName, lName,
address, position, sex, DOB, salary,
branchNo
FROM Employee;

Example 2 - Specific Columns, All


All Columns, All Rows Rows
• Can use * as an abbreviation for 'all • Produce a list of salaries for all
columns': staff, showing only staff number,
• SELECT * first and last names, and salary.
FROM Employee; • SELECT staffNo, fName, lName,
salary
FROM Employee;

Example 3 - Use of DISTINCT Example 3 Use of DISTINCT


• List the branch numbers. • Use DISTINCT to eliminate
• SELECT branchNo duplicates:
• FROM Employee; • SELECT DISTINCT branchNo
FROM Employee;

4
8/19/2014

Example 4 - Specific Columns, Example 5- All Columns,


Specific Rows. Specific Rows.
• Find the salaries of employees • Find all the information relating
named White. to employees named White.
• SELECT Salary as Remuneration • SELECT *
FROM Employee FROM Employee
WHERE Surname = ’White’; WHERE Surname = ’Employee’;

Example 7 Comparison Search


Example 6 - calculated field Condition

• Produce a list of monthly salaries for all • List all staff with a salary greater
employees, showing staff number, first than 10,000.
and last names, and salary details • SELECT staffNo, fName, lName,
position, salary
• SELECT Snumber, Fname, Lname,
FROM Staff
Salary / 12 AS MonthlySalary
WHERE salary > 10000;
FROM Employee;

Example 8 Compound Comparison


Search Condition Could also write:
• Find all employees who are managers or • SELECT staffNo, fName, lName,
supervisors. position
• SELECT * FROM Staff
FROM Employee WHERE position IN ('Manager',
‘Supervisor');
WHERE position = ‘Manager' OR position
= ‘Supervisor';

5
8/19/2014

Example 9 Range Search


Condition Could also write:
• List all Employees with a salary between • SELECT staffNo, fName, lName, position,
20,000 and 30,000. salary
• SELECT staffNo, fName, lName, position, • FROM Employee
salary WHERE salary>=20000 AND salary <=
FROM Employee 30000;
WHERE salary BETWEEN 20000 AND
30000;

Alternative JOIN
Constructs
Simple join query
• Find the names of the employees and • SQL provides alternative ways to specify joins:
the cities in which they work. • FROM Employee E JOIN Department D ON
• SELECT Employee.FirstName, E.Dept = D.DeptName
Employee.Surname, Department.City • FROM Employee JOIN Department USING
DeptName
FROM Employee, Department • FROM Employee NATURAL JOIN Department
WHERE Employee.Dept = • In each case, FROM replaces original FROM and
Department.DeptName; WHERE. However, first produces table with two
identical DeptName columns

Three Table Join Three Table Join


• For each branch, list staff who manage • Alternative formulation for FROM
properties, including city in which branch is and WHERE:
located and properties they manage. • FROM (branch b JOIN Staff s
• SELECT b.branchNo, b.city, s.staffNo, fName, USING branchNo) AS bs JOIN
lName, propertyNo PropertyForRent p USING staffNo
FROM branch b, staff s, property_for_rent p
WHERE b.branchNo = s.branchNo AND
s.staffNo = p.staffNo
ORDER BY b.branchNo, s.staffNo, propertyNo

6
8/19/2014

Outer Joins Left Outer Join

• To include unmatched rows in result • List branches and properties that are
table, use an Outer join. in
same city along with any unmatched
branches.
• SELECT b.*, p.*
FROM Branch1 b LEFT JOIN
PropertyForRent1 p ON b.bCity =
p.pCity;

Right Outer Join


Full Outer Join
• List branches and properties in same • List branches and properties in same city
city and any unmatched properties.
and any unmatched branches or
• SELECT b.*, p.* properties.
FROM Branch1 b RIGHT JOIN • SELECT b.*, p.*
PropertyForRent1 p ON b.bCity = FROM Branch1 b FULL JOIN
p.pCity;
PropertyForRent1 p ON b.bCity = p.pCity;

Aggregation
Aggregation
• ISO standard defines five – AVG returns average of values
aggregate functions. These are: in a specified column.
– COUNT returns number of – MIN returns smallest value in a
values in a specified column. specified column.
– SUM returns sum of values in a – MAX returns largest value in a
specified column. specified column.

7
8/19/2014

Aggregate functions Aggregate functions


• Each operates on a single column of a table • COUNT(*) counts all rows of a table,
and return single value. regardless of whether nulls or duplicate
values occur.
• COUNT, MIN, and MAX apply to numeric • Can use DISTINCT before column name to
and non-numeric fields, but SUM and AVG eliminate duplicates.
may be used on numeric fields only. • DISTINCT has no effect with MIN/MAX
• Apart from COUNT(*), each function (it eliminates duplicates itself),
eliminates nulls first and operates only on • but may have with SUM/AVG, e.g.–
– select avg(sal) from emp ≠ select
remaining non-null values. avg(distinct sal) from emp;

Aggregate functions Aggregation examples


• Aggregate functions can be used only • The Count function
in SELECT list and in HAVING clause. – How many properties cost more than
£350 per month for rent?
• SELECT Count(*) AS count
FROM property
WHERE property.Rent > 350;

Aggregation examples Aggregation examples


• The Max, Min and Avg function • Using the Group By clause
– Find the minimum, maximum and average – Find the number of staff working in
staff salary. each branch and the total of their
salaries.
• SELECT MIN(salary) AS MIN, • SELECT bno, COUNT(sno) AS count,
MAX(salary) AS MAX, AVG(salary) SUM(salary) AS sum
AS AVG FROM staff
FROM staff; GROUP BY bno
ORDER BY bno;

8
8/19/2014

Aggregation examples Aggregation examples


• Using predicates on grouping • SELECT bno, COUNT(sno) AS count,
results SUM(salary) AS sum
– For each branch office with FROM staff
more than one member of GROUP BY bno
staff, find the number of staff HAVING COUNT(SNO) > 1;
working in each branch and the
sum of their salaries.

Multiple Grouping Columns


Subqueries
• Find number of properties handled by each • Some SQL statements can have a
staff member. SELECT embedded within them.
• SELECT s.branchNo, s.staffNo, COUNT(*) • A subselect can be used in WHERE
AS count and HAVING clauses of an outer
SELECT, where it is called a subquery
FROM Staff s, PropertyForRent p or nested query.
WHERE s.staffNo = p.staffNo • Subselects may also appear in
GROUP BY s.branchNo, s.staffNo INSERT, UPDATE, and DELETEs.
ORDER BY s.branchNo, s.staffNo;

Subquery with Equality Subquery with Equality


• Inner SELECT finds branch number
• List staff who work in branch at '163 Main for branch at '163 Main St' ('B003').
St'. • Outer SELECT then retrieves details
• SELECT staffNo, fName, lName, position of all staff who work at this branch.
FROM Staff • Outer SELECT then becomes:
WHERE branchNo = (SELECT branchNo • SELECT staffNo, fName, lName,
FROM Branch position
WHERE street = '163 Main St'); FROM Staff
WHERE branchNo = 'B003';

9
8/19/2014

Subquery with Subquery with


Aggregate Aggregate
• List all staff whose salary is greater than • Cannot write 'WHERE salary >
the average salary, and show by how much. AVG(salary)'
• SELECT staffNo, fName, lName, position, • Instead, use subquery to find average
salary – (SELECT AVG(salary) FROM salary (17000), and then use outer SELECT
Staff) to find those staff with salary greater
As SalDiff than this:
FROM Staff • SELECT staffNo, fName, lName, position,
salary – 17000 As salDiff
WHERE salary > (SELECT AVG(salary)
FROM Staff); FROM Staff
WHERE salary > 17000;

Subquery Rules Subquery Rules


• ORDER BY clause may not be used in • By default, column names refer to
a subquery (although it may be used table name in FROM clause of
in outermost SELECT). subquery. Can refer to a table in
FROM using an alias.
• Subquery SELECT list must consist
• When subquery is an operand in a
of a single column name or comparison, subquery must appear on
expression, except for subqueries right-hand side.
that use EXISTS. • A subquery may not be used as an
operand in an expression.

Questions

10

You might also like