Wizard
Wizard

Reputation: 11265

SQL Union sort by Union

I have query

SELECT id, name 
  FROM users 
  WHERE id !=2 
UNION 
SELECT id, name 
  FROM users2 
  WHERE id != 3;

I want that sort will be, 1 union orders + 2 union it's possible ?

Upvotes: 0

Views: 200

Answers (2)

Rahul
Rahul

Reputation: 77866

You can as well do like

(SELECT id, name 
  FROM users 
  WHERE id !=2
ORDER BY id)
UNION ALL
(SELECT id, name 
  FROM users2 
  WHERE id != 3
  ORDER BY id);

Upvotes: 1

bobthedeveloper
bobthedeveloper

Reputation: 3783

Add a column to order on

SELECT id, name, 1 as unionOrder FROM users WHERE id !=2 
UNION 
SELECT id, name, 2 as unionOrder FROM users2 WHERE id != 3

ORDER BY unionOrder 

Upvotes: 2

Related Questions