Write a query to print stars

Patterns covered:
  • Increasing stars
  • Decreasing stars
  • Right-aligned increasing stars
  • Right-aligned decreasing stars
  • All patterns in one query

1. Increasing star pattern

Query:

SELECT LPAD('*', LEVEL, '*') AS col
FROM dual
CONNECT BY LEVEL <= 5;

Output:

*
**
***
****
*****

2. Decreasing star pattern

Query:

SELECT LPAD('*', 5 - LEVEL + 1, '*') AS col
FROM dual
CONNECT BY LEVEL <= 5;

Output:

*****
****
***
**
*

3. Right-aligned increasing star pattern

This query adds spaces on the left and then prints stars, creating a right-aligned triangle.

Query:

SELECT LPAD(' ', 5 - LEVEL, ' ') || LPAD('*', LEVEL, '*') AS col
FROM dual
CONNECT BY LEVEL <= 5;

Output:

    *
   **
  ***
 ****
*****

4. Right-aligned decreasing star pattern

This query prints decreasing stars while keeping them aligned to the right.

Query:

SELECT LPAD(' ', LEVEL - 1, ' ') || LPAD('*', 5 - LEVEL + 1, '*') AS col
FROM dual
CONNECT BY LEVEL <= 5;

Output:

*****
 ****
  ***
   **
    *

5. All patterns in one query

You can also display all four patterns together using a single query.

Query:

SELECT LPAD('*', LEVEL, '*') AS col1,
       LPAD('*', 5 - LEVEL + 1, '*') AS col2,
       LPAD(' ', 5 - LEVEL, ' ') || LPAD('*', LEVEL, '*') AS col3,
       LPAD(' ', LEVEL - 1, ' ') || LPAD('*', 5 - LEVEL + 1, '*') AS col4
FROM dual
CONNECT BY LEVEL <= 5;

What each column shows

Column Pattern
col1 Increasing stars
col2 Decreasing stars
col3 Right-aligned increasing stars
col4 Right-aligned decreasing stars

How it works

  • LEVEL generates rows from 1 to 5.
  • LPAD() pads the string with spaces or stars.
  • CONNECT BY LEVEL <= 5 creates the number of rows needed for the pattern.
Key Point:
LPAD() with LEVEL is a simple way to generate star patterns in Oracle SQL.

No comments:

Post a Comment