1

I would like to achieve something like this:

SELECT col1,col2-(SELECT foo FROM table1) 
FROM table2 
WHERE col2>(SELECT foo FROM table1)

Without SELECTing foo twice.

Can I do that with Oracle SQL? Would it be more efficient than SELECTing twice (or multiple times)?

1
  • 2
    Is there really only a single row in table1? If not, what is the relationship between the two tables? Commented Jan 12, 2012 at 12:05

4 Answers 4

6

How about

WITH
  foo      AS  select foo from table1
SELECT
    col1, col2 - foo.foo
FROM
    table2, foo
WHERE
   col2 > foo.foo
Sign up to request clarification or add additional context in comments.

2 Comments

+1 The WITH clause is expressly provided for the purpose of re-using a sub-query in more than one place.
Note that in this case it is only actually used in once place (in the cartesian join). However, that may have been because the example has been simplified, and WITH is a good thing to know about.
4

You could write it like this:

SELECT
    s.col1, s.col2 - s.foo
FROM
(
    SELECT col1, col2, (SELECT foo FROM table1) as foo
    FROM table2
) s
WHERE s.col2 > s.foo

Comments

1

Assuming that your subquery returns a single row (otherwise, both uses of the subquery would return errors), simply do a Cartesian join

SELECT a.col1, a.col2 - b.foo
  FROM table2 a,
       (SELECT foo FROM table1) b
 WHERE a.col2 > b.foo

Comments

1
SELECT col1, col2 - foo
  FROM table2, table1
 WHERE col2 > foo

But only if table1 has 1 row.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.