Skip to content
Advertisement

SQL Conditional on SELECT Subquery value

I want to apply a condition check on my select subquery. How can I do it optimally?

Here’s the initial query:

SELECT 
  table1.column1, 
  (SELECT min(table2.column1) FROM table2 WHERE table2.table1Id = table1.id) as subResult
FROM table1
WHERE table1.column2 = "something"

And I want to add the WHERE condition subResult = :parameter. And the :parameter is optional, meaning if :parameter is null, include row in result.

WHERE table1.column2 = "something" AND (:parameter is null or subResult = :parameter)

But I can’t reference the result of the subquery subResult inside my WHERE condition.

I can copy/paste the subquery into the WHERE clause, but that seems sloppy and error prone:

SELECT 
  table1.column1, 
  (SELECT min(table2.column1) FROM table2 WHERE table2.table1Id = table1.id) as subResult
FROM table1
WHERE table1.column2 = "something" AND (:parameter is null or (SELECT min(table2.column1) FROM table2 WHERE table2.table1Id = table1.id) = :parameter)

Advertisement

Answer

If you are running Oracle 12 or higher, I would recommend a lateral join:

select t1.column1, t2.min_column1
from table1 t1
outer apply (select min(t2.column1) min_column1 from table2 t2 where t2.table1id = t1.id) t2
where 
    t1.column2 = 'something' 
    and (:parameter is null or t2.min_column1 = :parameter)

In earlier versions, you can use a subquery or CTE:

select *
from (
    select t1.column1, 
        (select min(t2.column1) from table2 t2 where t2.table1id = t1.id) as min_column1
    from table1 t1
) t
where 
    t1.column2 = 'something' 
    and (:parameter is null or t2.min_column1 = :parameter)
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement