🔹 LEVEL in Oracle SQL
The LEVEL
pseudocolumn in Oracle is primarily used with hierarchical queries and CONNECT BY to generate sequences, recursive hierarchies, and tree structures.
1️⃣ Basic Usage of LEVEL to Generate a Sequence of Numbers
One of the simplest uses of LEVEL
is to generate a series of numbers without needing a table.
🔹 Output:
📌 Use Case: When you need a quick sequence of numbers for testing or looping.
2️⃣ Generating a Date Series
You can use LEVEL
to generate a range of dates dynamically.
🔹 Output:
📌 Use Case: Create a list of future dates dynamically.
3️⃣ Creating a Hierarchical Employee Tree
The LEVEL
pseudocolumn is often used in hierarchical queries to represent parent-child relationships.
🔹 Explanation:
START WITH manager_id IS NULL
→ Finds the top-level manager.CONNECT BY PRIOR emp_id = manager_id
→ Builds a tree hierarchy.
📌 Use Case: Retrieve a company's employee hierarchy.
4️⃣ Creating an Organizational Chart with Indentation
🔹 Output (Indented to show hierarchy):
📌 Use Case: Display a hierarchical structure with proper indentation.
5️⃣ Creating a Fibonacci Series Using LEVEL
🔹 Output:
📌 Use Case: Generate a Fibonacci series without using PL/SQL loops.
6️⃣ Duplicating Rows Using LEVEL
If you want to repeat each row multiple times, use LEVEL
.
📌 Use Case: Generate dummy test data.
7️⃣ Splitting a Comma-Separated String into Rows
If you have a column with comma-separated values and want to convert them into rows:
🔹 Output:
📌 Use Case: Normalize comma-separated values into rows.
8️⃣ Creating a Pivot Table Using LEVEL
If you need to transform rows into columns, LEVEL
can be helpful:
🔹 Output:
📌 Use Case: Convert rows to columns dynamically.
🔹 Summary of LEVEL Use Cases
Use Case | Example |
---|---|
Generating a Number Sequence | SELECT LEVEL FROM DUAL CONNECT BY LEVEL <= 10; |
Generating a Date Series | SELECT SYSDATE + LEVEL FROM DUAL CONNECT BY LEVEL <= 7; |
Building Employee Hierarchies | START WITH manager_id IS NULL CONNECT BY PRIOR emp_id = manager_id; |
Creating Indented Org Charts | `LPAD(' ', LEVEL * 3) |
Generating Fibonacci Series | Formula with POWER() and SQRT(5) |
Duplicating Rows | CONNECT BY LEVEL <= 3; |
Splitting CSV Values into Rows | REGEXP_SUBSTR(csv_data, '[^,]+', 1, LEVEL) |
Creating Pivot Tables | CASE WHEN LEVEL = 1 THEN category END |