You are on page 1of 22

Structured Query Language

SQL

So what is the most sought after skill in the IT industry today?

A - being able to sort out margins efficiently in Microsoft WORD B - an ability to throw your PC at your workmate? C - the ability to send e-mails to the wrong people D - SQL

What is SQL?

A database language 3 parts DDL (Data Definition Language)


set up tables, create keys, change table design labs 1&2

DCL (Data Control Language)


query, manipulate data in table(s)

control access permissions to the database etc. later

DML (Data Manipulation Language)


i.e. specify what to do, not how to do it

now and next

non-procedural

Widespread use in development (embedded in multiple platforms)

http://uadisq01.uad.ac.uk:5560/isqlplus

SELECT Query Structure

Basic Form
SELECT <attribute(s)> FROM <table(s)> WHERE <condition>;

Semi-colon at end * denotes all columns

SELECT * FROM Transport query 1 WHERE Make='BMW' OR Make='VOLVO';


4
How many rows in the answer?

Column Alias (AS)

Renames attributes for output result SELECT salary AS Pay FROM Personnel WHERE Surname = 'FRENCH';
Youll see from your database that Frenchs salary is 20184
RESULT Pay 20184

query 2

In Oracle, you can omit AS

Using two or more tables

Can use many tables

E.g.

query 3

SELECT p.div, b.div, surname FROM personnel p, branch b WHERE p.div=b.div and City='BRISTOL';
Table aliases List all tables used in FROM clause Specify matching columns in WHERE clause!!!!!! Make it clear which table each column belongs to

Use table.column notation where ambiguous

Can use table aliases to shorten

WHERE Clause

Any Boolean expression involving attribute conditions Use

column names, symbols =, <, etc., calculations, numbers, text

Combine conditions with AND, OR Text strings must be enclosed in single quotes case sensitive (in Oracle)! E.g. this will return nothing from your database SELECT * FROM PERSONNEL WHERE Sex='f';

query 4

LIKE operator

Used for string comparisons and pattern matching in WHERE clause Uses wildcards: _ (underscore): any single character (? in Access) % (percent): string of any length (* in Access)

SELECT * FROM PERSONNEL WHERE surname LIKE '_A%E'


query 5

picks 'BATE' and 'MACRAE' but not 'HAMILTON' or 'RAINES'

ORDER BY

ORDER BY <column> [ASC|DESC]

Sorts the result according to the column Can use several levels, e.g. SELECT * FROM PERSONNEL query 6 ORDER BY JobTitle, Salary Desc;

Sorts results by jobtitle, and where jobtitle is the same, sorts by salary, highest first

What's the result?

query 7

SELECT Surname,City,Salary AS Income FROM Personnel,Branch B WHERE Personnel.Div = b.div AND (City LIKE '%S%' OR Surname LIKE '_R%') ORDER BY CITY, SALARY DESC; ASURNAME
JAMES RAINES HAMILTON TRINGHAM KUMAR FRENCH BRAY MACRAE BROCK
SURNAME TRINGHAM CITY BRISTOL BRISTOL BRISTOL BRISTOL LONDON LONDON LONDON LONDON LONDON INCOME 42000 25872 18534 9384 30816 20184 18000 16200 12288

SURNAME JAMES RAINES HAMILTON TRINGHAM FRENCH BRAY BROCK

CITY BRISTOL BRISTOL BRISTOL BRISTOL LONDON LONDON LONDON CITY BRISTOL LONDON LONDON LONDON

INCOME 42000 25872 18534 9384 20184 18000 12288 INCOME 9384 20184 18000 12288

D SURNAME

CITY INCOME BRISTOL 9384

TRINGHAM FRENCH BRAY BROCK

Explicit Join

can specify JOINS explicitly in the From clause different types of JOIN operations: INNER, LEFT, RIGHT, FULL

SELECT <columns> FROM <table1> [INNER|LEFT|RIGHT|FULL] JOIN <table2> ON <Join Condition>;


