0% found this document useful (0 votes)
96 views

Introduction To SQL: Information Management

Uploaded by

Suneet Singh
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
96 views

Introduction To SQL: Information Management

Uploaded by

Suneet Singh
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 47

Information Management Ecosystem Partnerships

IBM Canada Lab

Summer/Fall 2010

Introduction to SQL

Information Management

© 2010 IBM Corporation


Information Management

Agenda
■ SQL
■ Data Definition Language
■ Data Manipulation Language
■ JOINs
■ Data Control Language
■ Transaction Control Statements

2 © 2010 IBM Corporation


Information Management

SQL in a nutshell

Standard language of relational database access is SQL (Structured
Query Language), designed for accessing tabular data

Data Definition Language (DDL)

Defines properties of data objects
CREATE, ALTER, DROP, TRANSFER OWNERSHIP


Data Manipulation Language (DML)

Used to retrieve, add, edit and delete data
SELECT, INSERT, UPDATE, DELETE


Data Control Language (DCL)

Controls access to databases and data objects
GRANT, REVOKE


Transaction Control Languages (TCL)

Groups DML statements into transactions that can collectively be
applied to a database or undone in the event of a failure
COMMIT, ROLLBACK, SAVEPOINT
3 © 2010 IBM Corporation
Information Management

Data Definition Language


■ To create, modify, delete objects in a database, SQL Data
Definition Language (DDL) is used.

■ DDL has four basic SQL statements:


–CREATE
–ALTER
–DROP
–DECLARE

4 © 2010 IBM Corporation


Information Management

CREATE Statement
Used to CREATE database objects
■ Table ■ Stored procedures
■ Index ■ Trigger
■ Schema ■ Alias
■ View ■ Method
■ User-defined function ■ Nickname
■ User-defined data type ■ Sequence
■ Buffer pool ■ Table space

CREATE TABLE <table name>...


name>
CREATE SCHEMA <schema name>...

5 © 2010 IBM Corporation


Information Management

ALTER Statement
Used to CHANGE database objects
■ Table ■ Sequence
■ Table space ■ Type
■ Database partition ■ View
■ Procedure ■ Method
■ Function ■ User mapping
■ Nickname ■ Buffer pool
■ Schema ■ Index

ALTER TABLE <table name>...


ALTER INDEX <index name>...

6 © 2010 IBM Corporation


Information Management

DROP Statement
Used to REMOVE database objects

■ Can drop any object created with CREATE <database object >
and DECLARE <table> statements.

DROP TABLE <table name>...


DROP INDEX <index name>...

7 © 2010 IBM Corporation


Information Management

Data Manipulation Language


■ Retrieving Data
– Select Statement
■ Inserting Data
– Insert Statement
■ Updating Data
– Update Statement
■ Deleting Data
– Delete Statement

8 © 2010 IBM Corporation


Information Management

Retrieving Data – Select Statement


■ The SELECT statement is used to retrieve data from a
database table

–Syntax:

SELECT <%EXPRESSIONS%>
FROM <%TABLE REFERENCES%>

■ Expressions: Column names, values, function calls etc.


■ Table References is a source that returns tabular data
–Usually a list of table names
–Subqueries or tabular functions are also accepted

9 © 2010 IBM Corporation


Information Management

Additional Clauses – Where,Order By,Group By


■ WHERE allows you to filter the query
–Specify filters based on expressions
■ GROUP BY allows you to consolidate the query
–Groups by the field you specify
–This function allows you to utilize aggregate functions
■ HAVING also allows you to filter the aggregate data
■ ORDER BY allows you to sort the query
–Specify the sort order of the returned set
–Can specify ASC, DESC
• e.g. ORDER BY NAME DESC
■ Clauses must appear in the order above after the select
statement

10 © 2010 IBM Corporation


Information Management

Select Statement
EXAMPLES
SELECT *
FROM EMPLOYEE
 Retrieves all fields in the employee table
 Note: * will return all fields

EMPNO FNA LNAM EMPNO FNA LNAM


ME E ME E
161 Bob Joe 161 Bob Joe
143 Steve Craig 143 Steve Craig
n n
155 John Smith 155 John Smith

11 © 2010 IBM Corporation


Information Management

Select Statement
SELECT EMPNO, FNAME, LNAME
FROM EMPLOYEE WHERE EMPNO > 150
– Retrieves the EMPNO,FNAME,LNAME columns from the table
EMPLOYEE where the EMPNO is greater than 150
EMPNOFNA LNAM EMPNO FNA LNAM
ME E ME E
161 Bob Joe 155 John Smith
143 Steve Craig 161 Bob Joe
No particular order!
n FNAME, LNAME
SELECT EMPNO,
FROM EMPLOYEE
155EMPNOJohn
WHERE > 150 Smith
AND FNAME = 'Bob'
– Finding the Bobs' that have EMPNO greater than 150

