Introduction & Advanced SQL
Introduction & Advanced SQL
SQL:
Introduction & Advanced
Chapters 7 & 8 — Complete Reference
Introduction
to SQL
SQL Overview
DDL
DML
DCL
Single-Table Queries
Views
Referential Integrity
RDBMS Defined
A Database Management System that manages data as a collection of tables in which all relationships
are represented by common values in related tables. There are no pointers or physical links — only
logical connections via shared key values.
1970 E.F. Codd publishes his landmark paper at IBM introducing the relational database concept.
1974–79 IBM Research Lab builds System R using SEQUEL (later renamed SQL).
1979 Oracle Corporation markets the first commercially available SQL relational database.
1986 ANSI releases the first official SQL standard, also adopted by ISO.
1989 SQL-89: Major update adding referential integrity and enhanced integrity constraints.
1992 SQL-92 (SQL2): New data types, schema manipulation, new JOIN types, improved error handling.
1999 SQL:1999 (SQL3): Object-relational features, triggers, stored procedures (PSM), recursive
queries.
2003 SQL:2003: XML support, BIGINT, MULTISET, MERGE statement, identity columns, window
functions.
Current SQL is supported by all major database vendors; the core ANSI standard is universally recognized.
Reduced training costs Personnel trained on one RDBMS can transfer skills to another.
Application portability Apps can move between environments (e.g., Oracle → PostgreSQL).
Application longevity SQL-based apps remain viable longer — the standard is stable.
Reduced vendor dependence Organisations are not locked into a single vendor's language.
Cross-system communication Systems from different vendors can exchange data using SQL.
Key Components
Catalog: The highest-level unit. A named collection of schemas constituting the complete description
of a database (e.g., DEV_C vs. PROD_C).
Schema: A named container within a catalog grouping related objects — base tables, views,
constraints, domains, character sets — all belonging to a particular user or application context.
DDL Data Definition Language Defines/modifies database CREATE TABLE, ALTER TABLE,
structure DROP TABLE, CREATE VIEW
DML Data Manipulation Language Maintains and queries a SELECT, INSERT, UPDATE,
database DELETE
DCL Data Control Language Controls database access GRANT, REVOKE, COMMIT,
and security ROLLBACK
CHAR(n) String Fixed-length string. Padded with spaces to n chars. Use for state codes
(CHAR(2)).
VARCHAR(n) String Variable-length string up to n chars. Ideal for names and addresses.
BLOB Binary Binary Large Object. Variable length. Used for images, audio, documents.
DECIMAL(p,s) Number Exact number with user-defined precision and scale. DECIMAL(6,2) → 1234.56.
BOOLEAN Boolean Stores TRUE, FALSE, or UNKNOWN (arising from NULL comparisons).
1 Identify data types Choose VARCHAR, INTEGER, DECIMAL, DATE, etc. for every column.
3 Unique columns Use UNIQUE for candidate keys that must not contain duplicates.
4 PK–FK relationships Document which columns link related tables for referential integrity.
6 Domain constraints Use CHECK to limit valid values (e.g., PRODUCT_FINISH IN ('Cherry', ...)).
7 Create table & indexes Execute CREATE TABLE; create indexes separately for performance.
{column_definition [table_constraint]} , . . .
);
-- column_definition:
-- table_constraint:
CUSTOMER_T (1) ■■■■ (M) ORDER_T One customer places many orders
ORDER_T (1) ■■■■ (M) ORDER_LINE_T One order contains many line items
PRODUCT_T (1) ■■■■ (M) ORDER_LINE_T One product appears on many order lines
CUSTOMER_ADDRESS VARCHAR2(30),
CITY VARCHAR2(20),
STATE VARCHAR2(2),
POSTAL_CODE VARCHAR2(9),
);
);
PRODUCT_DESCRIPTION VARCHAR2(50),
PRODUCT_FINISH VARCHAR2(20)
CHECK (PRODUCT_FINISH IN
STANDARD_PRICE DECIMAL(6,2),
PRODUCT_LINE_ID INTEGER,
);
ORDERED_QUANTITY NUMBER(11,0),
);
Composite Primary Key Rule: When a PK spans multiple columns it must be declared as a table-level
constraint. Both component columns must be NOT NULL.
...
);
DROP TABLE is destructive — it removes the table definition and all data. Most RDBMSs require child
tables to be dropped first, or CASCADE DROP to be specified.
Assertions can reference data across multiple tables — unlike column or table CHECK constraints. Not all
RDBMS products support assertions (Oracle uses triggers instead).
RESTRICT Safest. Parent row cannot be deleted/updated if child rows reference it. Operation is blocked.
CASCADE Change is propagated. If CUSTOMER_ID is updated, all matching FKs in ORDER_T are
updated too.
SET NULL Parent deleted/updated → FK in child rows set to NULL. Child row preserved but link severed.
SET DEFAULT Parent deleted/updated → child FK values set to a predefined default value.
INSERT INTO CUSTOMER_T VALUES (001, 'Contemporary Casuals', '1355 S. Himes Blvd.',
'Gainesville', 'FL', 32601);
DELETE is a DML operation that can be rolled back. Without WHERE, all rows are deleted but the table
remains.
UPDATE PRODUCT_T
WHERE PRODUCT_ID = 7;
Without WHERE all rows are updated. UPDATE is subject to all CHECK constraints.
GROUP BY Groups rows sharing the same values for aggregate computation. 3rd
HAVING Filters groups created by GROUP BY (like WHERE but for groups). 4th
Processing order: FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY. You cannot
reference a SELECT alias in a WHERE clause because WHERE is processed before SELECT.
FROM PRODUCT_V
Function Description
Cannot mix aggregated and non-aggregated columns in SELECT unless non-aggregated columns are in
GROUP BY.
FROM PRODUCT_V
Operator precedence: NOT → AND → OR. Parentheses override. Without parentheses, SQL evaluates AND
before OR, producing wrong results.
FROM CUSTOMER_V
IN replaces multiple OR conditions and can be more efficiently executed by the query optimizer.
FROM CUSTOMER_V
GROUP BY CUSTOMER_STATE;
GROUP BY collapses rows sharing the same grouping-column value into a single output row. Scalar
aggregate → one row total; vector aggregate → one row per group.
FROM CUSTOMER_V
GROUP BY CUSTOMER_STATE
Best Practice Always use WHERE when possible Only when filtering on aggregate results
Base Table Actual physical table containing raw data on disk. Yes — physical As needed by
DML
Dynamic View Virtual table defined by a stored SELECT. No data No — virtual Always current
stored — re-executes SELECT on every query.
Materialized View Physical copy (snapshot) stored on disk. Must be Yes — snapshot Periodically
refreshed periodically. refreshed
-- WITH CHECK OPTION prevents inserting products priced ≤ $300 via this view
FROM PRODUCT_T
Performance Cannot use indexes with leading % Optimizer-friendly; can use indexes
Use Case Partial text search (names ending in Exact match: STATE IN ('CA','TX')
"Corp")
Best Practice Avoid leading % on high-volume tables Preferred over multiple OR conditions
Advanced
SQL
Multi-Table Joins
Subqueries
Transactions
Triggers
Stored Procedures
Correlated Subqueries
Union Queries
CASE Expressions
Equi-Join Join condition based on equality (PK = FK). Common columns appear redundantly in the
result.
Natural Join Equi-join where one duplicate common column is eliminated from the result.
Outer Join Includes rows even when no match exists. Three variants: LEFT, RIGHT, FULL OUTER JOIN.
Union Join Includes all columns from each table and all rows. Does not match rows — fills NULLs
elsewhere.
Matching Equality on common Equality on common All left rows + All rows, no
cols cols matching right matching
Performance Good with indexes Good with indexes Slightly higher cost Very high (full cross)
Best Use Standard PK–FK Clean reports Parents with/without Rarely used in
lookups children practice
* = No orders placed — will appear only in OUTER JOIN results with NULL ORDER_ID.
1001 10/21/2006 1
1002 10/21/2006 8
1003 10/22/2006 15
1004 10/22/2006 5
1005 10/24/2006 3
1006 10/24/2006 2
1007 10/27/2006 11
1008 10/30/2006 12
1009 11/5/2006 4
1010 11/5/2006 1
-- INNER JOIN via NATURAL JOIN — only matched rows returned (10 rows)
ON CUSTOMER_T.CUSTOMER_ID = ORDER_T.CUSTOMER_ID;
10 of 15 customers have orders → exactly 10 result rows (Customer 1 appears twice for orders 1001 and
1010). The duplicate CUSTOMER_ID from ORDER_T is suppressed in the output.
FROM CUSTOMER_T
ON CUSTOMER_T.CUSTOMER_ID = ORDER_T.CUSTOMER_ID;
5 Impressions 1004
16 rows total. Customers with NULL ORDER_ID have never placed an order.
SELECT
ORDERED_QUANTITY,
PRODUCT_DESCRIPTION, STANDARD_PRICE,
FROM
WHERE
Rule: For N tables joined, you need N-1 join conditions. Missing one produces a Cartesian product.
8.6 Subqueries
A subquery (nested query or inner query) is a SELECT statement embedded inside another SQL
statement. Subqueries provide an alternative to joins for certain multi-table operations.
Dependency Does NOT reference outer query References data from the outer query
Execution Executes ONCE for the entire query Executes ONCE per row of the outer
query
Operators IN, NOT IN, =, >, <, ANY, ALL EXISTS, NOT EXISTS, IN with outer ref
Best Use When inner result is independent When must check against each outer row
SELECT CUSTOMER_NAME
FROM CUSTOMER_T
WHERE CUSTOMER_ID IN
FROM ORDER_T);
Step 1: Inner query runs once and produces {1,2,3,4,5,8,11,12,15}. Step 2: Outer query returns names for
customers in that set. Result: 9 rows.
WHERE EXISTS
(SELECT *
FROM PRODUCT_T
EXISTS returns TRUE if the subquery produces at least one row. It short-circuits as soon as one match is
found — more efficient than IN for existence checks. The subquery re-executes for every outer row.
FROM
PRODUCT_T
UNION
ORDER BY ORDERED_QUANTITY;
Same column count Both SELECT statements must produce the same number of columns.
Column names Result column names come from the first SELECT statement.
ORDER BY Appears only once, after the last SELECT; applies to the entire combined result.
CASE expression
END
CASE
ELSE 'Unpriced'
END AS PRICE_TIER
NULLIF(a,b) returns NULL if a=b, else returns a. COALESCE(a,b,c…) returns the first non-NULL value —
powerful for null handling.
BEGIN TRANSACTION;
END TRANSACTION;
DBA_CONSTRAINTS All constraints: PK, FK, UNIQUE, CHECK, NOT NULL — names, types, tables
DBA_USERS All database users: account name, creation date, default tablespace
SYSCOLUMNS Table and column definitions — data types, lengths, nullability, defaults
• Functions: Accept input parameters, perform computation, return a single value. Usable inline in
SQL expressions.
• Stored Procedures: Perform a set of operations, do NOT return a value via RETURN (may use
OUT parameters). Called via CALL or EXECUTE.
8.14.2 Triggers
Trigger Definition
A stored routine that automatically executes in response to a specific database event — INSERT,
UPDATE, or DELETE on a specified table. Unlike stored procedures (called explicitly), triggers are
event-driven — they fire implicitly when the triggering event occurs.
Return Value Can return via OUT params or result sets No return value; performs side-effect
action
Parameters Accept IN, OUT, INOUT parameters Access NEW and OLD virtual rows
Performance Predictable — called only when needed Adds overhead to every triggering DML
Best Use Case Complex logic, batch, multi-step Audit logging, cascading rules, derived
transactions columns
[WHEN (search_condition)]
Clause Explanation
BEFORE / AFTER Fires before/after the DML. BEFORE can modify data being inserted/updated.
INSTEAD OF Replaces the DML entirely — used mainly with non-updatable views.
FOR EACH ROW Fires once per affected row (row-level). FOR EACH STATEMENT fires once per DML.
WHEN Optional filter — trigger body executes only when condition is true.
NEW / OLD Virtual rows. NEW = values being inserted or new update values. OLD = values before
change.
[NO SQL | CONTAINS SQL | READS SQL DATA | MODIFIES SQL DATA]
routine_body;
Embedded Hard-coded SQL inside a host Type-safe, precompiled, Inflexible — SQL cannot
SQL language (C, Java, COBOL). good performance. change at runtime without
Pre-processed by a precompiler. recompiling.
Fixed at compile time.
Dynamic SQL SQL constructed and compiled at Highly flexible — query Performance overhead;
runtime based on user input or structure can vary based risk of SQL injection if
application state. on input. input not sanitised.
User-Defined Types (UDT) SQL:1999 Custom data types as subclasses or complex object types. Enables
object-relational capabilities.
BIGINT SQL:2003 64-bit integer for very large numbers (up to ~9.2×10¹■).
XML SQL:2003 Native XML data type with XQuery support for XML document
navigation.
CREATE TABLE LIKE SQL:2003 Creates a new table with the same structure as an existing table.
MERGE Statement SQL:2003 Combines INSERT and UPDATE into one atomic "upsert" operation.
SQL/PSM SQL:1999 Persistent Stored Modules — complete procedural extension with IF,
LOOP, WHILE, FOR.
Object-Relational SQL:1999 Typed tables, reference types, inheritance, row types, and array types.
Vendor implementations: Oracle → PL/SQL; Microsoft SQL Server → T-SQL; PostgreSQL → PL/pgSQL,
PL/Python, PL/Perl.
Equi-Join vs. Natural Join vs. Outer Section 8.1.2 Equi = equality match; Natural = no duplicate cols; Outer
Join = includes unmatched rows.
Correlated vs. Non-Correlated Section 8.6.2 Non-correlated runs once (efficient); correlated runs per
Subqueries row (powerful for EXISTS).
WHERE vs. HAVING Section 7.6.8 WHERE filters rows before grouping; HAVING filters
groups after GROUP BY.
Base vs. Dynamic vs. Materialized Section 7.7.1 Base stores data; Dynamic is always current virtual;
Views Materialized is OLAP snapshot.
Stored Procedures vs. Triggers Section 8.14.3 Procedures called explicitly; triggers fire automatically on
DML events.
LIKE vs. IN Operators Section 7.7.5 LIKE does wildcard pattern matching; IN tests exact
membership in a list.
ORDER_T
ORDER_ID NUMBER(11,0) NOT NULL [PK]
ORDER_DATE DATE DEFAULT SYSDATE
CUSTOMER_ID NUMBER(11,0) [FK → CUSTOMER_T]
PRODUCT_T
PRODUCT_ID INTEGER NOT NULL [PK]
PRODUCT_DESCRIPTION VARCHAR2(50)
PRODUCT_FINISH VARCHAR2(20) CHECK IN (Cherry, Natural Ash, White Ash, Red Oak,
Natural Oak, Walnut)
STANDARD_PRICE DECIMAL(6,2), PRODUCT_LINE_ID INTEGER
ORDER_LINE_T
ORDER_ID NUMBER(11,0) NOT NULL [PK, FK → ORDER_T]
PRODUCT_ID NUMBER(11,0) NOT NULL [PK, FK → PRODUCT_T]
ORDERED_QUANTITY NUMBER(11,0)
Composite PK: (ORDER_ID, PRODUCT_ID)