Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 49

Structured Query Language

Oracle – SQL training Olivier Comte


French CSO
2015
Oracle SQL training
Session 1

• Definitions:
– Database, Schema
– DB Server, DB Clients (Integrated Development Environment – IDE, programs)
– SQL, PL/SQL, APIs

• Connection to an Oracle database


• Database structure (tables, sequences, indexes), sessions, transaction
• Basic queries
– SELECT
– DELETE
– INSERT
– UPDATE
– MERGE

• Exercises

Copyright 2014 Manhattan Associates, Inc. Strictly Confidential. Not for Distribution.
2
A few definitions

• Database server / DBMS


Database server: a machine running at least one instance of a Database management system (DBMS). Oracle,
MySQL, DB2, SyBase or SQL Server, for instance, are DBMS.

• Database / Schema
In Oracle acceptation, each Oracle server instance is called a database. Each database is a collection of named
schemas. Schemas are the containers of all DB objects.

• DB clients
Software that uses the services provided by the DB Server. For instance:
– Integrated Development Environment – IDE. PL/SQL Developer and Oracle SQL Developer are two IDE used by MA
consultants to access the DB.
– Command Line Interface – CLI. SQL*Plus is a CLI used by our client to run our DB patches.
– Frameworks. DAL and Hibernate two frameworks providing API (see below) used by WMOS to access the DB.

• Session
A DB session is a conversation between a DB client and a DB server. It starts by a connection and ends by a
disconnection or a crash (hang up). Usually the connection requires a user name and a password.

• API
Application Programming Interface: protocol used by programs to interface each others.

Copyright 2014 Manhattan Associates, Inc. Strictly Confidential. Not for Distribution.
3
Languages related definitions

• SQL
Structured Query Language: an old language to query the DBMS. ANSI but very incomplete. Human readable
ASCII texts. Every DBMS offers its own extensions. Oracle version is divided in 4 parts: DDL, DML, TCL and DCL.
– DDL
Data Definition Language: used to define the database structure or schema (CREATE, DROP, ALTER...).
– DCL
Data Control Language: used to manage permissions to data (GRANT, REVOKE, DENY...).
– DML
Data Manipulation Language: used to manage data (SELECT, INSERT, UPDATE, DELETE, MERGE...).
– TCL
Transaction Control Language: used to manage transactions i.e. changes made by DML (COMMIT, ROLLBACK...).

• PL/SQL
Procedural Language / Structured Query Language: an extension of SQL that adds procedural
languages features to SQL (loops, tests, procedures, functions…). It is a different language but it
allows direct calls of (almost) all DML and TCL constructs. It also allows DDL and DCL statements
through EXECUTE IMMEDIATE.

• SQL*Plus
A command-line query interface (even if a GUI and a Web UI also exist). Mostly used for batches. Its
own idiom allow to launch SQL commands, PL/SQL blocks and SQL*Plus commands.
For instance, database patched (SDN) are delivered to the client as SQL*Plus scripts and should be
tested through sqlplus command line even when they only contain SQL statements.

Copyright 2014 Manhattan Associates, Inc. Strictly Confidential. Not for Distribution.
4
Connection to the database

o Adds (optionally) a new TNS declaration in file tnsnames.ora (it names every known DB
instances)
– For Oracle Administrator client: %ORACLE_HOME%\network\admin
– For Oracle light client: %TNS_ADMIN%
scpp11r2=
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(HOST = discovery.us.manh.com )(PORT = 1522))
)
(CONNECT_DATA =
(SERVER = DEDICATED) (SERVICE_NAME = scpp11r2.us.manh.com )
)
)

o Connection string:
– Using TNS: schema/password@tns_name
SQLTRAINING/SQLTRAINING@scpp11r2
– Without using TNS: schema/password@database_server:port/service_name
SQLTRAINING/SQLTRAINING@discovery.us.manh.com:1522/scpp11r2.us.manh.com

Copyright 2014 Manhattan Associates, Inc. Strictly Confidential. Not for Distribution.
5
Database basics: tables

• Definition: a collection of related data held in a structured format within a


schema. It consists of fields (columns) and rows.
• Syntax:
– Creation:
create table Z_LPN_DETAIL -- a detail line of a LPN
( LPN_ID integer not null
, ITEM_ID integer not null
, QUANTITY number not null
, CREATE_DTTM timestamp default current_timestamp not null
, LAST_UPDATE_DTTM date default current_date not null
, USER_ID varchar2(20)
);
– Creation from a query:
create table Z_ESSAI as
select LPN_ID, LPN_NUMBER
from Z_LPN
where rownum <= 10;

– Destruction
drop table Z_ESSAI;

Copyright 2014 Manhattan Associates, Inc. Strictly Confidential. Not for Distribution.
6
Database basics: some datatypes
Oracle ANSI Description
Datatype Datatype
VARCHAR2(size) CHAR VARYING(n)
Variable-length character string having length between 1 and size characters. Maximum
NCHAR VARYING(n)
NVARCHAR2(size) size is 4000 characters. The prefix N stands for Unicode (National in fact).
CHAR(size) String of exactly size characters. Maximum size is 2000 characters. Default is 1.
NCHAR(size) Prefix N is for Unicode.
NUMBER or NUMBER(*) or FLOAT Floating-point number.
NUMBER(p) Equivalent to NUMBER(p, 0).
INTEGER or INT Equivalent to NUMBER(*,0).
NUMBER(p,s) Fixed-point decimal number of p digits with s digits of decimals. p can also be * (means
implementation limit - around 39 in current Oracle versions) .
The precision p (total number of digits) can range from 1 to 38.
The scale s can range from -84 to 127.
FLOAT(p) Floating-point binary number of p digits. p (number of binary digits) can range from 1 to 126.
BINARY_FLOAT 32-bit floating-point number.
BINARY_DOUBLE REAL 64-bit floating-point number.
DATE Date and time – no fractional seconds, no time zone.; now is SYSDATE or CURRENT_DATE.
TIMESTAMP Date and time – no time zone.; now is SYSTIMESTAMP or CURRENT_TIMESTAMP.
CLOB Character Large Object storage (single-byte or multibyte)
NCLOB Character Large Object storage (unicode)
BLOB Binary Large Object storage (pictures, video, XMLs, …)
BFILE Binary external File locator

You can also define your own custom datatypes by specifying both the structure of the data and the ways
of operating on it (CREATE TYPE).

Copyright 2014 Manhattan Associates, Inc. Strictly Confidential. Not for Distribution.
7
Database basics: keys

• Primary Key – a set of fields with unique not null values within the
whole table. At most one primary key exists per table. It can be used to
uniquely references each row of a table.

alter table Z_LPN


add constraint Z_LPN_PK primary key(LPN_ID)
using index;

• Foreign Key – a set of fields that references the primary key of another
table to keep the consistency between 2 tables
alter table Z_LPN
add constraint Z_LPN_FK1 foreign key(LOCATION_ID)
references Z_LOCATION(ID);

Copyright 2014 Manhattan Associates, Inc. Strictly Confidential. Not for Distribution.
8
Sample schema structure

Z_LPN Z_LPN_LOCK
Z_LOCATION

Z_LPN_DETAIL Z_LOCK

Z_ITEM
Z_ITEM_SET_DETAIL

Copyright 2014 Manhattan Associates, Inc. Strictly Confidential. Not for Distribution.
9
Sample schema structure - DDL
create table Z_LOCATION --Location
( LOCATION_ID integer primary key
, CLASS char(1) not null
, BARCODE varchar2(20) not null
, DESCRIPTION varchar2(20)
);
create table Z_ITEM --Item
( ITEM_ID integer primary key
, REFERENCE varchar2(20) not null
, DESCRIPTION varchar2(50)
);
create table Z_LPN --LPN
( LPN_ID integer primary key
, LPN_NUMBER varchar2(20) not null
, LOCATION_ID integer
, LPN_STATUS number(2)
, PLT_ID integer
);
create table Z_LPN_DETAIL
( LPN_ID integer not null
, ITEM_ID integer not null
, QUANTITY number not null
);
create table Z_LOCK
( LOCK_CODE char(2) primary key
, PRIORITY number(2) not null
);
create table Z_LPN_LOCK
( LPN_ID integer not null
, LOCK_CODE char(2) not null
);
create table Z_ITEM_SET_DETAIL --Item set
( ITEM_ID integer not null
, ITEM_DETAIL_ID integer not null
, QUANTITY number default 1 not null check(QUANTITY > 0)
);

Copyright 2014 Manhattan Associates, Inc. Strictly Confidential. Not for Distribution.
10
Database basics: locks and transactions

• When data is inserted, updated or deleted into a table, it is stored within


a temporary place and the modifications are visible with your current
session.
• Modified rows are “locked” for other sessions. It means that other
sessions trying to modify them will be locked (frozen) temporarily.
• If you COMMIT the changes, the modifications are applied to the real
table and the locks are released. Everybody can see the changes now
and the locked sessions can continue.
• If you ROLLBACK the changes, the modifications are cancelled and the
locks are released. Nothing has changed since the begin of the
transaction but the locked sessions can continue.
• COMMIT or ROLLBACK ends the current transaction (and starts the
next one).
• Locking sessions can produce deadlocks!

Copyright 2014 Manhattan Associates, Inc. Strictly Confidential. Not for Distribution.
11
Database basics: locks and transactions

• When data is inserted, updated or deleted into a table, it is stored within


a temporary place and the modifications are visible with your current
session.
• Modified rows are “locked” for other sessions. It means that other
sessions trying to modify them will be locked (frozen) temporarily.
• If you COMMIT the changes, the modifications are applied to the real
table and the locks are released. Everybody can see the changes now
and the locked sessions can continue.
• If you ROLLBACK the changes, the modifications are cancelled and the
locks are released. Nothing has changed since the begin of the
transaction but the locked sessions can continue.
• COMMIT or ROLLBACK ends the current transaction (and starts the
next one).
• Locking sessions can produce deadlocks!

