1Z0-071 — Oracle Database SQL Cheat Sheet

Cheat sheet: Oracle Database SQL 1Z0-071 reference covering query syntax, joins, functions, subqueries, set operators, DML, DDL, and exam traps.

Independent quick reference for candidates preparing for Oracle Oracle Database SQL (1Z0-071). Use it to review high-yield syntax rules, common exam traps, and decision points for real Oracle SQL questions.

Use the tables for a quick pre-exam check. Expand a topic’s notes for explanations, examples, and additional distinctions.

Scope and study context

The exam rewards precision. Many missed questions are not caused by unfamiliar SQL, but by small details: NULL behavior, alias scope, join output, aggregate rules, datatype conversion, transaction control, and Oracle-specific syntax.

Core SELECT Processing

Logical Query Order vs Written Order

Written clause orderLogical evaluation ideaExam points
SELECT5Column expressions, aliases, aggregate output
FROM1Tables, views, joins, inline views
WHERE2Row filtering before grouping
GROUP BY3Creates groups for aggregate evaluation
HAVING4Group filtering after aggregation
ORDER BY6Final sort; can use select-list aliases
Row limiting7Applied after ordering when used correctly
Notes and examples
SELECT department_id, AVG(salary) AS avg_sal
FROM employees
WHERE salary IS NOT NULL
GROUP BY department_id
HAVING AVG(salary) > 5000
ORDER BY avg_sal DESC;

Alias Rules

LocationCan use select-list alias?Notes
ORDER BYYesCommon exam-safe use
WHERENoWHERE is evaluated before SELECT alias creation
GROUP BYUsually avoidUse the original expression for exam-style Oracle SQL
HAVINGUsually avoidUse the aggregate expression
Same select listNoAn alias is not normally reusable by another expression in the same select list
-- Correct
SELECT salary * 12 AS annual_salary
FROM employees
ORDER BY annual_salary;

-- Avoid / exam trap
SELECT salary * 12 AS annual_salary
FROM employees
WHERE annual_salary > 100000;

Logical clause order

Memorize the logical processing order, not just the written syntax.

Written orderLogical roleCandidate reminder
SELECTChoose expressions to displayAliases are created here
FROMIdentify source tables/viewsJoins are resolved here
WHEREFilter individual rowsCannot use aggregate functions directly here
GROUP BYForm groupsEvery non-aggregate selected expression must be grouped
HAVINGFilter groupsUse for aggregate conditions
ORDER BYSort final resultCan use select-list aliases

Logical evaluation is commonly understood as: FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY.

Alias rules that often appear in exam questions

LocationCan use select-list alias?Example issue
ORDER BYUsually yesORDER BY annual_salary works if alias is in select list
WHERENoAlias does not exist yet logically
GROUP BYDo not rely on it for 1Z0-071-style questionsGroup by the expression or column
HAVINGDo not rely on select aliasUse the aggregate expression

If a question gives a calculated alias such as salary * 12 annual_salary, expect a trap where the alias is reused too early.

Filtering, Sorting, and Operators

Comparison and Null Logic

PredicateMeaningTrap
=, <>, !=, <, >, <=, >=Standard comparisonsComparisons with NULL return unknown, not true
BETWEEN a AND bInclusive rangeEquivalent to >= a AND <= b
IN (...)Matches any listed valueIN with NULL does not match null rows
LIKEPattern matching% = any length, _ = one character
IS NULLTests nullUse instead of = NULL
IS NOT NULLTests non-nullUse instead of <> NULL
ANDBoth conditionsEvaluated before OR
OREither conditionUse parentheses to control intent
NOTNegates conditionWatch NOT IN with nulls
Notes and examples
SELECT last_name
FROM employees
WHERE commission_pct IS NULL;

SELECT last_name
FROM employees
WHERE last_name LIKE 'Smi_h%' ESCAPE '\';

Boolean Precedence

Higher to lowerExample
Comparisons and pattern testssalary > 5000, job_id LIKE 'SA%'
NOTNOT department_id = 10
ANDa AND b
ORa OR b

Exam trap:

-- Means: department_id = 10 OR (department_id = 20 AND salary > 5000)
WHERE department_id = 10 OR department_id = 20 AND salary > 5000

-- Clearer:
WHERE (department_id = 10 OR department_id = 20)
  AND salary > 5000

Sorting Rules

SyntaxResult
ORDER BY col ASCAscending; default
ORDER BY col DESCDescending
ORDER BY 2Sort by second select-list expression
ORDER BY aliasSort by select-list alias
NULLS FIRST / NULLS LASTExplicit null placement
SELECT employee_id, last_name, salary * 12 AS annual_pay
FROM employees
ORDER BY annual_pay DESC NULLS LAST;

Single-Row Functions

Character Functions

FunctionPurposeExample result idea
LOWER(char)LowercaseLOWER('SQL') → sql
UPPER(char)UppercaseUPPER('sql') → SQL
INITCAP(char)Initial capitalsINITCAP('oracle sql')
CONCAT(a,b)Concatenate two valuesOnly two arguments
`ab`
SUBSTR(char,start,len)SubstringPositions start at 1
LENGTH(char)Character lengthCounts characters
INSTR(char,search)Position of substring0 if not found
LPAD / RPADPad left/rightFormatting output
TRIMRemove leading/trailing charsSpaces by default
REPLACEReplace substringCase-sensitive
Notes and examples
SELECT UPPER(last_name),
       SUBSTR(phone_number, 1, 3),
       first_name || ' ' || last_name AS full_name
