Constraints work as expected, with one Oracle-specific capability worth knowing: a constraint can be DEFERRABLE INITIALLY DEFERRED, meaning it is checked at COMMIT rather than at each statement. That is what lets you insert two halves of a circular reference, or swap two unique values, without an intermediate state that violates the rule.
Constraints also have states beyond on and off: ENABLE VALIDATE is the normal one; ENABLE NOVALIDATE enforces new rows without checking existing ones, which is how you add a constraint to a large table without a long outage; and DISABLE with RELY tells the optimiser to believe a relationship it is not enforcing, which is used in warehouses and is a loaded gun.
Sequences and identity. GENERATED ALWAYS AS IDENTITY is the modern form. Sequences remain available and useful when several tables share a number space. Note CACHE - the default of 20 means sequence values are pre-allocated in memory and a shutdown loses the unused ones, so sequences have gaps and that is by design. Code that assumes contiguous identifiers is wrong.
Analytic functions are one of the areas where Oracle led and the syntax is now standard: ROW_NUMBER, RANK, DENSE_RANK, LAG, LEAD, FIRST_VALUE, SUM ... OVER. They compute across a window of rows without collapsing them. Oracle adds some the others lack - RATIO_TO_REPORT, NTILE, KEEP (DENSE_RANK FIRST/LAST) - and MATCH_RECOGNIZE, which does row pattern matching and has no real equivalent elsewhere.
Hierarchical queries. CONNECT BY PRIOR is Oracle's original tree traversal, with LEVEL, SYS_CONNECT_BY_PATH and CONNECT_BY_ISLEAF. It is concise and it is Oracle-specific. Recursive WITH is the standard form and portable. Use recursive WITH in new code unless you need CONNECT BY's cycle handling, which is better.
Materialized views store the result of a query and can refresh on commit, on demand, or on a schedule. With query rewrite the optimiser can silently use one in place of the base tables - a major warehouse feature. Query rewrite requires a licence consideration on some editions, and fast refresh requires materialized view logs on the base tables.
Laboratory exercise 2 - two competing models.
Design two schemas for the capstone's order processing system. Suggested contrast: a classic normalised model, against one denormalising order totals and customer rollups for reporting.
Implement both with named constraints. Use an identity column in one and a shared sequence in the other, and note the difference when two tables must draw from one number space. Make at least one constraint deferrable and demonstrate why.
Write the representative queries against both: place an order, read an order with its lines, monthly revenue by product with a running total, and the top three products per customer using an analytic function. Add a hierarchical query over a product category tree, written both with CONNECT BY and with a recursive WITH.
Build a materialized view for the monthly rollup and demonstrate both refresh modes.
Deliverable: both schemas, all queries in both forms where applicable, a test that attempts to violate each constraint and shows the engine refusing, the deferrable demonstration, and a page arguing for one model - including what the materialized view costs on write.
-- ------------------------------------------------------------------
-- Deferrable constraints: checked at COMMIT, not at each statement.
-- ------------------------------------------------------------------
CREATE TABLE ord_owner.orders (
order_id NUMBER(12) GENERATED ALWAYS AS IDENTITY
CONSTRAINT pk_orders PRIMARY KEY,
customer_id NUMBER(12) NOT NULL,
ordered_at TIMESTAMP(3) WITH TIME ZONE DEFAULT SYSTIMESTAMP NOT NULL,
status VARCHAR2(20 CHAR) DEFAULT 'pending' NOT NULL,
total_amount NUMBER(19,4) DEFAULT 0 NOT NULL,
CONSTRAINT fk_orders_customer FOREIGN KEY (customer_id)
REFERENCES ord_owner.customer (customer_id)
DEFERRABLE INITIALLY IMMEDIATE,
CONSTRAINT ck_orders_total CHECK (total_amount >= 0)
) TABLESPACE app_data;
-- Defer it for one transaction, to allow a temporarily inconsistent
-- intermediate state - swapping two unique values, say:
SET CONSTRAINT fk_orders_customer DEFERRED;
-- ... the inconsistent steps ...
COMMIT; -- checked HERE. A violation rolls back the whole transaction.
-- Adding a constraint to a huge table without a long outage:
ALTER TABLE ord_owner.orders ADD CONSTRAINT ck_status_valid
CHECK (status IN ('pending','paid','shipped','cancelled'))
ENABLE NOVALIDATE;
-- Enforces NEW rows immediately; does not scan the existing ones.
-- Validate later, when there is a window:
ALTER TABLE ord_owner.orders MODIFY CONSTRAINT ck_status_valid VALIDATE;
-- ------------------------------------------------------------------
-- Sequences: and why identifiers have gaps.
-- ------------------------------------------------------------------
CREATE SEQUENCE ord_owner.document_seq
START WITH 1 INCREMENT BY 1 CACHE 100 NOCYCLE;
-- ^^^^^^^^^ 100 values pre-allocated in
-- memory. A shutdown or a RAC node failure loses the unused ones.
-- Sequences HAVE GAPS, by design, and code that assumes contiguous
-- identifiers is wrong. Use NOCACHE only if you truly cannot tolerate
-- them, and accept the serialisation cost.
-- ------------------------------------------------------------------
-- Analytic functions.
-- ------------------------------------------------------------------
SELECT
p.product_id, p.name,
TRUNC(o.ordered_at, 'MM') AS month,
SUM(l.quantity * l.unit_price) AS revenue,
-- A running total across months, without collapsing the rows:
SUM(SUM(l.quantity * l.unit_price)) OVER (
PARTITION BY p.product_id ORDER BY TRUNC(o.ordered_at, 'MM')
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS running_revenue,
-- Share of the month, which Oracle gives you directly:
RATIO_TO_REPORT(SUM(l.quantity * l.unit_price)) OVER (
PARTITION BY TRUNC(o.ordered_at, 'MM')
) AS share_of_month,
LAG(SUM(l.quantity * l.unit_price)) OVER (
PARTITION BY p.product_id ORDER BY TRUNC(o.ordered_at, 'MM')
) AS previous_month
FROM ord_owner.orders o
JOIN ord_owner.order_line l ON l.order_id = o.order_id
JOIN ord_owner.product p ON p.product_id = l.product_id
GROUP BY p.product_id, p.name, TRUNC(o.ordered_at, 'MM');
-- Top three products per customer. FETCH FIRST ... WITH TIES is 12c+;
-- before that this was a ROWNUM subquery, which is what you will find
-- in older code and is easy to get wrong.
SELECT * FROM (
SELECT c.customer_id, p.name,
SUM(l.quantity * l.unit_price) AS spend,
ROW_NUMBER() OVER (PARTITION BY c.customer_id
ORDER BY SUM(l.quantity * l.unit_price) DESC) AS rn
FROM ord_owner.customer c
JOIN ord_owner.orders o ON o.customer_id = c.customer_id
JOIN ord_owner.order_line l ON l.order_id = o.order_id
JOIN ord_owner.product p ON p.product_id = l.product_id
GROUP BY c.customer_id, p.name
) WHERE rn <= 3;
-- ------------------------------------------------------------------
-- Hierarchies: the Oracle way and the portable way.
-- ------------------------------------------------------------------
-- CONNECT BY - concise, Oracle-only:
SELECT LEVEL,
LPAD(' ', (LEVEL - 1) * 2) || name AS tree,
SYS_CONNECT_BY_PATH(name, ' > ') AS path,
CONNECT_BY_ISLEAF AS is_leaf
FROM ord_owner.category
START WITH parent_id IS NULL
CONNECT BY PRIOR category_id = parent_id
ORDER SIBLINGS BY name;
-- Recursive WITH - standard, portable, and with better cycle handling:
WITH tree (category_id, name, parent_id, depth, path) AS (
SELECT category_id, name, parent_id, 1, CAST(name AS VARCHAR2(4000))
FROM ord_owner.category WHERE parent_id IS NULL
UNION ALL
SELECT c.category_id, c.name, c.parent_id, t.depth + 1,
t.path || ' > ' || c.name
FROM ord_owner.category c JOIN tree t ON c.parent_id = t.category_id
)
CYCLE category_id SET is_cycle TO 'Y' DEFAULT 'N'
SELECT depth, path, is_cycle FROM tree ORDER BY path;
-- ------------------------------------------------------------------
-- Materialized views.
-- ------------------------------------------------------------------
CREATE MATERIALIZED VIEW LOG ON ord_owner.order_line
WITH ROWID, SEQUENCE (order_id, product_id, quantity, unit_price)
INCLUDING NEW VALUES; -- required for FAST refresh
CREATE MATERIALIZED VIEW ord_owner.mv_monthly_revenue
TABLESPACE app_data
BUILD IMMEDIATE
REFRESH FAST ON COMMIT -- every commit maintains it: correct,
-- and it slows every write. ON DEMAND
-- with a schedule is usually better.
ENABLE QUERY REWRITE -- the optimiser may silently use this
AS -- instead of the base tables
SELECT TRUNC(o.ordered_at, 'MM') AS month, l.product_id,
SUM(l.quantity * l.unit_price) AS revenue, COUNT(*) AS line_count
FROM ord_owner.orders o JOIN ord_owner.order_line l ON l.order_id = o.order_id
GROUP BY TRUNC(o.ordered_at, 'MM'), l.product_id;
EXEC DBMS_MVIEW.REFRESH('ORD_OWNER.MV_MONTHLY_REVENUE', 'C'); -- complete
SELECT mview_name, last_refresh_type, last_refresh_date, staleness
FROM user_mviews;
Discussion
No questions on this topic yet. Sign in to ask the first one.