Mohsin
Mohsin

Reputation: 61

Can we write subquery in between SELECT and FROM

i want to know, how to write subquery in between SELECT and FROM as

SELECT Col_Name,(Subquery) 
  From Table_Name 
 Where Some_condition

Upvotes: 6

Views: 2366

Answers (2)

OMG Ponies
OMG Ponies

Reputation: 332541

This:

SELECT y.col_name,
       (SELECT x.column
          FROM TABLE x) AS your_subquery
  FROM TABLE y
 WHERE y.col = ?

...is a typical subquery in the SELECT clause. Some call it a "subselect". This:

SELECT y.col_name,
       (SELECT x.column
          FROM TABLE x
         WHERE x.id = y.id) AS your_subquery
  FROM TABLE y
 WHERE y.col = ?

...is a correlated subquery. It's correlated because the subquery result references a table in the outer query (y in this case).

Effectively, just write whatever additional SELECT statement you want in the SELECT clause, but it has to be surrounded by brackets.

Upvotes: 6

Iulian
Iulian

Reputation: 1200

you can do it, but you must use an alias for the subquery

SELECT Col_Name,(Subquery) as S
  From Table_Name 
 Where Some_condition

Upvotes: 2

Related Questions