Copyright 2014 Manhattan Associates, Inc. Strictly Confidential. Not for Distribution.
12
Database basics: What is a deadlock?
Transaction #1 Transaction #2
update Z_LPN
set USER_ID = ‘FOO’
where LPN_ID = 1; update Z_LPN_DETAIL
1st row of
Z_LPN is
set QUANTITY = 2*QUANTITY
locked
where LPN_ID = 1
and ITEM_ID = 2;
update Z_LPN_DETAIL
« ORA-00060: 1st row of
deadlock detected
set USER_ID = ‘FOO’
while waiting for
Z_LPN_DETAIL
is locked
resource » is thrown
where LPN_ID = 1;
in session 1.
update Z_LPN
Transaction #1 is set LPN_STATUS = LPN_STATUS+1
rolled back and dies
#1 is frozen, where LPN_ID = 1;
waiting for the
lock on
Z_LPN_DETAIL
Commit; to be released Commit; 1st#2
rowis of Z_LPN
also is
frozen,
locked
waiting for the
lock on Z_LPN
Updates are written onto the
be released
disk
and Transaction #2 ends

Copyright 2014 Manhattan Associates, Inc. Strictly Confidential. Not for Distribution.
13
Rules of thumb to avoid (some) deadlocks (coding for )

• Inside a transaction, changes should respect the following order:


• Header tables are always updated/inserted before detail tables.
• In a table, rows are updated/inserted according to their primary key
order.
• Deletions should follow the reverse order.

• Commit as often as possible (as soon the DB global state is acceptable)


but not more often!

• Take care of open interactive session in your DB client connected to client


production database!

Copyright 2014 Manhattan Associates, Inc. Strictly Confidential. Not for Distribution.
14
Database basics: sequences

• A sequence is a database object from which unique integers can be


generated in sequence. When the next number is generated, the
sequence is incremented independent of the transaction (no need to
commit and rollback don’t recycle the number generated).
• Example:
-- Creation:
create sequence Z_LPN_SEQ;
insert into Z_LPN(LPN_ID, LPN_NUMBER, LPN_STATUS)
values(Z_LPN_ID_SEQ.nextval, 'LPN1', 10);
insert into Z_LPN(LPN_ID, LPN_NUMBER, LPN_STATUS)
values(Z_LPN_ID_SEQ.nextval, 'LPN2', 10);
select Z_LPN_ID_SEQ.currval as LAST_LPN_ID from dual;
commit;

Copyright 2014 Manhattan Associates, Inc. Strictly Confidential. Not for Distribution.
15
Database basics: sequences as default values

• Prior to Oracle 12c nextval couldn’t be used as default value for a


column. A common workaround was to add a “before insert” trigger to
simulate it.
• After Oracle 12c, just write:
create table Z_LPN
( LPN_ID INTEGER default Z_LPN_ID_SEQ.nextval primary key
, LPN_NUMBER VARCHAR2(20) not null
, LOCATION_ID INTEGER
, LPN_STATUS NUMBER(2) default 10 not null
, PLT_ID INTEGER
);

Copyright 2014 Manhattan Associates, Inc. Strictly Confidential. Not for Distribution.
16
SELECT query (simplified)
SQL Description
[WITH alias_name AS Defines a sub-query with an alias in order to
(SELECT […] reuse it in the main select.
Has been extended in Oracle 11 for ANSI
)[ ,…] SQL hierarchical queries.
]
SELECT [DISTINCT] expression Lists fields to be displayed.
[[AS] expression can be [table_alias.]field or
field_alias] a constant or a function.
[ ,…]
FROM table [table_alias] Declare the table(s) from which the fields
[ ,…] will be selected. table can be replaced by a
sub-query or by an alias_name.
[WHERE condition] Filter the rows according to some condition

[GROUP BY field[,…] List of fields that will uniquely identify the


[HAVING condition] returned (aggregated) rows optionally
filtered by some condition applied on the
] resulting rows.

[ORDER BY field [DESC] [,…]] Order the rows in ASCENDING (default) or


DESCENDING order
Copyright 2014 Manhattan Associates, Inc. Strictly Confidential. Not for Distribution.
17
SELECT query
Syntax elements
• Expressions
– Column Names (must be associated with table FROM clause)- select LNP_NUMBER from Z_LPN;
– Functions (can be a user or Oracle supplied function) - ex. select upper(LNP_NUMBER) from Z_LPN;
– Operations ( ||, -,+,*,/ …) ex. Select 1200*3 from DUAL;
– Constants (Character string or numeric constants) ex. SELECT ‘Employee Report’ FROM dual;
– Cases (Gives SELECT statement IF-THEN-ELSE functionality) ex- select ID, case TYPE when ‘I‘ then ‘Input’ else ‘Output’ end from Z_LPN;
– Fields (Table.Column)

• Column Aliases
– Used to rename column heading
– Used double quotes if alias contains blanks
– The AS keyword is optional

• Boolean expressions
– Only in WHERE (or WHEN)
– New operators: =, <>,>,<, >=, <=,BETWEEN, NOT BETWEEN, IN, NOT IN, LIKE, NOT LIKE, IS NULL, IS
NOT NULL
– != is a useless Oraclism. Always prefer the SQL <>.

• DISTINCT in a SELECT clause


– DISTINCT or UNIQUE (skip duplicated values) ex. SELECT DISTINCT USER_ID FROM Z_LPN;
– Useless in a IN or EXISTS.