11

query 8

SELECT city, jobtitle Worked FROM branchExample b LEFT JOIN personnel p ON b.div=p.div WHERE city <>'BRISTOL';
CITY JOBTITLE

LONDON LONDON LONDON LONDON LONDON LONDON LONDON LONDON LONDON LONDON LONDON MANCHESTER BIRMINGHAM

SECRETARY CLERK CHAIRMAN DIRECTOR MANAGER SECRETARY ACCOUNTANT CONSULTANT CONSULTANT MANAGER CONSULTANT

These are included in the LEFT JOIN even though there is no match. They would NOT be included if it were an INNER JOIN

12

More SELECT features


What if we wanted to strip out query 9 duplicates from the answer? Select distinct city, jobTitle Use DISTINCT word From branch b left join personnel p on b.div=p.div Where city <>'BRISTOL'; Can we perform maths in the SELECT? YES!!! SELECT salary/12 AS monthPay SELECT salary + bonus AS totalPay

13

Aggregates

extends SQL COUNT COUNT(*) how many tuples? COUNT(DISTINCT <field>) how many unique values in field? SUM, MAX, MIN, AVG Examples

14

SELECT COUNT(*) SELECT SUM(Salary) SELECT MIN(Salary),MAX(Salary),AVG(Salary)

GROUP BY

Applies aggregate to subsets of tuples (subtotals)


DIV SUM(SALARY)

SELECT Div, SUM(Salary) FROM Personnel GROUP BY Div SELECT SUM(Salary) FROM Personnel

30
20 10

98400
95790 179340

SUM(SALARY) 373530

15

SELECT Div, SUM(Salary) FROM Personnel

Error!

Group conditions: HAVING

HAVING

For conditions at the group level Can only be used with GROUP BY

WHERE is for conditions on individual rows


SELECT div, max(salary)- min(salary) FROM PERSONNEL GROUP by div HAVING max(salary)- min(salary)>30000;

query10

16

For each division where total salary is more than 25,000, show no. of employees and total salary. Which SQL will achieve this?

A
B

SELECT Div, COUNT(Surname), SUM(SALARY) FROM Personnel GROUP BY Div HAVING SUM(Salary)>25000;

SELECT Div, COUNT(Surname), SUM(SALARY) FROM Personnel WHERE Salary > 25000 GROUP BY Div;
SELECT Div,COUNT(Surname),SUM(SALARY) Total FROM Personnel GROUP BY Div HAVING Total>25000; Both A and C are correct

C D

Use of Aliases

Renaming

Finds employees who share the same manager and the same job title

columns in the result output table abbreviations for use within SQL

Joining a table with itself

to find multiples instances of an attribute, e.g.

Query11

SELECT p1.surname , p2.surname FROM personnel p1, personnel p2 WHERE p1.manager = p2.manager and p1.surname <> p2.surname and p1.jobtitle = p2.jobtitle;

18

Syntax of SELECT
The full syntax of an SQL Select statement is
SELECT [DISTINCT] <attribute list> FROM <table list> [WHERE <condition>] [GROUP BY <attribute list>] [HAVING <group condition>] [ORDER BY <attribute list>]; [] denotes optional parts. Explicit JOIN not included

19

Keyword Definitions

WHERE

A condition on individual tuples determines whether it is included in the result implicit joins (e.g. table1.key = table2.key) Collects together tuples which have the same value for the specified fields A condition on each group determines whether that group is included in result The result table is sorted with this clause

GROUP BY

HAVING

ORDER BY

20

SQL Tutor if you have bought the book!

Lots of SQL tutors online try Google!

21

Interactive practice environment for SQL Available in the DatabasePlace online You should have details and a password in your copy of Connolly/Begg

Links for practice


http://www.w3schools.com/sql/default.asp http://www.sqlcourse.com/ http://www.firstsql.com/tutor.htm

22

You might also like