Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reuse a sub query in sql?

I have query like the following

select columns
from (select columns1
      from result_set
      where condition_common and condition1) as subset1
      join
      (select columns2
       from result_set
       where condition_common and condition2) as subset2 
      on subset1.somekey = subset2.somekey

I want to somehow reuse

select columns
from result_set
where condition_common

I have oversimplified the above query, but the above select in reality is huge and complicated. I dont want to have the burden of making sure both are in sync

I dont have any means of programmatically reusing it. T-SQL is ruled out. I can only write simple queries. This is an app limitation.

Is there a way to reuse same subquery, in a single statement

like image 216
Schu Avatar asked Feb 20 '13 18:02

Schu


People also ask

Can you use 2 subqueries in a SQL query?

A subquery is a complete query that appears in the WHERE or HAVING clause of an SQL statement. You can specify up to 16 subqueries within a single SQL statement, and you can specify subqueries within a subquery. Subqueries run from last to first within the main SQL statement in which they appear.

How do you enclose a sub query?

You must enclose a subquery in parenthesis. A subquery must include a SELECT clause and a FROM clause. A subquery can include optional WHERE, GROUP BY, and HAVING clauses. A subquery cannot include COMPUTE or FOR BROWSE clauses.

Is sub query return a single value?

A scalar subquery returns a single value (one column of one row). If no rows qualify to be returned, the subquery returns NULL. A non-scalar subquery returns 0, 1, or multiple rows, each of which may contain 1 or multiple columns. For each column, if there is no value to return, the subquery returns NULL.

Can sub query be used inside a case statement?

To answer your question, Yes, you can have a subquery inside a Case statement.


1 Answers

Use a Common Table Expression (CTE) if you're using SQL Server 2005+:

with cte as (
      select columns
      from result_set
      where condition_common
    )
select columns
from cte  as subset1
      join
      cte as subset2 
         on subset1.somekey = subset2.somekey
where otherconditions
like image 135
sgeddes Avatar answered Oct 19 '22 13:10

sgeddes