Copyright 2014 Manhattan Associates, Inc. Strictly Confidential. Not for Distribution.
18
SELECT query
Built-in functions

• Character Functions
– LENGTH
– UPPER, LOWER, INITCAP, CONCAT, TRIM, LTRIM, RTRIM, LPAD, RPAD
– INSTR, SUBSTR, REPLACE

• Numeric Functions
– ROUND, TRUNC
– GREATEST, LEAST, SIGN, CEIL, FLOOR
– MOD, SQRT, POWER

• Date/Time Functions
– SYSDATE, CURRENT_DATE, CURRENT_TIMESTAMP, SYSTIMESTAMP
– EXTRACT, TO_CHAR

• Conversion Function
– TO_CHAR , TO_NUMBER, TO_DATE

• Miscelaneous
– USER, SYS_CONTEXT
– NVL, NVL2, COALESCE, DECODE, NULLIF

Copyright 2014 Manhattan Associates, Inc. Strictly Confidential. Not for Distribution.
19
SELECT query
some functions

COALESCE(expr, expr[, …]) -- returns the first expr NOT NULL (equivalent to the Oraclism NVL)
SUBSTR(expr, begin[, length]) -- returns the substring of the expr

TRIM(expr) -- removes leading and ending spaces in expr

CASE expr WHEN value1 THEN expr1


[WHEN value2 THEN expr2]
[ELSE expr3]
END -- returns expr1 if expr = value1, … else expr3

CASE WHEN condition1 THEN expr1


[WHEN condition2 THEN expr2]
[ELSE expr3]
END -- returns expr1 if condition1 is met, … else expr3

Copyright 2014 Manhattan Associates, Inc. Strictly Confidential. Not for Distribution.
20
SELECT query
some other functions

TRUNC(date) -- returns the date or timestamp at midnight (it removes the time
part).

TO_DATE(string, mask)
TO_TIMESTAMP(string, mask) -- converts a string into a date according to the
provided mask.

TO_CHAR(date, mask) -- converts a date into a string matching the mask

TRANSLATE(string, from_chars, to_chars) -- replaces characters or removes them.


EXTRACT(part FROM date) -- returns the specified field from a date expression.
» Part can be YEAR, MONTH, DAY, HOUR, MINUTE or SECOND.

Copyright 2014 Manhattan Associates, Inc. Strictly Confidential. Not for Distribution.
21
SELECT query
Aggregate functions

Function name Returned value


sum(expr) Sum of expr values.
count(expr) Count the number of rows!
Uses the following more explicit syntaxes:
count(1) or count(*)
count(distinct expr) Count of distinct values of expr.
rank(number) within group(order by expr) Rank of a value in a group of values.
dense_rank(number) within group(order by expr)

max(expr) Maximum/minimum/average/variance of
min(expr) expr.
avg(expr)
variance(expr)
wm_concat(expr) Deprecated! Concatenate all the expr string
values separated by comma
listagg(expr,separator) within group(order by expr) Concatenate all the expr values
separated by separator

Aggregate functions ignore silently NULL values of expr.

Copyright 2014 Manhattan Associates, Inc. Strictly Confidential. Not for Distribution.
22
SELECT query
Aggregate examples
=> Select all LPNs in status 10 Z_LPN
SELECT lpn_number LPN_NUMBER
FROM z_lpn
WHERE lpn_status = 10
LPN1
LPN2
=> Count the number of LPN per status
SELECT COUNT(1) as "COUNT", lpn_status as status Z_LPN
FROM z_lpn COUNT STATUS
GROUP BY lpn_status
2 10
=> Select the list of LPN statuses used by less than 7 7 30
LPNs, in decreasing number of LPN order
6 20
SELECT COUNT(1) as "COUNT", lpn_status as status
FROM z_lpn
Z_LPN
GROUP BY lpn_status
HAVING COUNT(1) < 7 COUNT STATUS
ORDER BY COUNT(1) DESC
6 20
2 10

Copyright 2014 Manhattan Associates, Inc. Strictly Confidential. Not for Distribution.
23
SELECT query
joins
• INNER JOIN: Returns only rows where the join condition is met between the 2
tables.
=>Select the content of LPNs in status 10 (SKU + quantities)

SELECT zl.lpn_number, zi.description, zld.quantity


FROM z_lpn zl
INNER JOIN z_lpn_detail zld ON zld.lpn_id = zl.lpn_id
INNER JOIN z_item zi ON zi.item_id = zld.item_id
WHERE zl.lpn_status = 10

Z_LPN Z_LPN_DETAIL Z_ITEM


LPN_NUMBER LPN_ID LPN_ID ITEM_ID LPN_ID DESCRIPTION
LPN2 6 9 2 9 Housse de couette bleu clair

LPN1 9 6 9 6 Oreiller
6 16 6 Drap housse bleu clair

… … … ,,,

Copyright 2014 Manhattan Associates, Inc. Strictly Confidential. Not for Distribution.
24
SELECT query
joins
• INNER JOIN: Returns only rows where the join conditions are met between the 2
tables.
=> Select the content of LPNs in status 30 (SKU + quantities)
SELECT zl.lpn_number, zi.description, zld.quantity
FROM z_lpn zl
INNER JOIN z_lpn_detail zld
ON zld.lpn_id = zl.lpn_id
INNER JOIN z_item zi
ON zi.item_id = zld.item_id
WHERE zl.lpn_status = 30;

