Sub topic 5
Indenting the output to look like a tree
This chapter assumes you can write a basic START WITH ... CONNECT BY PRIOR query and that you know what LEVEL returns. It also assumes you are comfortable with LPAD and the || concatenation operator. Here you turn the flat list a hierarchical query returns into text that looks like an org chart.
Why a flat list is hard to read
A hierarchical query returns rows in depth-first order. Each child appears after its parent and before the parent's next sibling. The order is already correct, but nothing in the output shows depth. With only last_name selected, you can't tell a vice president from an intern.
SELECT last_name, LEVEL
FROM employees
START WITH manager_id IS NULL
CONNECT BY PRIOR employee_id = manager_id;The LEVEL column holds the depth, but a number is not a picture. The usual fix is to pad each name on the left with spaces. The number of spaces grows with LEVEL.
The LPAD pattern
LPAD(string, n, pad) returns string padded on the left with pad characters until it is n characters long. If string is already longer than n, LPAD truncates it. This is the main trap in this pattern, and a later section covers it.
The common idiom pads a single space to a length that depends on the depth:
SELECT LPAD(' ', 2 * (LEVEL - 1)) || last_name AS org_chart,
LEVEL
FROM employees
START WITH manager_id IS NULL
CONNECT BY PRIOR employee_id = manager_id
ORDER SIBLINGS BY last_name;Read the expression from the inside out:
LEVEL - 1is 0 for the root, 1 for its direct reports, 2 for the next layer, and so on.2 * (LEVEL - 1)gives two spaces of indent per layer.LPAD(' ', 2 * (LEVEL - 1))builds a string of exactly that many spaces.|| last_nameappends the name after the spaces.
Subtracting 1 matters. Without it the root would be indented by two spaces. Subtracting 1 also keeps the width at zero for the root. The width then never reaches zero for a deeper row, so the LPAD call never receives a length of zero.
The ORDER SIBLINGS BY last_name clause sorts employees alphabetically within each manager. It keeps every child directly under its parent. The next chapter covers it in detail. It is included here so the output is stable and easy to read.
A result for a typical sample table looks like this:
ORG_CHART LEVEL
-------------------- -----
King 1
Cambrault 2
Bates 3
Bloom 3
Kochhar 2
Baer 3What the three arguments do
The second argument is the total length of the result. Many people expect it to be the number of pad characters to add. For a one-space source string the two are the same only when the source is exactly one character long, which is the case here. That is why the idiom pads ' ' and not the name.
The third argument is optional. When you leave it out, LPAD pads with spaces. The following two expressions give the same result:
SELECT LPAD(' ', 4) AS a,
LPAD(' ', 4, ' ') AS b
FROM dual;You may therefore write the third argument for clarity, or drop it, as the earlier example does.
Choosing a different indent character
Spaces can disappear when the output is shown in a web page or a client that trims whitespace. Use a visible filler when you need the structure to survive:
SELECT LPAD('-', 2 * (LEVEL - 1), '-') || last_name AS org_chart
FROM employees
START WITH manager_id IS NULL
CONNECT BY PRIOR employee_id = manager_id
ORDER SIBLINGS BY last_name;Here the first argument is '-', which has length 1. The expression builds a run of dashes whose length is 2 * (LEVEL - 1). For the root the length is 0, so LPAD returns an empty string in Oracle. An empty string in Oracle is NULL. Concatenating NULL with a string using || returns the string unchanged, so the root still prints.
A common mistake: the zero-length result
Because an empty string is NULL in Oracle, LPAD(' ', 0) returns NULL. This is safe with || but not with other functions. If you wrap the padded value in LENGTH, CONCAT with a non-string, or an arithmetic expression, the NULL can propagate. Use || for building the label and you avoid the problem.
Indenting a different column
You can indent any expression, not just a name. Another form pads the name itself so that the column has a fixed width that grows with depth:
SELECT LPAD(last_name, LENGTH(last_name) + 2 * (LEVEL - 1)) AS org_chart
FROM employees
START WITH manager_id IS NULL
CONNECT BY PRIOR employee_id = manager_id
ORDER SIBLINGS BY last_name;This version passes the name as the first argument. The target length is the name's own length plus the indent. LPAD therefore adds exactly 2 * (LEVEL - 1) characters to the left of the name, and nothing is truncated.
The danger appears when you choose a fixed target length instead:
SELECT LPAD(last_name, 10) AS broken
FROM employees
START WITH manager_id IS NULL
CONNECT BY PRIOR employee_id = manager_id;A name longer than 10 characters is cut off at 10. A fixed target also does not indent by depth at all, because it ignores LEVEL. When the target length depends on LENGTH(last_name), no name is truncated.
| Pattern | Indent grows with depth | Names can be truncated | Notes | Column | Column |
|---|---|---|---|---|---|
| `LPAD(' ', 2 * (LEVEL - 1)) \ | \ | last_name` | Yes | No | The standard idiom. |
| `LPAD(last_name, LENGTH(last_name) + 2 * (LEVEL - 1))` | Yes | No | One call, but `LENGTH` is repeated. | ||
| `LPAD(last_name, 10)` | No | Yes | Aligns to a fixed width only. |
Adding a tree-style branch marker
You can build a more tree-like look by adding a marker after the padding:
SELECT LPAD(' ', 3 * (LEVEL - 1)) ||
CASE WHEN LEVEL > 1 THEN '+- ' END ||
last_name AS org_chart
FROM employees
START WITH manager_id IS NULL
CONNECT BY PRIOR employee_id = manager_id
ORDER SIBLINGS BY last_name;The CASE expression has no ELSE, so it returns NULL for the root. As before, || treats NULL as an empty string, and the root prints with no marker. Each deeper row gets +- in front of its name.
Keep the indent out of your data
The padded value is a display label. Do not use it for joins, comparisons, or further grouping. If you need the real name in the same query, select it as a separate column:
SELECT employee_id,
last_name,
LPAD(' ', 2 * (LEVEL - 1)) || last_name AS org_chart
FROM employees
START WITH manager_id IS NULL
CONNECT BY PRIOR employee_id = manager_id
ORDER SIBLINGS BY last_name;If you move this query into a view or a subquery, apply the indentation in the outermost SELECT list when you can. Other consumers of the view then still get clean values.
Client display issues
Padding with spaces depends on the client showing the result in a fixed-width font.
- In SQL*Plus and SQLcl the default output is fixed-width, and the leading spaces display as written.
- Some tools trim leading whitespace in grid views. Switch to a visible filler such as
'.'or'-', or use the branch-marker form. - Spooling to a file preserves the spaces, but a spreadsheet import may strip them.
- Use
SET LINESIZEand aCOLUMN org_chart FORMAT A40setting in SQL*Plus if long names wrap or are cut.
Summary of the pattern
- Subtract 1 from
LEVELso the root has no indent. - Multiply by the indent width you want per layer.
- Pad a one-character string, then concatenate the name with
||. - Keep
ORDER SIBLINGS BYin place so the tree order is preserved. Without it, the order among siblings is not defined. - Do not use the padded label for anything except display.
Exercise
A colleague writes SELECT LPAD(last_name, 2 * LEVEL) FROM employees START WITH manager_id IS NULL CONNECT BY PRIOR employee_id = manager_id; to indent the names. Name two things that go wrong, and write a corrected expression that indents each layer by four spaces with no indent for the root.
Show answer
First, the target length 2 * LEVEL is a total length, not the number of spaces to add. A name longer than 2 * LEVEL characters is truncated, so shallow rows with long names lose characters. Second, the root has LEVEL 1, so even the root is treated as needing a total width of 2, and the indent does not match the depth in a meaningful way. The corrected expression is LPAD(' ', 4 * (LEVEL - 1)) || last_name. It pads a single space to a length of 0 for the root and 4 more for each deeper layer, then appends the full name with no truncation.
Exercise
Why does LPAD(' ', 2 * (LEVEL - 1)) || last_name still show the root's name even though LPAD returns a zero-length value for the root? What could break if you replaced || with another operation?
Show answer
In Oracle an empty string is NULL. The || operator treats NULL as an empty string, so NULL || 'King' returns 'King'. If you replaced || with an operation that does not tolerate NULL, such as arithmetic or some function calls like LENGTH on the padded value, the root's result would be NULL and the root row would show as blank or fail to compute.