Middle
SQL task: how to retrieve users with names in Cyrillic and Latin, sorted so that Cyrillic comes first, and within groups lexicographically?
sobes.tech AI
Answer from AI
To extract users with names in Cyrillic and Latin scripts, sorted so that Cyrillic comes first, and within groups sorted lexicographically, you can use SQL with a Unicode range check.
Example for PostgreSQL:
SELECT username
FROM users
ORDER BY
CASE
WHEN username ~ '^[\u0400-\u04FF]' THEN 0 -- Cyrillic
ELSE 1 -- Latin and others
END,
username;
Explanation:
- The regular expression
^[\u0400-\u04FF]checks if the name starts with a character in the Cyrillic range. - In
ORDER BY, first sort by this condition (0 — Cyrillic, 1 — others), then lexicographically by the name.
If the database does not support Unicode in regex, you can use a function to check the first character by its code, for example:
ORDER BY
CASE
WHEN ascii(substring(username from 1 for 1)) BETWEEN 192 AND 255 THEN 0
ELSE 1
END,
username
But this is less universal and depends on the encoding.