RESULT
LPN_NUMBER DESCRIPTION QUANTITY
LPN3 Ours en peluche 2
LPN3 Pack d'ours 3
,,, ,,, ,,,

Copyright 2014 Manhattan Associates, Inc. Strictly Confidential. Not for Distribution.
25
SELECT query
joins
• LEFT/RIGHT JOIN: Returns rows of the left/right table joined to the other table
when possible.
=>Select the locks, with their priority, put on each LPN in status 10 if any
SELECT zl.lpn_number, zlo.lock_code, zlo.priority
FROM z_lpn zl
LEFT OUTER JOIN
( z_lpn_lock zll
INNER JOIN z_lock zlo ON zlo.lock_code = zll.lock_code
) ON zll.lpn_id = zl.lpn_id
WHERE zl.lpn_status = 10;

Z_LPN Z_LPN_LOCK Z_LOCK


LPN_NUMBER ID LPN_ID LOCK_CODE PRIORITY
LOCK_CODE
LPN1 9 1 AB 10 AB
LPN2 6 1 FU 30 FU
1 HT 10 HT

Copyright 2014 Manhattan Associates, Inc. Strictly Confidential. Not for Distribution.
26
SELECT query
joins
• LEFT/RIGHT JOIN: Returns rows of the left/right table joined to the other table
when possible.
=>Select the locks, with their priority, put on each LPN in status 10 if any
SELECT zl.lpn_number, zlo.lock_code, zlo.priority
FROM z_lpn zl
LEFT OUTER JOIN
( z_lpn_lock zll
INNER JOIN z_lock zlo ON zlo.lock_code = zll.lock_code
) ON zll.lpn_id = zl.lpn_id
WHERE zl.lpn_status = 10;

RESULT
LPN_NUMBER LOCK_CODE PRIORITY
LPN1 HT 10
LPN1 AB 10
LPN1 FU 30
LPN2

Copyright 2014 Manhattan Associates, Inc. Strictly Confidential. Not for Distribution.
27
SELECT query
joins

• FULL JOIN: Returns all the rows of the 2 tables joined together where possible.

=>For each component of a set of items and for each LPN in status 10, display the
components, quantities and the LPN numbers in status 10 where they can be found. Items
into LPN in status 10 which are not part of a set are kept.

SELECT zi_h.description as kit, zl.lpn_number


, COALESCE(zld.quantity, 0)*COALESCE(zisd.quantity, 1), zi_d.description
FROM z_item_set_detail zisd
INNER JOIN z_item zi_h
ON zi_h.item_id = zisd.item_id
FULL OUTER JOIN
( z_lpn zl
INNER JOIN z_lpn_detail zld
ON zld.lpn_id = zl.lpn_id AND lpn_status = 10
) ON zisd.detail_item_id = zld.item_id
INNER JOIN z_item zi_d
ON zi_d.item_id = COALESCE(zld.item_id, zisd.detail_item_id)
ORDER BY zi_h.description ASC, zl.lpn_number ASC;

Copyright 2014 Manhattan Associates, Inc. Strictly Confidential. Not for Distribution.
28
KIT
ID KIT KIT ITEM ID
Advanced
7 Query
Ensemble syntaxHousse de couette bleu clair
draps 1 bleu clair 4
7 Ensemble draps 1 bleu clair Taie d'oreiller bleu clair 6
7 Ensemble draps 1 bleu clair Drap housse bleu clair 3
7 Ensemble draps 1 bleu clair Drap bleu clair 2
12 Ensemble draps 2 bleu clair Housse de couette bleu clair 4
12 Ensemble draps 2 bleu clair Drap housse bleu clair 3
12 Ensemble draps 2 bleu clair Housse de traversin bleu clair 11
12 Ensemble draps 2 bleu clair Drap bleu clair 2
16 Pack de tissu en gros Flanelle rouge sang 15
16 Pack de tissu en gros Mousseline jaune d'oeuf 14
16 Pack de tissu en gros Dentelle vert caca d'oie 13
10 Pack d'ours Ours en peluche 9

iLPN

ITEM_ID QUANTITY LPN_NUMBER


2 3 LPN1
3 3 LPN1
4 3 LPN1
6 6 LPN1
10 1 LPN1
1 5 LPN2
8 1 LPN2
3 2 LPN2

Copyright 2014 Manhattan Associates, Inc. Strictly Confidential. Not for Distribution.
29
RESULT

KIT LOCATION iLPN QUANTITY iLPN ITEM

Ensemble draps 1 bleu clair LPN1 3 Drap housse bleu clair


Ensemble draps 1 bleu clair LPN1 3 Housse de couette bleu clair

Ensemble draps 1 bleu clair LPN1 3 Drap bleu clair

Ensemble draps 1 bleu clair LPN1 12 Taie d'oreiller bleu clair

Ensemble draps 1 bleu clair LPN2 2 Drap housse bleu clair

Ensemble draps 2 bleu clair LPN1 3 Drap housse bleu clair

Ensemble draps 2 bleu clair LPN1 3 Drap bleu clair

Ensemble draps 2 bleu clair LPN1 3 Housse de couette bleu clair

Ensemble draps 2 bleu clair LPN2 2 Drap housse bleu clair

Ensemble draps 2 bleu clair 0 Housse de traversin bleu clair

Pack de tissu en gros 0 Flanelle rouge sang

Pack de tissu en gros 0 Mousseline jaune d'oeuf

Pack de tissu en gros 0 Dentelle vert caca d'oie

Pack d'ours 0 Ours en peluche

LPN1 1 Pack d'ours


LPN2 5 Oreiller
LPN2 1 Couette

Copyright 2014 Manhattan Associates, Inc. Strictly Confidential. Not for Distribution.
30
SELECT query
joins

• CROSS JOIN: Returns all the rows of the left table multiply by all the rows of the
right tables. Also called “Cartesian product”.
=>Evaluates the number of LPN for each reserve location and for each lock code
of priority 10
SELECT zloc.barcode, zlo.lock_code, COUNT(DISTINCT zl.lpn_id) as "COUNT"
FROM z_location zloc
CROSS JOIN z_lock zlo
LEFT OUTER JOIN
(z_lpn zl
INNER JOIN z_lpn_lock zll
ON zll.lpn_id = zl.lpn_id
) ON zlo.lock_code = zll.lock_code AND zloc.location_id = zl.location_id
WHERE zloc.class = 'R' AND zlo.priority = 10
GROUP BY zloc.barcode, zlo.lock_code
ORDER BY zloc.barcode, zlo.lock_code;

No condition (ON) needed.


CROSS JOIN is equivalent to a simple comma.
select A from B cross join C  select A from B, C

Copyright 2014 Manhattan Associates, Inc. Strictly Confidential. Not for Distribution.
31
RESULT
Z_LOCATION
BARC LOCK_CODE COUNT
BARCODE ID ODE

1 ABC 01 AB 0
ABC 01

2 ABC 01 HT 0
ABC 02

3 ABC 02 AB 1
ABC 03

8 ABC 02 HT 1
XYZ 01

9 ABC 03 AB 0
XYZ 02

10 ABC 03 HT 0
XYZ 03
XYZ 01 AB 0

XYZ 01 HT 0
Z_LOCK
XYZ 02 AB 0
LOCK_CODE ID
XYZ 02 HT 0
AB 3
XYZ 03 AB 0
HT 2
XYZ 03 HT 0

Copyright 2014 Manhattan Associates, Inc. Strictly Confidential. Not for Distribution.
32
SELECT query
joins

• Other categories
• Self Join: Joins one row from a table to another row in same table (aliased).
• Equijoin: Data is joined between tables with an equality type operator
• Non-Equijoin: Data is joined between tables with a non-equality type operator
• Join Using: Another syntax for equijoin.
Select ename, dname FROM emp JOIN dept USING (deptno);
 Select ename, dname FROM emp JOIN dept ON emp.deptno = dept.deptno;

• Natural Join: Is the same as a join using where the joining columns are all the
columns that have the same name and same datatype between the two joined
tables (not usable for MA tables).
SELECT ename, dname FROM emp NATURAL JOIN dept;

Copyright 2014 Manhattan Associates, Inc. Strictly Confidential. Not for Distribution.
33
INSERT query
•2 main syntaxes:
•Example: we insert a new iLPN containing items of reference 001, 006 and 009.

o Insert one row

INSERT INTO table [( field[, …])]


VALUES (field[, …])