FROM employees;

Number Functions

FunctionPurposeKey distinction
ROUND(n, d)Rounds to d decimalsMay increase value
TRUNC(n, d)Truncates to d decimalsDoes not round
MOD(n, m)RemainderUseful for divisibility
SELECT ROUND(45.926, 2), TRUNC(45.926, 2), MOD(10, 3)
FROM dual;

Date Functions and Date Arithmetic

ExpressionMeaningExam point
SYSDATECurrent database server date/timeIncludes time component
CURRENT_DATECurrent date in session time zoneDifferent from SYSDATE in some environments
date + nAdd n daysn may be fractional
date - nSubtract n days
date1 - date2Difference in daysNumeric result
MONTHS_BETWEEN(d1,d2)Months between datesMay return fractional months
ADD_MONTHS(d,n)Add monthsHandles month boundaries
NEXT_DAY(d,'MONDAY')Next named weekdayLanguage-sensitive
LAST_DAY(d)Last day of month
ROUND(date,'MONTH')Round dateDate granularity
TRUNC(date,'YEAR')Truncate dateCommon for grouping
SELECT hire_date,
       hire_date + 7 AS one_week_later,
       MONTHS_BETWEEN(SYSDATE, hire_date) AS months_employed
FROM employees;

Single-row functions

Single-row functions return one result per input row. They can be nested, used in SELECT, WHERE, and ORDER BY, and often appear in conversion or date questions.

Character functions

FunctionPurposeExample result idea
LOWER, UPPER, INITCAPChange caseUseful for case-insensitive comparisons
CONCAT(a,b)Concatenate two valuesSimilar to `a
SUBSTR(char, start, length)Extract part of a stringOracle positions are character-based
LENGTH(char)Count charactersSpaces count
INSTR(char, search)Find positionReturns position of search string
LPAD, RPADPad to a lengthFormatting output
TRIMRemove leading/trailing charactersDefault trims spaces
REPLACEReplace matching textCharacter substitution

Candidate trap: CONCAT takes two arguments, while || can chain multiple values.

Number functions

FunctionPurposeTrap
ROUND(number, n)Round to n decimal placesNegative n rounds left of decimal
TRUNC(number, n)Truncate to n decimal placesDoes not round
MOD(m, n)RemainderUseful for divisibility checks

Date functions

Oracle DATE values include date and time components.

FunctionPurposeReview point
SYSDATECurrent database server date/timeIncludes time
MONTHS_BETWEEN(d1, d2)Months between datesCan return fractional months
ADD_MONTHS(date, n)Add monthsHandles month boundaries
NEXT_DAY(date, char)Next named weekdayDepends on date language settings
LAST_DAY(date)Last day of monthHigh-yield date function
ROUND(date, fmt)Round date to format unitFormat matters
TRUNC(date, fmt)Truncate date to format unitCommon for removing time portion
EXTRACT(part FROM date)Extract year, month, day, etc.Syntax differs from normal functions

Conversion functions and format models

FunctionConvertsTypical use
TO_CHAR(date, fmt)Date to formatted textDisplay dates
TO_CHAR(number, fmt)Number to formatted textCurrency, decimal display
TO_DATE(char, fmt)Text to dateAvoid implicit date conversion
TO_NUMBER(char, fmt)Text to numberControlled numeric conversion

High-yield format elements include YYYY, YY, RR, MM, MON, MONTH, DD, DAY, DY, HH, HH24, MI, SS, and numeric elements such as 9, 0, comma, decimal, and currency symbols.

Candidate trap: implicit conversion may work in one environment and fail in another because date and numeric formats can depend on session settings. For exam questions, explicit conversion with the correct format model is safer.

Conditional expressions

ExpressionUseNotes
CASEStandard conditional logicSupports searched and simple forms
DECODEOracle-specific conditional comparisonOften shorter but less flexible
NVLReplace NULLTwo arguments
COALESCEFirst non-nullShort-circuits conceptually
NULLIFReturn null when equalUseful for avoiding divide-by-zero patterns
NVL2Null-dependent branchingThree arguments

Conversion and Conditional Expressions

Conversion Functions

FunctionPurposeExample
TO_CHAR(date, fmt)Date to textTO_CHAR(hire_date,'YYYY-MM-DD')
TO_CHAR(number, fmt)Number to textTO_CHAR(salary,'999,999')
TO_DATE(char, fmt)Text to dateTO_DATE('2026-06-18','YYYY-MM-DD')
TO_NUMBER(char, fmt)Text to numberTO_NUMBER('1,200','9,999')
Notes and examples

Common format model elements:

ElementMeaning
YYYYFour-digit year
YYTwo-digit year
RRTwo-digit year with Oracle RR century logic
MMMonth number
MONAbbreviated month name
MONTHFull month name
DDDay of month
DYAbbreviated day name
DAYFull day name
HH24Hour 0-23
MIMinute
SSSecond
AM / PMMeridian indicator
SELECT TO_CHAR(SYSDATE, 'YYYY-MM-DD HH24:MI:SS')
FROM dual;

Null and Conditional Functions

FunctionReturnsHigh-yield distinction
NVL(expr1, expr2)expr2 if expr1 is nullOracle-specific; data types must be compatible
NVL2(expr1, expr2, expr3)expr2 if not null, else expr3Reverses common intuition
NULLIF(expr1, expr2)NULL if equal, else expr1Useful to avoid divide-by-zero logic
COALESCE(a,b,c,...)First non-null expressionANSI-style; multiple expressions
CASEConditional resultSearched or simple form
DECODEOracle conditional comparisonOlder Oracle-specific style
SELECT last_name,
       NVL(commission_pct, 0) AS commission_pct,
       CASE
         WHEN salary >= 10000 THEN 'HIGH'
         WHEN salary >= 5000  THEN 'MID'
         ELSE 'LOW'
       END AS salary_band
FROM employees;

Aggregate Functions and Grouping

Aggregate Function Behavior

FunctionCounts nulls?Notes
COUNT(*)YesCounts rows
COUNT(expr)NoCounts non-null expression values
COUNT(DISTINCT expr)NoCounts distinct non-null values
SUM(expr)NoNumeric/date interval-style use depends on expression
AVG(expr)NoNulls excluded from denominator
MIN(expr)NoWorks on comparable data
MAX(expr)NoWorks on comparable data
Notes and examples
SELECT department_id,
       COUNT(*) AS row_count,
       COUNT(commission_pct) AS commission_count,
       AVG(salary) AS avg_salary
FROM employees
GROUP BY department_id;

GROUP BY Rules

RuleExample / trap
Every non-aggregate select expression must be groupedSELECT department_id, job_id, AVG(salary) ... GROUP BY department_id, job_id
WHERE filters rows before groupingCannot use aggregate functions in WHERE
HAVING filters groups after groupingUse HAVING AVG(salary) > 5000
Grouping by expression requires the expressionGROUP BY TRUNC(hire_date,'YEAR')
Nulls form a groupNull department values group together
-- Correct
SELECT department_id, AVG(salary)
FROM employees
WHERE salary > 0
GROUP BY department_id
HAVING AVG(salary) > 5000;

-- Incorrect: aggregate in WHERE
SELECT department_id
FROM employees
WHERE AVG(salary) > 5000
GROUP BY department_id;

Joins

Join Type Selection

NeedUseNotes
Matching rows in both tablesINNER JOINDefault when JOIN without outer keyword
All rows from left table plus matchesLEFT OUTER JOINUnmatched right columns become null
All rows from right table plus matchesRIGHT OUTER JOINLess common; can often rewrite as left join
All rows from both sidesFULL OUTER JOINUnmatched columns become null
Join a table to itselfSelf joinRequires aliases
Join on non-equality conditionNon-equijoinExample: ranges
All combinationsCross joinCartesian product; often accidental
Join same-named columns automaticallyNATURAL JOINRisky: uses all same-name columns
Join same-named selected columnsJOIN ... USING (col)Cannot qualify col with table alias in select list
Notes and examples
SELECT e.last_name, d.department_name
FROM employees e
JOIN departments d
  ON e.department_id = d.department_id;

Outer Join Filter Trap

-- Preserves departments with no employees
SELECT d.department_name, e.last_name
FROM departments d
LEFT OUTER JOIN employees e
  ON d.department_id = e.department_id;

-- Trap: WHERE condition on right table can turn it into an effective inner join
SELECT d.department_name, e.last_name
FROM departments d
LEFT OUTER JOIN employees e
  ON d.department_id = e.department_id
WHERE e.job_id = 'SA_REP';

-- Safer when the filter belongs to the matching condition
SELECT d.department_name, e.last_name
FROM departments d
LEFT OUTER JOIN employees e
  ON d.department_id = e.department_id
 AND e.job_id = 'SA_REP';

USING and NATURAL JOIN Traps

-- With USING, do not qualify the joined column in the select list
SELECT department_id, e.last_name, d.department_name
FROM employees e
JOIN departments d USING (department_id);

-- NATURAL JOIN joins on every column with the same name in both tables
SELECT employee_id, department_name
FROM employees
NATURAL JOIN departments;
TrapWhy it matters
Missing join conditionProduces Cartesian product
NATURAL JOINNew same-name columns can silently change results
Qualifying a USING columnInvalid in common Oracle exam syntax
Filtering outer-joined table in WHEREMay remove null-extended rows

Join types

Join typePurposeTrap
Inner joinRows with matching valuesNonmatching rows disappear
Left outer joinAll rows from left table plus matchesPredicate placement can turn it into an inner join
Right outer joinAll rows from right table plus matchesSame predicate trap
Full outer joinAll matching and nonmatching rows from both sidesNulls appear for missing side
Self-joinTable joined to itselfRequires aliases
Cross joinCartesian productUsually wrong unless intentional
Natural joinJoins same-name columns automaticallyDangerous if multiple same-name columns exist

ON, USING, and natural joins

SyntaxBest useWatch for
JOIN ... ON t1.col = t2.colMost explicit and safestQualify columns clearly
JOIN ... USING (col)Same column name in both tablesThe joined column is referenced once
NATURAL JOINQuick join on all same-name columnsCan silently join on unintended columns

For exam safety, prefer reasoning with ON because it makes the join condition explicit.

Outer join predicate trap

A common missed question places an outer join in the FROM clause but then filters the optional table in the WHERE clause.

PatternEffect
Left join plus WHERE right_table.status = 'A'Often removes null-extended rows
Left join with condition in ON clausePreserves left rows while limiting matches
WHERE right_table.col IS NULL after left joinFinds unmatched rows

When reading an outer join question, ask: “Is this condition part of the match, or is it filtering the final result?”

Subqueries

Subquery Types

TypeReturnsOperators
Single-row subqueryOne row, one column=, >, <, >=, <=, <>
Multiple-row subqueryMany rows, one columnIN, ANY, ALL
Multiple-column subqueryMany columnsRow/value comparisons
Correlated subqueryReferences outer queryExecutes logically per outer row
Scalar subqueryOne valueCan appear where a single value is valid
Inline viewSubquery in FROMActs like a derived table
Notes and examples
-- Single-row subquery
SELECT last_name, salary
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);

-- Multiple-row subquery
SELECT last_name
FROM employees
WHERE department_id IN (
  SELECT department_id
  FROM departments
  WHERE location_id = 1700
);

ANY, ALL, IN, EXISTS

OperatorMeaningExam interpretation
INEqual to any value in listSame idea as = ANY
> ANYGreater than at least one returned valueGreater than the minimum is enough
> ALLGreater than every returned valueGreater than the maximum
< ANYLess than at least one returned valueLess than the maximum
< ALLLess than every returned valueLess than the minimum
EXISTSTrue if subquery returns at least one rowCommon with correlated subqueries
NOT EXISTSTrue if no row returnedSafer than NOT IN when nulls may appear
SELECT e.employee_id, e.last_name
FROM employees e
WHERE EXISTS (
  SELECT 1
  FROM dependents d
  WHERE d.employee_id = e.employee_id
);

Subquery Traps

SituationResult / issue
Single-row operator with multi-row subqueryError
NOT IN and subquery returns NULLOften returns no rows due to unknown comparison
Correlated subquery missing correlationMay become uncorrelated and change result
Subquery in ORDER BYMust be valid scalar expression
Subquery in FROMNeeds aliasing/column handling for readability
-- Safer anti-match pattern
SELECT d.department_id
FROM departments d
WHERE NOT EXISTS (
  SELECT 1
  FROM employees e
  WHERE e.department_id = d.department_id
);

Subquery types

TypeReturnsOperators
Single-row subqueryOne row, one column=, >, <, >=, <=, <>
Multiple-row subqueryMultiple rows, one columnIN, ANY, ALL
Multiple-column subqueryMultiple columnsTuple-style comparisons
Correlated subqueryDepends on outer query rowOften used with EXISTS
Scalar subqueryOne valueCan appear where a single expression is valid

Operator decision table

If the subquery can return…Use
Exactly one valueSingle-row operator such as =
Multiple valuesIN, ANY, ALL, or EXISTS
Existence only mattersEXISTS
Nonexistence mattersNOT EXISTS is often safer than NOT IN with nullable data

NOT IN and NULL

This is one of the highest-yield traps.

If a subquery used with NOT IN returns a NULL, the comparison can become unknown and return no rows that you expected. When nulls are possible, NOT EXISTS is often the safer logical pattern.

Correlated subquery reading method

For each row in the outer query:

  1. Substitute the outer row’s relevant value into the inner query.
  2. Evaluate the inner query.
  3. Decide whether the outer row qualifies.

This mental model helps with questions using department averages, maximum salary by group, or existence checks.

Set Operators

Set Operator Matrix

OperatorDuplicatesMeaning
UNIONRemoves duplicatesRows from either query
UNION ALLKeeps duplicatesRows from either query, faster conceptually because no duplicate elimination
INTERSECTRemoves duplicatesRows common to both queries
MINUSRemoves duplicatesRows in first query not in second
Notes and examples
SELECT department_id FROM employees
UNION
SELECT department_id FROM departments;

Set Operator Rules

RuleExam point
Same number of columnsEach query must return same column count
Compatible data type groupsCorresponding columns must be compatible
Column names come from first queryFinal output headings use first select
ORDER BY appears at the endNot inside each component query unless using a valid subquery
Use column position or first-query alias in final ORDER BYEspecially useful for expressions
Parentheses control evaluationAvoid relying on precedence assumptions
SELECT employee_id AS id, last_name AS name FROM employees
UNION ALL
SELECT department_id, department_name FROM departments
ORDER BY name;

Set operators

Set operators combine result sets from separate queries.

OperatorResult
UNIONCombined distinct rows
UNION ALLCombined rows including duplicates
INTERSECTRows common to both result sets
MINUSRows in first result set but not second

Set operator rules

RuleCandidate reminder
Same number of columnsEach query must return matching column count
Compatible datatype groupsCharacter with character, numeric with numeric, etc.
Column namesTaken from the first query
ORDER BYAppears at the end for the combined result
DuplicatesRemoved unless UNION ALL is used
Mixed operatorsUse parentheses to make intent clear

Do not assume each individual query can have its own final sort. The final ORDER BY applies to the combined result.

Row Limiting and Top-N Queries

TechniqueUseTrap
FETCH FIRST n ROWS ONLYModern row limiting after ORDER BYPut after ORDER BY
OFFSET n ROWSSkip rows before fetchOften paired with fetch
ROWNUMPseudocolumn assigned as rows are returnedROWNUM > 1 directly is a classic trap
Inline view with ROWNUMTop-N with older styleSort inside inline view, filter outside
SELECT employee_id, last_name, salary
FROM employees
ORDER BY salary DESC
FETCH FIRST 10 ROWS ONLY;

Older top-N pattern:

SELECT *
FROM (
  SELECT employee_id, last_name, salary
  FROM employees
  ORDER BY salary DESC
)
WHERE ROWNUM <= 10;

DML: INSERT, UPDATE, DELETE, MERGE

DML Command Reference

CommandPurposeKey syntax
INSERTAdd rowsVALUES or subquery
UPDATEChange rowsUse WHERE unless all rows should change
DELETERemove rowsUse WHERE unless all rows should be removed
MERGEInsert/update based on matchUseful for upsert-style logic
Notes and examples
INSERT INTO departments (department_id, department_name)
VALUES (280, 'Research');

INSERT INTO departments (department_id, department_name)
SELECT 281, 'Analytics'
FROM dual;

UPDATE employees
SET salary = salary * 1.10
WHERE department_id = 60;

DELETE FROM employees
WHERE employee_id = 999;

MERGE Pattern

MERGE INTO bonuses b
USING employees e
   ON (b.employee_id = e.employee_id)
WHEN MATCHED THEN
  UPDATE SET b.salary = e.salary
WHEN NOT MATCHED THEN
  INSERT (employee_id, salary)
  VALUES (e.employee_id, e.salary);

Transaction Control

StatementEffect
COMMITMakes current transaction changes permanent
ROLLBACKUndoes uncommitted changes
SAVEPOINT nameMarks a point for partial rollback
ROLLBACK TO nameRolls back to savepoint
DDL statementCauses implicit commit behavior in Oracle
SAVEPOINT before_raise;

UPDATE employees
SET salary = salary * 1.05
WHERE department_id = 80;

ROLLBACK TO before_raise;
COMMIT;

DML statements

StatementPurposeExam focus
INSERTAdd rowsColumn order, default values, subquery inserts
UPDATEModify rowsMissing WHERE updates all qualifying rows
DELETERemove rowsMissing WHERE deletes all qualifying rows
MERGEInsert/update based on match logicUnderstand match vs not-match behavior if tested

Transaction control

StatementEffect
COMMITMakes transaction changes permanent
ROLLBACKUndoes uncommitted transaction changes
SAVEPOINT nameMarks a point to roll back to
ROLLBACK TO SAVEPOINT nameUndoes changes after that savepoint

High-yield distinction:

ActionTransaction impact
DML such as INSERT, UPDATE, DELETERequires transaction control
DDL such as CREATE, ALTER, DROP, TRUNCATEHas implicit commit behavior in Oracle
DELETEDML; can be rolled back before commit
TRUNCATEDDL; not the same transactional behavior as DELETE

Candidate trap: DELETE FROM table_name and TRUNCATE TABLE table_name may both remove rows, but they are not equivalent.

DDL and Schema Objects

Table DDL

StatementPurposeExam note
CREATE TABLECreate tableDefine columns and constraints
ALTER TABLEModify tableAdd/drop/modify columns or constraints
DROP TABLERemove table definitionDDL; commits
TRUNCATE TABLERemove all rows efficientlyDDL; commits; no row-by-row delete
RENAMERename objectObject name change
Notes and examples
CREATE TABLE projects (
  project_id   NUMBER CONSTRAINT projects_pk PRIMARY KEY,
  project_name VARCHAR2(100) NOT NULL,
  start_date   DATE DEFAULT SYSDATE,
  budget       NUMBER(10,2),
  status       VARCHAR2(20)
);

Constraint Reference

ConstraintPurposeColumn-level?Table-level?
NOT NULLRequires valueYesNo
UNIQUEPrevents duplicate non-null valuesYesYes
PRIMARY KEYUnique row identifier; not nullYesYes
FOREIGN KEYEnforces parent-child relationshipYesYes
CHECKEnforces conditionYesYes
CREATE TABLE order_items (
  order_id    NUMBER,
  line_id     NUMBER,
  product_id  NUMBER NOT NULL,
  quantity    NUMBER CHECK (quantity > 0),
  CONSTRAINT order_items_pk PRIMARY KEY (order_id, line_id),
  CONSTRAINT order_items_product_fk
    FOREIGN KEY (product_id) REFERENCES products(product_id)
);

Constraint Actions and Traps

FeatureMeaning
ON DELETE CASCADEDeleting parent deletes child rows
ON DELETE SET NULLDeleting parent sets child foreign key to null
No delete action specifiedParent delete fails if child rows exist
CHECK (col IS NOT NULL)Similar effect to NOT NULL, but not the same declaration
UNIQUE with nullsNull handling differs from ordinary equality intuition; do not treat null as a normal duplicate value

Views

A view is a stored query. It can simplify complex joins, restrict displayed columns, or present derived data.

View conceptReview point
Simple viewOften based on one table; may be updatable if rules are met
Complex viewIncludes joins, groups, functions, or aggregates; update restrictions likely
WITH CHECK OPTIONPrevents changes through the view that violate the view condition
WITH READ ONLYPrevents DML through the view

Candidate trap: a view does not automatically store a separate copy of ordinary query data like a table. It is generally a query definition unless materialized view concepts are explicitly involved.

Sequences

Sequences generate numeric values, commonly for surrogate keys.

PseudocolumnMeaning
sequence_name.NEXTVALGets next sequence value
sequence_name.CURRVALCurrent value in session after NEXTVAL has been used

Review sequence options conceptually: START WITH, INCREMENT BY, MAXVALUE, MINVALUE, CYCLE, NOCYCLE, CACHE, and NOCACHE.

Candidate traps:

  • Sequence numbers can have gaps.
  • Rolling back a transaction does not necessarily “put back” a sequence value.
  • CURRVAL is not available in a session before that session has used NEXTVAL.

Indexes and synonyms

ObjectPurposeTrap
IndexSpeeds access paths and supports uniquenessToo many indexes can affect DML overhead conceptually
Unique indexEnforces uniqueness when used for constraintsConstraint and index are related but not identical concepts
SynonymAlternative name for an objectDoes not grant object privileges
Private synonymAvailable to its ownerName scope matters
Public synonymAvailable database-wide by nameStill requires privileges

Views, Sequences, Synonyms, and Indexes

Views

View conceptMeaning
Simple viewBased on one table, no grouping/functions; more likely DML-capable
Complex viewJoins, groups, functions, expressions, or aggregates; DML may be restricted
CREATE OR REPLACE VIEWRecreates view without dropping privileges in the same way as drop/create
WITH CHECK OPTIONDML through view must satisfy view predicate
WITH READ ONLYPrevents DML through view
FORCECreate view even if base object is not currently valid
NOFORCERequires base object validity
Notes and examples
CREATE OR REPLACE VIEW emp80 AS
SELECT employee_id, last_name, salary, department_id
FROM employees
WHERE department_id = 80
WITH CHECK OPTION;

Sequences

PseudocolumnMeaningTrap
sequence_name.NEXTVALGenerates next sequence valueAdvances the sequence
sequence_name.CURRVALCurrent session’s sequence valueRequires prior NEXTVAL in session
CREATE SEQUENCE project_seq
  START WITH 1
  INCREMENT BY 1;

INSERT INTO projects (project_id, project_name)
VALUES (project_seq.NEXTVAL, 'Migration');

Sequence exam points:

PointExplanation
Sequences are independent objectsNot automatically tied to one table unless used that way
Gaps can occurRollbacks, caching, or failed statements may leave gaps
CURRVAL is session-specificNot valid before NEXTVAL in that session

Indexes and Synonyms

ObjectPurposeNotes
IndexImproves access path for queriesOracle may create indexes for some constraints
Unique indexEnforces uniqueness when used for unique constraintsDistinguish object from constraint
Function-based indexIndex on expressionQuery must use matching expression conceptually
SynonymAlternative name for objectDoes not copy the object
Public synonymAvailable broadlyPrivileges still matter

Privileges and Access Control Basics

ConceptMeaning
System privilegeAllows an action, such as creating objects
Object privilegeAllows access to a specific object, such as SELECT on a table
RoleNamed group of privileges
GRANTGives privilege or role
REVOKERemoves privilege or role
WITH GRANT OPTIONLets grantee grant object privilege to others
WITH ADMIN OPTIONLets grantee administer a role/system privilege
GRANT SELECT ON employees TO analyst_role;
REVOKE SELECT ON employees FROM analyst_role;

High-Yield Error Patterns

PatternLikely problem
WHERE col = NULLShould use IS NULL
Aggregate in WHEREUse HAVING
Non-grouped column in aggregate queryAdd to GROUP BY or aggregate it
Single-row subquery returns multiple rowsUse multi-row operator or restrict subquery
NOT IN subquery returns nullUse NOT EXISTS pattern
Missing join conditionCartesian product
Filtering outer-joined table in WHERERemoves unmatched rows
CONCAT(a,b,c)Oracle CONCAT accepts two arguments
Using alias in WHEREAlias not available there
ROWNUM > 1 directlyNo first row can satisfy it
Set operator column mismatchSame column count and compatible types required
DDL followed by rollback expectationDDL has implicit commit behavior

Mini Decision Tables

WHERE vs HAVING

NeedClause
Filter individual rows before aggregationWHERE
Filter groups after aggregationHAVING
Use aggregate conditionHAVING
Improve grouping input setWHERE

Join vs Subquery

NeedPrefer
Return columns from multiple tablesJoin
Test existenceEXISTS / NOT EXISTS
Compare to aggregate valueScalar or single-row subquery
Anti-match with possible nullsNOT EXISTS
Combine similar result sets verticallySet operator

DELETE vs TRUNCATE vs DROP

NeedUse
Remove selected rows and allow transaction controlDELETE ... WHERE ...
Remove all rows as DDL-style operationTRUNCATE TABLE
Remove the table object itselfDROP TABLE

Exam-Day SQL Checklist

Before selecting an answer on Oracle 1Z0-071 SQL questions, check:

  1. Are nulls involved? If yes, verify IS NULL, aggregate behavior, and NOT IN logic.
  2. Are aggregates mixed with detail columns? If yes, verify GROUP BY.
  3. Is the filter row-level or group-level? Choose WHERE or HAVING.
  4. Is an alias used before it exists? Alias is safest in ORDER BY.
  5. Does a subquery return one row or many rows? Match the operator.
  6. Does an outer join still preserve unmatched rows after filtering?
  7. Do set operator queries have the same number and compatible types of columns?
  8. Does DDL appear in a transaction question? Remember implicit commit behavior.
  9. Is a date compared as text? Prefer explicit conversion with a format model.
  10. Is the question asking for syntax validity or result behavior? Check both.

High-yield review map

AreaKnow coldCommon trap
SELECT statementsClause order, aliases, sorting, filteringUsing a column alias in WHERE
NULL handlingIS NULL, NVL, COALESCE, NULLIF, NVL2Comparing with = NULL or <> NULL
Single-row functionsCharacter, number, date, conversion, conditionalConfusing ROUND and TRUNC; implicit conversion surprises
Group functionsCOUNT, SUM, AVG, MIN, MAX, GROUP BY, HAVINGSelecting non-grouped columns with aggregates
JoinsInner, outer, self, cross, ON, USING, natural joinsNatural joins matching unintended same-name columns
SubqueriesSingle-row, multiple-row, correlated, EXISTSNOT IN with NULL returning no expected rows
Set operatorsUNION, UNION ALL, INTERSECT, MINUSWrong column count or incompatible datatype groups
DML and transactionsINSERT, UPDATE, DELETE, COMMIT, ROLLBACK, SAVEPOINTForgetting DDL causes implicit commit behavior
DDL and objectsTables, constraints, views, sequences, indexes, synonymsAssuming a synonym grants privileges
PrivilegesGRANT, REVOKE, system vs object privilegesConfusing WITH GRANT OPTION and WITH ADMIN OPTION

Filtering, sorting, and row conditions

Predicates and operators

NeedUseWatch for
Exact match=Case-sensitive for character data unless transformed
RangeBETWEEN low AND highInclusive on both ends
List matchIN (...)Equivalent to multiple OR checks
Pattern matchLIKE% means any length; _ means one character
Null testIS NULL / IS NOT NULLNever = NULL
Negative logicNOT, <>, !=, NOT INNULL can change expected results
Combined logicAND, ORAND has higher precedence than OR
Notes and examples

Use parentheses when a condition mixes AND and OR. The exam often checks whether you know how a condition is actually evaluated.

NULL rules

NULL means unknown or unavailable, not zero, blank, or false.

ExpressionResult concept
salary + NULLNULL
commission_pct = NULLNot true; use IS NULL
commission_pct <> NULLNot true; use IS NOT NULL
NVL(commission_pct, 0)Replace null with 0
COALESCE(a, b, c)First non-null expression
NULLIF(a, b)Returns NULL if a = b, else a
NVL2(expr, value_if_not_null, value_if_null)Two-branch null handling

Sorting rules

SyntaxMeaning
ORDER BY col ASCAscending; often default
ORDER BY col DESCDescending
ORDER BY 2Sort by second select-list item
ORDER BY aliasSort by select-list alias
NULLS FIRST / NULLS LASTExplicit null placement

If a query does not include ORDER BY, do not assume output order.

Group functions and aggregation

Aggregate function essentials

FunctionWhat it doesNull behavior
COUNT(*)Counts rowsIncludes rows with nulls
COUNT(expr)Counts non-null expression valuesIgnores nulls
COUNT(DISTINCT expr)Counts distinct non-null valuesIgnores nulls
SUM(expr)Adds valuesIgnores nulls
AVG(expr)Averages valuesIgnores nulls
MIN(expr)Lowest valueIgnores nulls
MAX(expr)Highest valueIgnores nulls
Notes and examples

Important difference:

  • AVG(commission_pct) averages only rows where commission_pct is not null.
  • AVG(NVL(commission_pct, 0)) treats null commission values as zero.

GROUP BY decision rule

If the SELECT list contains both aggregate expressions and non-aggregate expressions, every non-aggregate expression must be included in the GROUP BY.

Select-list itemMust be in GROUP BY?
department_idYes, if selected with aggregates
UPPER(job_id)Yes, as the expression if selected with aggregates
COUNT(*)No
AVG(salary)No
Literal such as 'Total'No

WHERE vs HAVING

ClauseFiltersCan use group functions?
WHERERows before groupingNo
HAVINGGroups after groupingYes

Example decision:

  • Need employees with salary > 10000 before calculating department average? Use WHERE.
  • Need departments with AVG(salary) > 10000? Use HAVING.

DDL, data types, and constraints

Common Oracle data types

Data typeUseReview point
VARCHAR2(size)Variable-length character dataCommon text type
CHAR(size)Fixed-length character dataPads to fixed length
NUMBER(p,s)Numeric dataPrecision and scale matter
DATEDate and time to secondsNot just date-only
TIMESTAMPMore precise date/timeFractional seconds
CLOBLarge character dataLarge text
BLOBBinary large objectBinary data
Notes and examples

Constraint types

ConstraintPurposeKey trap
NOT NULLColumn must have valueColumn-level only in typical syntax
UNIQUEValues must be uniqueMultiple nulls may be allowed depending on columns
PRIMARY KEYUnique row identifierImplies uniqueness and not null
FOREIGN KEYEnforces parent-child relationshipChild value must match parent or be null if allowed
CHECKEnforces conditionCannot rely on invalid expressions
DEFAULTSupplies value when omittedNot the same as inserting explicit NULL

Foreign key delete actions

ClauseEffect
No special clauseParent delete blocked if child rows exist
ON DELETE CASCADEDeletes dependent child rows
ON DELETE SET NULLSets child foreign key values to null

Data dictionary and metadata

Oracle data dictionary views are frequently grouped by prefix.

PrefixMeaning
USER_Objects owned by the current user
ALL_Objects accessible to the current user
DBA_Database-wide administrative views, if privileged

Examples you may see conceptually include table, column, constraint, view, sequence, index, and synonym metadata. Know the difference between owning an object and merely having access to it.

Privileges and security basics

Privilege types

TypeExamplesGranted on
System privilegeCREATE SESSION, CREATE TABLECapability in the database
Object privilegeSELECT, INSERT, UPDATE, DELETESpecific object
RoleNamed collection of privilegesGranted to users or other roles depending on rules

Grant option distinctions

ClauseApplies toMeaning
WITH GRANT OPTIONObject privilegesRecipient can grant that object privilege to others
WITH ADMIN OPTIONSystem privileges or rolesRecipient can administer/grant it further

Candidate trap: revoking a privilege can have cascading effects for object privileges granted onward through WITH GRANT OPTION.

Common 1Z0-071 mistake checklist

Before answering, check these items:

  1. Is there an ORDER BY? If not, do not assume row order.
  2. Is NULL involved? Replace normal comparison thinking with three-valued logic.
  3. Is an alias used too early? WHERE cannot see select-list aliases.
  4. Are aggregate and non-aggregate columns mixed? Check GROUP BY.
  5. Is the filter row-level or group-level? Choose WHERE vs HAVING.
  6. Is the join natural? Look for unintended same-name columns.
  7. Is an outer join filtered in WHERE? It may remove null-extended rows.
  8. Can a subquery return multiple rows? Use the right operator.
  9. Can a NOT IN subquery return null? Consider the null trap.
  10. Do set operator queries align? Same column count and compatible datatype groups.
  11. Is a date literal or conversion format ambiguous? Prefer explicit conversion.
  12. Is the statement DML or DDL? Transaction behavior differs.
  13. Does a synonym exist? That does not mean the user has privileges.
  14. Is a sequence expected to be gap-free? Do not assume that.
  15. Is COUNT(*) being confused with COUNT(column)? Null handling differs.

Fast decision tables

Which clause should solve the problem?

RequirementLikely clause
Choose displayed columns or expressionsSELECT
Choose source tablesFROM
Connect tablesJOIN ... ON or USING
Filter rows before groupingWHERE
Group rowsGROUP BY
Filter groupsHAVING
Sort final outputORDER BY
Notes and examples

Which SQL feature should solve the problem?

RequirementFeature
Replace null commission with zeroNVL or COALESCE
Display date as textTO_CHAR
Convert text to dateTO_DATE
Compare to department averageSubquery or analytic logic if provided
Return departments with no employeesOuter join plus null check or NOT EXISTS
Combine two result sets and remove duplicatesUNION
Combine two result sets and keep duplicatesUNION ALL
Find rows in first query but not secondMINUS
Generate new numeric key valuesSequence
Prevent invalid child rowsForeign key constraint
Restrict DML through a viewWITH CHECK OPTION or WITH READ ONLY

Practice plan after this review

Use this page as a final concept pass, then move into active recall:

  1. Topic drills: Work in focused sets: joins, subqueries, group functions, DML, DDL, and set operators.
  2. Original practice questions: Prioritize questions that require predicting output or identifying invalid SQL.
  3. Detailed explanations: For every missed item, identify the exact rule: alias scope, null behavior, datatype conversion, grouping rule, transaction behavior, or privilege rule.
  4. Mixed question bank sessions: After topic drills, use mixed sets to practice switching between concepts under time pressure.
  5. Mock exams: Use full-length practice only after your weak topics are improving; otherwise, mock exams mostly confirm the same gaps.

Final quick review routine

In your last study block before more practice, review in this order:

  1. NULL rules and conditional functions.
  2. Group functions, GROUP BY, and HAVING.
  3. Join types and outer join predicate placement.
  4. Subquery operators, especially IN, ANY, ALL, EXISTS, and NOT IN.
  5. Set operator alignment rules.
  6. DML vs DDL transaction behavior.
  7. Constraints, views, sequences, synonyms, and privileges.

Next step: move from reading to doing—start a focused 1Z0-071 question bank session with topic drills and detailed explanations, then use your missed questions to drive the next review pass.

Put the review into practice