EMPNO FNA LNAM


ME E
12 161 Bob Joe © 2010 IBM Corporation
Information Management

Select Statement
Renaming the
Examples column to
SELECT MAX(SALARY) as MAX_SALARY, TITLE MAX_SALAR
FROM EMPLOYEE
GROUP BY TITLE
Y
 Get the Highest salary for each title bracket
EMPNO FNA LNA TITLE SALA Calculated
ME ME RY from the
Aggregate
151 Joe Brian MGR 100 function
000 MAX()
123 Steve Jack ENTR 35 000
Non-
Y
Aggregate
166 Tom MAX_SALARY TITLE
Jones SENI 75 000 columns must
120 000 OR MGR be grouped
190 Eric 45
Jame
000 MGR ENTRY
120 together
s 000
13
75 000 SENIOR © 2010 IBM Corporation
Information Management

Select Statement
SELECT TITLE,AVG (SALARY) AS SALARY_AVG
FROM EMPLOYEE
GROUP BY TITLE
HAVING AVG (SALARY) > 50000
– Get all of the Titles that have an average salary
above 50000
TITLE SALARY_ TITLE SALARY_A
AVG VG
SENIOR 75 000 MGR 110 000
SELECT TITLE,AVG (SALARY) AS SALARY_AVG
SENIOR 75 000
MGR 110 000
FROM EMPLOYEE
GROUP BY TITLE
HAVING AVG (SALARY) > 50000
ORDER BY TITLE
– The above query, ordered by Title

14 © 2010 IBM Corporation


Information Management

Inserting Data – Insert Statement


■ The INSERT statement allows you to insert a single record or
multiple records into a table
–Syntax:

INSERT INTO <%TABLE REFERNCE%>


( <%EXPRESSION%> )
VALUES
(%VALUES%)

OR

INSERT INTO <%TABLE REFERNCE%>


( <%EXPRESSION%> **)
SELECT <%EXPRESSION%>
FROM <%TABLE REFERNCE%>
**Explicit mapping is not necessary
15 © 2010 IBM Corporation
Information Management

Insert Statement
Examples
INSERT INTO EMPLOYEE (FNAME , LNAME)
VALUES ('Joe' , 'Bob')

– Inserts the name Joe Bob into the table Employee

TITLE FNAME LNAME


NULL Joe Bob

Value was
not provided,
a NULL (if
column is
nullable) will
place hold
16 © 2010 IBM Corporation
Information Management

Insert Statement
INSERT INTO EMPLOYEE (FNAME,LNAME,TITLE)
SELECT FNAME,LNAME,CATEGORY
FROM OUTSOURCED
WHERE CATEGORY = 'TRANSFER'

– Selects the people from table Outsourced with the


category field as Transfer into the Employee Table
• Note: If both tables have the exact same fields
then an explicit mapping is not required.
OUTSOUR
CED EMPLOYEE
FNAME TITLE FNAM LNAM
LNA CATEGO
ME RY E E
Billy Sue TRANSF NULL Joe Bob
ER TRANSFE Billy Sue
Susan John NEW R
17 HIRE © 2010 IBM Corporation
Information Management

Data Modifications – Update Statement


■ The UPDATE statement is used to update existing records in
a table
–Syntax:

UPDATE <%TABLE REFERENCE%>


SET <%EXPRESSION%> = %VALUE%

■ UPDATE uses the same WHERE clause as the SELECT

18 © 2010 IBM Corporation


Information Management

Update Statement
Example
UPDATE EMPLOYEE
SET BONUS = SALARY/10
 Update every entry in the employee table and set the
bonus field to 10% of the salary field

SALARY BONU SALARY BONUS


S 50 000 5 000
50 000 NULL 35 000 3 500
35 000 20 000 100 000 10 000
100 000 NULL 150 000 15 000
150 000 NULL

19 © 2010 IBM Corporation


Information Management

Update Statement
UPDATE EMPLOYEE
SET TITLE = 'Executive'
WHERE TITLE = 'Manager' and Tenure = 10
– Update title of Employees who has tenure of 10 and is
currently a manager in the Employee Table

FNAME LNAM TITLE TENU


E RE
Stan Jones Manager 5
Bob Billy Executive 12
Joe Moe Senior 14
FNAME LNAME TITLE TENURE
Susie
Stan Susan
Jones Manager
Manager 10
5
Bob Billy Executive 12
Joe Moe Senior 14
Susie Susan Executive 10
20 © 2010 IBM Corporation
Information Management

