How can I shorten an Oracle SQL Union All query in which most elements are the exact same?
10:59 26 May 2026

I'm working with Oracle SQL 20.2 and writing a PLSQL procedure. The main body of the procedure is a Select query in which I make use of UNION ALL to get rows from two different tables that join onto the same table, from which I get the vast majority of values.

I've written a simplified version of the query:

SELECT
    t2.col_b AS col_1,
    t1.col_2,
    [...]
    t1.col_30
    FROM table_a t1 JOIN table_b t2 ON t2.fk_table_a = t1.id
    WHERE [...] --Other conditions, different from below
UNION ALL
    t2.col_c AS col_1,
    t1.col_2,
    [...]
    t1.col_30
    FROM table_a t1 JOIN table_c t2 ON t2.fk_table_a = t1.id
    WHERE [...] --Other conditions, different from above

Here I'm simply getting 30 columns, of which the first one depends on the table I'm joining to, and the remaining 29 are the exact same, all taken from table_a. In truth, the query I'm working with is much longer and has plenty of joins and where clauses that are common between the two halves of the UNION ALL, but I imagine that doesn't make a difference.

As you can see, in this example I would have to copy and paste those 29 lines that take from table_a's columns in both elements of the union, meaning the final query would end up being almost twice as long as if I could just write those once. Is there any way for me to rewrite this query by perhaps only taking col_1 out of the union, meaning I wouldn't have to repeat lines of the query?

oracle-database plsql oracle-sqldeveloper