I want to write a query which will sort the results based on multiple conditions.
Please refer to following dummy table
| name | domain |
|---|---|
| Apple | gmail |
| .Apple2 | yahoo |
| _Apple3 | xyz |
| Apple4 | zyx |
| Ball | abc |
| .Ball2 | efg |
| _Ball3 | gmail |
| Ball4 | yahoo |
| Bear | xyz |
| Cat | abc |
I want to sort above table
1 - By Known domain yahoo followed by gmail then rest.
So I want to divide result rows in three parts.
1st section with rows having yahoo as domain then in 2nd section rows with gmail domain at last rest of the rows.
2 - Alphabetically and all special characters at the end.
Every section should be further sorted alphabetically on name field with special characters at the end.
Result should look like following table.
| name | domain |
|---|---|
| Ball4 | yahoo |
| .Apple2 | yahoo |
| Apple | gmail |
| _Ball3 | gmail |
| Apple4 | zyx |
| Ball | abc |
| Bear | xyz |
| Cat | abc |
| _Apple3 | xyz |
| .Ball2 | efg |
I have managed to sort result alphabetically with special symbols at bottom with following query but I am not able to get the 1st part of sorting correct i.e sort by known domain.
SELECT * FROM table1
ORDER BY
CASE WHEN name GLOB '[A-Za-z]*'
THEN name
ELSE '~' || name
END COLLATE NOCASE