Example:
INSERT INTO Z_LPN (LPN_ID, LPN_NUMBER, LPN_STATUS, USER_ID)
VALUES((SELECT MAX(LPN_ID)+1 FROM z_lpn), 'LPN_TO_DELETE', 10, 'WM‘)

o Insert one or multiple rows

Copyright 2014 Manhattan Associates, Inc. Strictly Confidential. Not for Distribution.
34
INSERT query
•2 main syntaxes:
•Example: we insert a new iLPN containing items of reference 001, 006 and 009.

o Insert one row


o Insert one or multiple rows
[WITH alias_name AS (SELECT […])]
INSERT INTO table [ ( field[, …])]
SELECT …
--Insert a new iLPN containing items of reference 001, 006 and 009.
INSERT INTO Z_LPN_DETAIL (LPN_ID, ITEM_ID, QUANTITY, USER_ID)
SELECT (SELECT LPN_ID FROM Z_LPN WHERE LPN_NUMBER='LPN_TO_DELETE')
, ITEM_ID
, 11
, 'WM'
FROM Z_ITEM
WHERE REFERENCE IN ('009', '006', '001');

Copyright 2014 Manhattan Associates, Inc. Strictly Confidential. Not for Distribution.
35
INSERT query
•Multi-table syntax:
INSERT ALL
INTO table1 [( field[, …])]
VALUES (field[, …])
INTO table2 [( field[, …])]
VALUES (field[, …])

select …;
Example:
INSERT ALL
INTO Z_LPN (LPN_ID, LPN_NUMBER, LPN_STATUS, USER_ID)
VALUES(LPN_ID, 'LPN_TO_DELETE', 10, USER_ID)
INTO Z_LPN_DETAIL (LPN_ID, ITEM_ID, USER_ID)
VALUES(LPN_ID, 'LPN_TO_DELETE', 10, USER_ID)
Select Z_LPN_ID_SEQ.nextval as LPN_ID
, ITEM_ID, 'WM' as USER_ID
from Z_ITEM
where REFERENCE = '008‘;

Copyright 2014 Manhattan Associates, Inc. Strictly Confidential. Not for Distribution.
36
INSERT query
•Multi-table syntax:
INSERT ALL
[WHEN(condition1) THEN]
INTO table1 [( field[, …])]
VALUES (field[, …])
[WHEN(condition2) THEN]
INTO table2 [( field[, …])]
VALUES (field[, …])
[…]
select …;
Example:
INSERT ALL
INTO Z_LPN (LPN_ID, LPN_NUMBER, LPN_STATUS, USER_ID)
VALUES(LPN_ID, 'LPN_TO_DELETE', 10, USER_ID)
INTO Z_LPN_DETAIL (LPN_ID, ITEM_ID, USER_ID)
VALUES(LPN_ID, 'LPN_TO_DELETE', 10, USER_ID)
Select Z_LPN_ID_SEQ.nextval as LPN_ID
, ITEM_ID, 'WM' as USER_ID
from Z_ITEM
where REFERENCE = '008‘;
Copyright 2014 Manhattan Associates, Inc. Strictly Confidential. Not for Distribution.
37
INSERT query
•Multi-table syntax 2:
INSERT FIRST
[WHEN(condition1) THEN]
INTO table1 [( field[, …])]
VALUES (field[, …])
[WHEN(condition2) THEN]
INTO table2 [( field[, …])]
VALUES (field[, …])
[…]
select …;

In this case, we will insert only one row per row of the select clause (as far as the corresponding
conditions are satisfied).

Copyright 2014 Manhattan Associates, Inc. Strictly Confidential. Not for Distribution.
38
UPDATE query
•Basic syntax:
UPDATE table [table_alias]
SET field = value
[, … ]
[WHERE conditions]

Warning: without the optional WHERE clause all rows will be updated!

=>Update the status of the new LPN to 30, the user to your name and the last update timestamp to now.
UPDATE z_lpn
SET lpn_status = 30
, user_id = 'JULIEN‘
, last_update_dttm = CURRENT_TIMESTAMP
WHERE lpn_number = 'LPN_TO_DELETE'

Copyright 2014 Manhattan Associates, Inc. Strictly Confidential. Not for Distribution.
39
UPDATE query
•Advanced syntax:
UPDATE table [table_alias]
SET ( field[, … ] )
= (select …)
[WHERE conditions]
Warning: without the optional WHERE clause all rows will be updated, even there is a WHERE
clause in the subquery!

The value of the fields being updated can be used in the subquery.

=>For all the items being a part of a set, update the quantities of the new LPN to be a multiple
of the set. In addition, update the user with the user of the set detail.

Copyright 2014 Manhattan Associates, Inc. Strictly Confidential. Not for Distribution.
40
UPDATE query
•Advanced syntax:
=>For all the items being a part of a set, update the quantities of the new LPN to be a multiple
of the set. In addition, update the user with the user of the set detail.

UPDATE z_lpn_detail zld


SET (quantity, user_id)
= (SELECT FLOOR(zld.quantity/zisd.quantity)*zisd.quantity
, zisd.user_id
FROM z_item_set_detail zisd
WHERE zisd.detail_item_id = zld.item_id
)
WHERE EXISTS(SELECT 1
FROM z_item_set_detail zisd
WHERE zisd.detail_item_id = zld.item_id
)
AND EXISTS(SELECT 1
FROM z_lpn zl
WHERE zld.lpn_id = zl.lpn_id
AND zl.lpn_number = 'LPN_TO_DELETE'
);

Copyright 2014 Manhattan Associates, Inc. Strictly Confidential. Not for Distribution.
41
UPDATE query
•More advanced syntax:
UPDATE
(select …
where …
) alias
SET …
WHERE …;

You can update through a SELECT in Oracle if the following conditions are met:
• Only one base table is updated

• All other joined tables are key-preserved: each of them must have at most one row for each
row of the base table.

Unfortunately Oracle is not good at detecting these conditions (group


by is not enough). So you should always prefer MERGE syntax.

Copyright 2014 Manhattan Associates, Inc. Strictly Confidential. Not for Distribution.
42
DELETE query

DELETE FROM table [table_alias]


[WHERE conditions]
Warning: without the optional WHERE clause all rows will be deleted (more or less equivalent to a
TRUNCATE TABLE)!

ÞDelete the new iLPN


DELETE FROM z_lpn_detail zld
WHERE zld.lpn_id in (SELECT zl.lpn_id
FROM z_lpn zl
WHERE zl.lpn_number = 'LPN_TO_DELETE'
);
DELETE FROM z_lpn zl
WHERE zl.lpn_number = 'LPN_TO_DELETE';

ÞRewrite the first query using EXISTS instead of IN.

Copyright 2014 Manhattan Associates, Inc. Strictly Confidential. Not for Distribution.
43
DELETE query

DELETE FROM table [table_alias]


[WHERE conditions]
Warning: without the optional WHERE clause all rows will be deleted (more or less equivalent to a
TRUNCATE TABLE)!

ÞDelete the new iLPN


ÞRewrite the first query using EXISTS instead of IN.
DELETE FROM z_lpn_detail zld
WHERE EXISTS(SELECT 1
FROM z_lpn zl
WHERE zld.lpn_id = zl.lpn_id
AND zl.lpn_number = 'LPN_TO_DELETE'
);

Copyright 2014 Manhattan Associates, Inc. Strictly Confidential. Not for Distribution.
44
MERGE query
Merging two tables or views
It allows to insert, update or delete some records into one single SQL statement

=> Modify the content of LPN1 to add 2 quantity of each SKU and remove the SKU which
exceeds the quantity of 4.
MERGE INTO z_lpn_detail T1
USING
(SELECT zl.LPN_ID, zi.ITEM_ID
FROM z_lpn zl
CROSS JOIN z_item zi
WHERE zl.lpn_number = 'LPN1'
) T2
ON (T1.lpn_id = T2.lpn_id and T1.item_id = T2.item_id)
WHEN MATCHED THEN
UPDATE SET QUANTITY = t1.QUANTITY + 2
, USER_ID = 'MERGE SQL'
, create_dttm = CURRENT_TIMESTAMP
DELETE WHERE t1.QUANTITY > 4
WHEN NOT MATCHED THEN
INSERT (LPN_ID, ITEM_ID, QUANTITY, USER_ID)
VALUES (T2.LPN_ID, T2.ITEM_ID, 2, 'MERGE SQL');

Copyright 2014 Manhattan Associates, Inc. Strictly Confidential. Not for Distribution.
45
MERGE query
Exercise: Bridges
See the « Functional Specifications » of each bridge in file:

Advanced SQL I.6 FS bridges.txt

Copyright 2014 Manhattan Associates, Inc. Strictly Confidential. Not for Distribution.
46
MERGE query
Exercise: 6 bridges input tables
create table Z_INPT_ITEM( INPT_ID integer /*default Z_INPT_ID_SEQ.nextval*/ primary key
, REFERENCE varchar2(20) not null
, DESCRIPTION varchar2(50) -- null means deletion of the item
);

create table Z_INPT_LPN_DETAIL( INPT_ID integer /*default Z_INPT_ID_SEQ.nextval*/ primary key


, LPN_NUMBER varchar2(20) not null
, ITEM_REFERENCE varchar2(20) not null
, QUANTITY number
);

create table Z_INPT_LPN( INPT_ID integer /*default Z_INPT_ID_SEQ.nextval*/ primary key


, LPN_NUMBER varchar2(20) not null
, LOCATION_BARCODE varchar2(20)
, LPN_STATUS number(2) not null
);

create table Z_INPT_PLT( INPT_ID integer /*default Z_INPT_ID_SEQ.nextval*/ primary key


, PLT_NUMBER varchar2(20)
, LPN_NUMBER varchar2(20) not null
);

create table Z_INPT_ITEM_SET_DETAIL( INPT_ID integer /*default Z_INPT_ID_SEQ.nextval*/ primary key


, REFERENCE varchar2(20) not null
, DETAIL_REFERENCE varchar2(20) not null
, QUANTITY number
);

create table Z_INPT_LPN_LOCK( INPT_ID integer /*default Z_INPT_ID_SEQ.nextval*/ primary key


, LPN_NUMBER varchar2(20) not null
, LOCK_CODE char(2)
);

Copyright 2014 Manhattan Associates, Inc. Strictly Confidential. Not for Distribution.
47
MERGE query
Merging two tables or views
BEFORE
LPN ITEM QUANTITY
LPN1 Drap bleu clair 3,00
LPN1 Drap housse bleu clair 3,00
LPN1 Housse de couette bleu clair 3,00
LPN1 Taie d'oreiller bleu clair 6,00
LPN1 Pack d'ours 1,00

ID LPN_ID ITEM_ID
41 1 1
AFTER
42 1 2
43 1 3 LPN ITEM QUANTITY
44 1 4 LPN1 Traversin 2,00
45 1 5
LPN1 Housse de traversin bleu clair 2,00
46 1 6
47 1 7 LPN1 Pack de tissu en gros 2,00
48 1 8 LPN1 Couette 2,00
49 1 9 LPN1 Ensemble draps 2 bleu clair 2,00
50 1 10
LPN1 Mousseline jaune d'œuf 2,00
51 1 11
52 1 12 LPN1 Flanelle rouge sang 2,00
53 1 13 LPN1 Ours en peluche 2,00
54 1 14 LPN1 Ensemble draps 1 bleu clair 2,00
55 1 15
LPN1 Oreiller 2,00
56 1 16
LPN1 Dentelle vert caca d'oie 2,00
LPN1 Pack d'ours 3,00

Copyright 2014 Manhattan Associates, Inc. Strictly Confidential. Not for Distribution.
48
End of the first session!

Copyright 2014 Manhattan Associates, Inc. Strictly Confidential. Not for Distribution.
49

You might also like