Rules
■ INSERT Rules
– INSERT rule is implicit when a foreign key is specified.

– A row can be inserted at any time into a parent table without any action being taken
in dependent table.

– A row cannot be inserted into dependent table unless there is a row in parent table
with a parent key value equal to foreign key value of row being inserted, unless
foreign key value is null.

– If an INSERT operation fails for one row during an attempt to insert more than one
row, all rows inserted by the statement are removed from the database.

■ UPDATE Rules
– RESTRICT – Update for parent key will be rejected if a row in dependent table
matches original values of key.

– NO ACTION – Update operation for parent key will be rejected if any row in
dependent table does not have a corresponding parent key when update statement
is completed (default).

21 © 2010 IBM Corporation


Information Management

Data Modifications – Delete Statement


■ The DELETE statement is used to remove rows in a table

DELETE <%TABLE REFERENCE%>

■ DELETE uses the same WHERE clause as a SELECT


■ Delete removes data only not the table itself

22 © 2010 IBM Corporation


Information Management

Delete Statement
Example
DELETE EMPLOYEE
 All entries inside employee are deleted
EMPNO STATU
S EMPNO STAT
1232 RETIR US
ED
DELETE EMPLOYEE
WHERE141
STATUS =ACTIVE
'Retired'
51 RETIR
Remove all the entries
 where the status is retired
ED
EMPNO STATU EMPNO STAT
S
US
1232 RETIR
141 ACTIV
23
ED © 2010 IBM Corporation
Information Management

DELETE Rules
■ RESTRICT
– Prevents any row in parent table from being deleted if any dependent
rows are found.
■ NO ACTION (default)
– Enforces the presence of a parent row for every child after all the
referential constraints are applied.
– The difference between NO ACTION and RESTRICT is based on when
constraint is enforced.
■ CASCADE
– Implies that deleting a row in parent table automatically deletes any
related rows in dependent table.
■ SET NULL
– Ensures that deletion of a row in parent table sets values of foreign key
in any dependent row to null (if nullable).
– Other parts of row are unchanged.

24 © 2010 IBM Corporation


Information Management

Joins
■ Linking of one or more tables

SELECT *
FROM EMPLOYEE E
INNER JOIN TEAM T ON E.TEAMID = T.ID

■ Several Types of joins:


–Cartesian Product
–Inner Join
–Left Outer Join
–Right Outer Join
–Full Outer Join

25 © 2010 IBM Corporation


Information Management

Cartesian Product
■ Joins every entry to a corresponding entry regardless of
criteria
■ Also called a Cross Join
■ This is particularly useful if you need all possible
permutations
–For Example:

EMPNO ROL EX TITL X EMPNO ROL EX TITL


E employee
All possible T E partners E T E
SELECT * FROM DETAIL D1, DETAIL D2
WHERE D1.EMPNO <> D2.EMPNO
■ Need to be careful – 30,000 X 100,000 = 3,000,000,000 Rows!

26 © 2010 IBM Corporation


Information Management

Cross Join Example


SELECT * FROM INFO I, DETAIL D

INFO (I) DETAIL (D)


EMPNO FNAM LNAM EMPNO ROL EX TITL
E E CROSS E T E
JOIN
001 Emily Steven 001 MGR 445 Mrs.
s 004 EXE 101 Dr.
002 John Doe
EMPNO FNAM LNAM EMPNO ROL
C
EX TITL
003 James Smith
E E E T E
001 Emily Steven 001
001
MGR 445 Mrs.
s MGR 445 Mrs.
001 Emily Steven 004
004
EXE
EXE
101 Dr.
101 Dr.
002 John Doe
s 001 C
MGR 445 Mrs.
C
27
003
002 James
John Smith
Doe 004 EXE 101 Dr.© 2010 IBM Corporation
Information Management

Walk Through – Cartesian Product


SELECT *
FROM TABLE T1,TABLE T2
WHERE T1.ID = T2.ID

T1 T2 T1.ID C2 T2.I C4
D
ID C2 ID C4 A 11 A 33
A 11 A 33 B 22 Z 44
B 22 Z 44 A 11 Z 44
T1.ID C2 T2.I C4 B 22 A 33
D
T1.ID C2 T2.I C4
WHE A 11 A 33
D
RE B 22 Z 44
A 11 A 33
A 11 Z 44 © 2010 IBM Corporation
28
Information Management

