0

I am trying to speed up a stored procedure, and have the following subqueries:

    SELECT
    ...
        ISNULL((SELECT Table1.Order WHERE Table2.STATUS <> 'R'),0) AS 'Order',
        ISNULL((SELECT Table1.Order WHERE Table2.STATUS = 'R'),0) AS 'Reject',
    ...
FROM Table1
LEFT JOIN
Table2
ON Table1.KEY=Table2.KEY

Is there a way to more efficiently write the above?

I was thinking an IF statement or something, but not quite sure how to write it.

I'm asking this because I read that it's good to minimize subqueries to improve performance.

14
  • 1
    Is that valid syntax? Where is the FROM in the subqueries? Commented May 10, 2013 at 18:42
  • 3
    Please provide the full and valid query. Commented May 10, 2013 at 18:42
  • Why are you selecting this as two separate columns? Commented May 10, 2013 at 18:42
  • 2
    "...I read that it's good to minimize subqueries to improve performance." You're hoping that a change will help. Hope doesn't scale well. Learn to read the execution plan instead. Commented May 10, 2013 at 18:47
  • 2
    @MartinSmith oh gross. Now how do we all unlearn that. Commented May 10, 2013 at 19:17

2 Answers 2

3

Try to use CASE WHEN:

SELECT 
       /* ... */
       [Order] = CASE
                   WHEN t2.STATUS <> 'R' THEN t1.[Order]
                   ELSE 0
                 END,
       Reject = CASE
                  WHEN t2.STATUS = 'R' THEN t1.[Order]
                  ELSE 0
                END
       /* ... */                
FROM   Table1 t1
       LEFT JOIN Table2 t2
         ON t1.[KEY] = t2.[KEY] 
Sign up to request clarification or add additional context in comments.

2 Comments

+1 but please don't use 'single quotes' for aliases - certain forms of this are deprecated and it makes them look an awful lot like string literals. [square brackets] are much preferred.
@Mike - Thanks, this was what I was looking for!...and thanks to all for your input.
0

You can try using oracle "UNION" equivalent for SQL Server. I have worked on Oracle 10g and you can use like,

SELECT Table1.Order 
FROM Table1, Table2 
WHERE Table2.STATUS <> 'R' and Table1.id=Table2.id

UNION or UNION ALL

SELECT Table1.Order 
FROM Table1, Table2 
WHERE Table2.STATUS = 'R' and Table1.id=Table2.id

I am not sure whether this helped you or not...!! Anyways...

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.