M
M
MasterCopipaster2021-06-01 20:30:36
SQL
MasterCopipaster, 2021-06-01 20:30:36

How to sort in sql query by two conditions for two selections?

I have a table with this content

id    |guid                                |sort|
------|------------------------------------|----|
239980|                                    |   1|
354533|666a9a7d-b2ed-11eb-8b8b-9c5c8e4f1f67|   0|
354538|                                    |   2|
354540|787a9a7d-b2ed-11eb-8b8b-9c5c8e4f1f67|   1|


I want to sort the records by the sort field, but so that the records with guid != NULL are sorted by their sort and are always at the top and the rest are below.
In short, I want to start like this
SELECT id,guid,sort from images where model_id = 102188 and guid is not null order BY sort DESC;


id    |guid                                |sort|
------|------------------------------------|----|
354540|787a9a7d-b2ed-11eb-8b8b-9c5c8e4f1f67|   1|
354533|666a9a7d-b2ed-11eb-8b8b-9c5c8e4f1f67|   0|


Then so

SELECT id,guid,sort from images where model_id = 102188 and guid is null order BY sort DESC;

id    |guid|sort|
------|----|----|
354538|    |   2|
239980|    |   1|


I need to somehow combine these two queries, if it's easier to glue their result so that it would turn out as a result

id    |guid                                |sort|
------|------------------------------------|----|
354540|787a9a7d-b2ed-11eb-8b8b-9c5c8e4f1f67|   1|
354533|666a9a7d-b2ed-11eb-8b8b-9c5c8e4f1f67|   0|
354538|                                    |   2|
239980|                                    |   1|

Please note that the records with the guid field are sorted first, and then those that do not.

I thought to combine queries using UNION or UNION ALL but the trouble is that it doesn't work that way
SQL Error [1221] [HY000]: Incorrect usage of UNION and ORDER BY
when using UNION, you cannot use ORDER BY - actually, how can I do what I want?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Rsa97, 2021-06-01
@MasterCopipaster

ORDER BY `guid` IS NULL, `sort` DESC

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question