INNER Join
■ INNER join requires a match on both sides
■ Both entries must satisfy the condition that was set in the
ON clause
■ This is useful if you need to create views that have relevance
to each other
–For example:
Require Descriptions from a Look-up table linking with an ID
■ Will return nothing if there is nothing in common

29 © 2010 IBM Corporation


Information Management

Inner Join Example


SELECT *
FROM INFO I
INNER JOIN DETAIL D ON I.EMPNO =
D.EMPNO
INFO (I) DETAIL (D)
EMPNOFNAM LNAM EMPNO ROL EX TITL
INNER
E E JOIN E T E
001 Emily Steven 001 MGR 445 Mrs.
s 004 EXE 101 Dr.
002 EMPNO Doe LNAM EMPNO
John FNAM ROL EXC TITL
003 JamesE Smith E E T E
001 Emily Steven 001 MGR 445 Mrs.
s
30
matching © 2010 IBM Corporation
Information Management

Walk Through – Inner Join


SELECT *
FROM TABLE T1 INNER JOIN T2
ON T1.ID = T2.ID

T1 T2

ID C2 ID C4 T1.ID C2 T2.I C4
A 11 A 33 D
B 22 Z 44 A 11 A 33

31 © 2010 IBM Corporation


Information Management

Right Outer Join


■ Right Outer Join joins tables on the condition that it matches
the fields that are specified in the ON clause
– Right Outer – Condition must be met for the Right Side
■ If condition not met
– take entry from the designated side and fill NULL in for the
non-designated side

32 © 2010 IBM Corporation


Information Management

Right Outer Join Example


SELECT *
FROM INFO I
RIGHT OUTER JOIN DETAIL D ON I.EMPNO =
D.EMPNO
INFO (I) DETAIL (D)
EMPNO FNAM LNAM RIGHT EMPNO ROL EX TITL
E E OUTER E T E
001 Emily Steven JOIN
001 MGR 445 Mrs.
s
EMPNO FNAM LNAM EMPNO004 ROL EXE
EX 101
TITL Dr.
002 John Doe
E E E CT E
003 James Smith
001 Emily Steven 001 MGR 445 Mrs.
s
matching 004 EXE 101 Dr.
33
NULL NULL NULL C © 2010 IBM Corporation
Information Management

Walk Through – Right Outer Join


SELECT *
FROM TABLE T1 RIGHT OUTER JOIN TABLE T2
ON T1.ID = T2.ID
WHERE T1.ID IS NOT NULL

T1 T2
T1.ID C2 T2.ID C4
ID C2 ID C4
A 11 A 33
A 11 A 33
NULL NULL Z 44
B 22 Z 44

T1.ID C2 T2.ID C4
T1.ID C2 T2.ID C4
A 11 A 33
WHE A 11 A 33
NULL NULL Z 44
RE

34 © 2010 IBM Corporation


Information Management

Left Outer Join


■ Left Outer Join joins tables on the condition that it matches
the fields that are specified in the ON clause
–Left Outer – Condition must be met for the Left Side
■ If condition not met
– take entry from the designated side and fill NULL in for the
non-designated side

35 © 2010 IBM Corporation


Information Management

Left Outer Join Example


SELECT *
FROM INFO I
LEFT OUTER JOIN DETAIL D ON I.EMPNO =
D.EMPNO
INFO (I) DETAIL (D)
EMPNOFNAM LNAM EMPNO ROL EX TITL
LEFT
E E OUTER E T E
001 Emily Steven JOIN 001 MGR 445 Mrs.
s 004 EXE 101 Dr.
002 EMPNO
John FNAM
Doe LNAM E R E T C
M
003 E
James Smith E P OX I
001 Emily Steven N L T T
O E L
s
E
002 Johnmatching
Doe
0 M4 M
36 © 2010 IBM Corporation
Information Management

Walk Through – Left Outer Join


SELECT *
FROM TABLE T1 LEFT OUTER JOIN TABLE T2
ON T1.ID = T2.ID
WHERE T2.ID IS NOT NULL

T1 T2
T1.ID C2 T2.I C4
ID C2 ID C4
D
A 11 A 33
A 11 A 33
B 22 Z 44 NULL
B 22 NUL
T1.ID C2 T2.I C4 L
T1.ID C2 T2.I C4
WHE D
D
RE A 11 A 33
A 11 A 33
B 22 NUL NULL
L
37 © 2010 IBM Corporation
Information Management

Full Outer Join


■ Will match records on columns where there is a match
■ If condition is not met
–The side that the condition is not met will fill with NULLs
–The side that the condition is met will be replicated
–Repeats for both sides
■ This is useful for when you require information from both

tables that have relevance with each other


–For example:
Find the cars that are blue, cars that are white or neither

38 © 2010 IBM Corporation


Information Management

Full Outer Join Example


SELECT *
FROM INFO I
FULL OUTER JOIN DETAIL D ON I.EMPNO =
D.EMPNO
INFO (I) DETAIL (D)
EMPNO FNAM LNAM
FULL EMPNO ROL EX
E E OUTER TITL
JOIN E T E
001 Emily Steven
s 001 MGR 445 Mrs.
002 John Doe 004 EXE 101 Dr.
E F L E RET C
003 James
M Smith M
P NN P OX I
N AA N L TT
O MM O E L
EE E
39
0ES matching 0 M4 M © 2010 IBM Corporation
Information Management

Walk Through – Full Outer Join


SELECT *
FROM TABLE T1 FULL OUTER JOIN TABLE T2
ON T1.ID = T2.ID
WHERE T2.ID IS NOT NULL AND T1.ID IS NOT NULL

T1 T2
T1.ID C2 T2.ID C4
ID C2 ID C4
A 11 A 33
A 11 A 33
B 22 NULL NULL
B 22 Z 44 NULL NULL Z 44
T1.ID C2 T2.ID C4
T1.ID C2 T2.ID C4
A 11 A 33
WHE A 11 A 33
B 22 NULL NULL
RE
NULL NULL Z 44
40 © 2010 IBM Corporation
Information Management

Challenge Question
SELECT E.EMPNO, A.RANK, T.DESCRIPTION
FROM EMPLOYEE E
LEFT OUTER JOIN ATTRIBUTE A ON E.AID = A.ID
FULL OUTER JOIN TYPE T ON E.TID = T.ID
WHERE A.RANK = 'Major' Attribute
ID RANK
Employee Type
ID DESCRIPT
1 Private
EMPNO AI TI
D D ION 2 Sergeant
9021 1 3 1 Army 3 Captain
4533 3 3 2 Marine 4 Major
1345 1 1 3 Air Force 5 General
EMPNO RANK DESCRIPTION
9038 4 1 RESULT:
9038 Major Army
41 © 2010 IBM Corporation
Information Management

Challenge Question
SELECT RANK
FROM EMPLOYEE
INNER JOIN ATTRIBUTE
ON EMPLOYEE.AID = ATTRIBUTE.ID
GROUP BY RANK
HAVING COUNT (EMPNO) > 1

Employee Attribute
ID RANK
EMPNO AI TI
1 Private
D D RESULT: RANK
9021 1 3 2 Sergeant Private
4533 3 3 3 Captain
1345 1 1 4 Major
42
9038 4 1 5 General © 2010 IBM Corporation
Information Management

Challenge – Prove they are equivalent


How are they equivalent?

SELECT *
FROM TABLE T1 INNER JOIN T2
ON T1.ID = T2.ID
– IS EQUIVALENT TO
SELECT *
FROM TABLE T1,TABLE T2
WHERE T1.ID = T2.ID
– IS EQUIVALENT TO
SELECT *
FROM TABLE T1 RIGHT OUTER JOIN TABLE T2
ON T1.ID = T2.ID
WHERE T1.ID IS NOT NULL

43 © 2010 IBM Corporation


Information Management

Aliases
■ Aliases : a reference to an object

SELECT E.FNAME AS 'First Name'


FROM EMPLOYEE E

■ E is now referenced to the table Employee

■ AS 'First Name' lets the column be returned as First Name


rather than FNAME

■ Important when distinguishing objects from different


sources that may have conflicting names

44 © 2010 IBM Corporation


Information Management

Data Control Language (DCL)


■ Data Control Language SQL statements control the security
and permissions of the objects or parts of the database(s)
■ GRANT - gives user's access privileges to database
■ REVOKE - withdraw access privileges given with the GRANT
command

GRANT SELECT ON <table name>...


REVOKE ALL ON <table name>...

45 © 2010 IBM Corporation


Information Management

Transaction Control Statements (TCL)



Transaction Control statements are used to manage the
changes made by DML statements. It allows statements to be
grouped together into logical transactions.
■ COMMIT - save work done
■ SAVEPOINT - identify a point in a transaction to which you can
later roll back
■ ROLLBACK - restore database to original since the last COMMIT
■ SET TRANSACTION - Change transaction options like isolation
level and what rollback segment to use

46 © 2010 IBM Corporation


Information Management Ecosystem Partnerships
IBM Canada Lab

Questions? Summer/Fall 2010

E-mail: [email protected]
Subject: “DB2 Academic Workshop”

Information Management

© 2010 IBM Corporation

You might also like