A Structured Approach To SQL Query Design
A Structured Approach To SQL Query Design
TECHNICAL DESIGN
Team: Technology
Creation Date: 22 May 2009
Created By: Brendan Furey (BrendanPF@Yahoo.com)
Last Updated: 19 August 2009
Control: 21095268.doc
Version: 1.1
Approvals:
Document Control
Change Record
• With each major release, Oracle increases the power of SQL and its ability to do internally
what previously had to be programmed, but the developer community can be slow to keep
pace with advances
• ERP systems in particular tend to have very complex, highly granular data models, owing to
the need for generality. This makes for rather complex SQL, which can be daunting to develop
without good design techniques. In practice SQL is hardly ever designed and the temptation is
to design a procedural program with simpler embedded SQL statements
The purpose of this document is to describe a structured, graphical approach to the design of SQL
queries that may be a useful way of handling the complexity without reverting to procedural design. It
focuses on subquery structure and join orders, rather than on other areas such as grouping and
aggregation, or design patterns. The author has used it to design complex queries with up to 48 table
instances, and the approach is demonstrated using a real (rather simpler) example of a custom report
within Oracle’s Order Management and Inventory modules (see REF-2 for Oracle’s table
specifications).
Design Process
The approach is based on entity-relationship diagramming, but applied in a different way from its
usage in database design. The main steps in the design process are:
• Produce one or more entity-relationship diagrams that include all the physical entities required
for the query
o Where necessary, follow a top-down approach using higher level entities to group
related entities together, and break them down in secondary diagrams
o Use subtypes to show the logical structure as well as the physical, based on the query
requirements (eg display Ship To and Bill To customers as distinct subtypes for an
Invoice Print query)
• Produce a query structure diagram, showing proposed subqueries, including inline views and
each section of any unions
• Produce one or more entity-relationship diagrams for each subquery (including the main
query)
o Where necessary, follow a top-down approach using higher level entities to group
related entities together, and break them down in secondary diagrams
• Define a route through each diagram that a query plan could reasonably take, marking with
numbered arrows the sequence of entities visited
o Begin with a possible driving table, then pass to entities that are linked to entities
already visited, favouring the most constraining entities
o The sequence represents the order in which the tables will be joined in the code, but
need not be that followed by the SQL engine
o The join sequence will be a good starting point in analysing any performance
problems that may occur
Diagramming Tool
It is important for clarity that that entities and links can be sized and positioned flexibly. This
effectively means that diagrams need to be be manually constructed rather than generated, and
Oracle Designer and similar tools do not appear suitable. We have used Microsoft Visio.
Subtypes
Subtypes are often used at the logical phase of database design to represent the partitioning of an
entity into a number of subentities, followed by a physical implementation in one of a number of ways:
for example, a Party in Oracle's customer model may be one of several types, including Organisation
and Person, and this is physically implemented by a party_type column on the table. The concept is
used here more generally and more dynamically, to represent a division of an entity into groups of
records, according to any data conditions specified in the query. Subtypes are depicted as two or more
entities within another entity (but take care to avoid confusing with distinct entities within an entity
group, and may be nested. Subtypes within a query diagram normally correspond to distinct table
instances.
Attributes
Attributes do not appear on the diagrams, as they are not necessary for our purposes and cause
clutter and distortion of entities, reducing clarity.
Notation
The following two points refer to both ERDs and query diagrams.
• Entities
o Rounded boxes
• Relationships
• Constraining entities
• Join sequence
o Numbered arrows
Performance Tuning
The design process followed here results in a logical join sequence. When the Cost Based Optimiser
fails to find a good execution plan, the starting point in analysis is usually to compare its join order
with what the developer would expect, and if necessary hints (such as LEADING) can be added to
obtain a better plan. This tends to more of an issue with large queries.
Documentation
The design process described results in a document that makes large queries much easier to
understand for support staff.
Package Design
The type of ERDs shown here can be used in designing package structures for maintenance of logical
entities. For example, where Oracle’s customer model is used, the logical entities are usually at a
higher level than Oracle’s physical model and maintenance procedures would correspond to the
logical level represented on Entity-Relationship diagrams.
Requirement Summary
This is a custom report based on Oracle Applications (11.5.10) Inventory and Order Management
modules (the table definitions can be obtained from REF-2). It lists order lines that are sold at zero
price, and includes the Inventory COGS (Cost of Goods Sold) account distributions in two categories
(material and overhead). Briefly, the requirements are:
• List order lines with zero unit price, showing COGS Material and Overhead Inventory costs
(where they exist), along with Warehouse, Ship To and Item data
• Order lines may be of type Configuration or Non-Configuration, and the latter are non-
shippable, so do not have Inventory records, in which case print the Order Line records with
zero for the COGS costs
• Report driven by the dates of a GL period, applied to the Inventory records for Configuration
Lines, and the Order Lines for Non-Configuration Lines
Entity Overview
The diagram below gives an overview, showing how the main entity groups relate to each other, with
the complex entities broken down subsequently. Broken lines denote complex entities (but don’t
always come out in Word!).
COGS
Logical
Overhead
MTL
COGS
Transaction Physical Component
Material
Account
MTL Transaction
Non-
Line Type
Configuration
Other
Warehouse Model
GL Account
Account Configuration
Order Line
Line
Ship To
Inventory Item
Site Use
Product Line
Customer
Category
Ship To Item
Ship To
Site Use Inventory Item
Customer
Address
Other
Ship To
Category Set
Item
Entity/Subtype Structure
The table below shows the entity structure and the subtype structure where applicable. Italics denote
complex entities referenced within others.
Entity 1 Entity 2 Entity 3 Subtype 1 Subtype 2
GL Period
MTL Transaction Logical
MTL Transaction Physical
Account Account
GL Account
Overhead
Warehouse
Material
Order Header
Other
Order Line
Line
Line Type
Model
Configuration
Component
Ship To Ship To Site Use Non-Configuration
Customer Site
Address Party Site
Location
Customer Account
Customer
Party
Inventory Item
Item Category
Item Category
Product Line
Product Line
Category Category Set
Other
Query Structure
Configuration
Non-
Configuration
Transaction View
Main Query
Notes
• The query is driven by two different sets of source records, requiring the inner union
• The union goes into an inline view in order to avoid duplicating all the the other tables for
each section
Non- 1
Configuration*
Configuration*
2
Transaction*
7 Ship To
Inventory Item Order Header Warehouse
Site Use
3 8
10 Customer
Other
11
GL Period* GL Period*
1 1
Account
Linked
4
Configuration Line
MTL 5 Non-
Transaction Parent Component Configuration
Account Line
MTL Transaction 6 2
2
3
GL Account Model*
Account
7
Configuration* Non-Configuration*
Transaction*
Notes
• Observe that we have shown the GL Account entity without the subtypes that appeared in the
ERD. This represents a design decision not to link to separate instances of the table for the
subtypes, but instead link to a single instance and use the row-column pivotting technique to
obtain the two COGS amounts on a single line. See the notes section after the query code for
an explanation
• We have used a different subtyping for our MTL Transaction from that in the ERD. The record
linked to may be a logical or a physical transaction, and we link from it to its parent, if it exists
(logical case)
Notes
Outer Joins
Outer joins are a frequent source of errors in SQL, either by the join being incorrectly specified as
outer (or inner), or by the outer join syntax being incorrectly implemented (usually by including the (+)
on only some of the relevant clauses). ANSI join syntax (see notes on next section) makes it harder to
get the implementation wrong. Specification errors will be less likely if the join type is part of the
design. Outer joins are indicated by the same symbol as in Oracle native SQL - (+) - in the table
above.
Query Code
Text
SELECT /*+ LEADING (ilv) USE_NL (ooh) */
war.organization_code orgcode,
Notes
Row-Column Pivotting
The GL Account is regarded as having three subtypes for the purpose of this query. The query needs
to bring back two of them for a given transaction, and display cost values in two columns
corresponding to the subtypes, but one or the other may be missing. We prefer to avoid the
complications and likely inefficiency of attempting to achieve this by outer-joining to two instances and
instead use a row-column pivotting method, which is a useful general purpose technique that goes as
follows (let’s say we have n columns, COL_1-COL_n whose values are obtained by expressions
EXPRESSION_1- EXPRESSION_n and corresponding Where conditions CONDITION_1-
CONDITION_n):
• Join the table once for all conditions corresponding to the columns
Hints
The Explain Plan for the query was found to favour hash joins, and poor performance was obtained.
As a result a LEADING hint was added to each subquery, giving the preferred join order, following
directly from the design sequences, and where necessary USE_NL hints were added to ensure nested
loop joins. This gave much improved performance.
ANSI SQL
We would prefer to use ANSI join syntax, but cannot because the version of Oracle 10g we are using
(10g 10.2.0.3.0 ) has a bug that causes some ANSI queries to fail spuriously with ORA-01445
Issues
# Issue Description Note if closed
1 ANSI join syntax Oracle bug, see above