Search code examples
sqlimpala

Search another table if the first query returns 0


I have this query :

select id,name,surname
from db.table
where id_date = 20201101

But I want if this query returns 0 results to run this:

select d.id, d.name, d.surname
from db.table2 as d
inner join db.table3 as g
on d.id = g.id
where d.id_date =20201101

Is this possible? My first thought was to do it with subquery but I can not figure out how to handle the result set


Solution

  • As per jarlh's comment:

    --"first query"
    select id,name,surname
    from db.table
    where id_date = 20201101
    
    UNION ALL
    
    --"second query"
    select d.id, d.name, d.surname
    from db.table2 as d
    inner join db.table3 as g
    on d.id = g.id
    where d.id_date =20201101 AND NOT EXISTS(
    
      select id,name,surname
      from db.table
      where id_date = 20201101
    
    )
    

    If the first query returns results then the NOT EXISTS will be false so the entire where clause of the second query is false and hence that second query has no output. The overall results are "some first query results union all nothing"

    Conversely if the first query outputs nothing then NOT EXISTS (nothing) is true and the output of the second query becomes dependent on the truth of d.id_date=20201101 The overall query results are "nothing union all some second query results"

    It's worth pointing out that this is exactly "run this, if no output run that" - it's a "run all of this" that achieves a modified output by considering both sides of a Boolean truth. As such it might be that the db will only run the first query once, having working out its used in two places, and reuse the results it gets in both places, but it's not guaranteed - it might be that the first query is run twice so make sure it's optimally indexed etc