3

I want to sort column2 based on Column1 values. I want split column1 data based on NULL value. The final query result will be displayed on evaluating the values in the column1

   Column1    Column2 
    NULL         100
    NULL          60
    NULL          90
    10            22
    20            40
    05            35
    15            20
    40            10
    30            25
    20            30

Would become:

   Column1     Column2 
    20            40
    05            35
    20            30
    30            25
    10            22
    15            20
    40            10
    NULL         100
    NULL          90
    NULL          60

Thanks
1
  • Which DBMS are you using? Postgres? Oracle? Commented Feb 23, 2017 at 9:48

3 Answers 3

5

You can use case in your order by clause like this:

Select * from t
Order by case when column1 is null then 1 else 0 end, column2 desc
Sign up to request clarification or add additional context in comments.

Comments

2

Use a case in your order by

ORDER BY case when column1 is null then 1 else 0 end, column2 desc

Comments

2
SELECT 1 AS Grp, column2
FROM T 
WHERE column1 IS NOT NULL
UNION ALL
SELECT 2 AS Grp, column2 
FROM T 
WHERE column1 IS NULL
ORDER BY Grp, column2;

This an alternative to GurV's approach, where this can actually benefit from indexes.

GurV's approach:

enter image description here

Union approach:

enter image description here

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.