Data Retrieval in PL/SQL โ SELECT, LEVEL, and Hierarchical Queries
Introduction to Data Retrieval in PL/SQL
Data Retrieval in PL/SQL
goes beyond simple SELECT
queries. Oracle supports:
Standard SQL
SELECT
statementsHierarchical queries using
LEVEL
Pattern matching using Regular Expressions
Full-text search with Oracle Text
This article explores how to retrieve both flat and hierarchical data in PL/SQL with real-world examples.
All PL/SQL codeโwhether part of an anonymous block, stored procedure, function, trigger, or packageโstarts with a block. Even the most complex Oracle application is built from these simple building blocks.
Basic SELECT Statement in PL/SQL
SELECT column_list
INTO variable_list
FROM table_list
[WHERE condition]
[ORDER BY column_list];
SELECT
: Columns, expressions, or*
INTO
: Stores result into one or more PL/SQL variablesFROM
: One or more tables or subqueriesWHERE
: Filters the result setORDER BY
: Sorts the result
Variables and INTO Clause
PL/SQL requires SELECT INTO
to fetch values into variables. These variables must match the number and data types of the selected columns.
DECLARE
v_title BOOKS.TITLE%TYPE;
BEGIN
SELECT title INTO v_title FROM books WHERE isbn = '72230665';
DBMS_OUTPUT.PUT_LINE(v_title);
END;
Handling SELECT Exceptions
You must ensure exactly one row is returned. Otherwise:
No rows:
ORA-01403: no data found
Multiple rows:
ORA-01422: exact fetch returns more than requested number of rows
EXCEPTION
WHEN NO_DATA_FOUND THEN ...
WHEN TOO_MANY_ROWS THEN ...
Hierarchical Data Retrieval in PL/SQL
Some data is structured hierarchically โ like employees and managers, or books in a series. To navigate these relationships, Oracle uses:
LEVEL
pseudocolumnSTART WITH
CONNECT BY PRIOR
Column | Description |
---|---|
ISBN | Unique ID for book |
PARENT_ISBN | References previous book |
TITLE | Book title |
SERIES | Series name |
Example: Using LEVEL, START WITH, CONNECT BY
SET SERVEROUTPUT ON
DECLARE
v_level PLS_INTEGER;
v_title BOOKS.TITLE%TYPE;
CURSOR cur_tree IS
SELECT isbn, title, series FROM books;
BEGIN
FOR l IN cur_tree LOOP
SELECT MAX(LEVEL)
INTO v_level
FROM books
START WITH isbn = l.isbn
CONNECT BY PRIOR parent_isbn = isbn;
DBMS_OUTPUT.PUT_LINE(l.title || ' is book ' ||
v_level || ' in the ' || l.series || ' series');
END LOOP;
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE(SQLERRM);
END;
/
Best Practices for Data Retrieval in PL/SQL
Always handle exceptions for
SELECT INTO
.Use
%TYPE
to keep variable types consistent with table columns.Use hierarchical queries for recursive relationships.
For multi-row SELECTs, use cursors or bulk collect.
AmantPoint Exclusive Learning Series
ยฉ 2025 AmantPoint. All rights reserved. Educational content for developers and learners.