I have a SQLite database and I want to order my results by ascending order of a String column (name
). I want the null
-valued rows to be last in ascending order.
Moreover, I am doing some filtering on the same column (WHERE name>"previously obtained value"
), which filters out the NULL
-valued rows, which I do not want. Plus, the version of SQLite I’m using (I don’t have control over this) does not support NULLS LAST
. Therefore, to keep it simple I want to use IFNULL(name,"Something")
in my ORDER BY
and my comparison.
I want this "Something"
to be as large as possible, so that my null
-valued rows are always last. I have texts in Japanese and Korean, so I can’t just use "ZZZ"
.
Therefore, I see two possible solutions. First, use the “maximum” character used by SQLite in the default ordering of strings, do you know what this value is or how to obtain it? Second, as the cells can contain any type in SQLite, is there a value of any other type that will always be considered larger than any string?
Example:
+----+-----------------+---------------+ | id | name | othercol | +----+-----------------+---------------+ | 1 | English name | hello | | 2 | NULL | hi | | 3 | NULL | hi hello | | 4 | 暴鬼 | hola | | 5 | NULL | bonjour hello | | 6 | 아바키 | hello bye | +----+-----------------+---------------+
Current request:
SELECT * FROM mytable WHERE othercol LIKE "hello" AND (name,id)>("English name",1) ORDER BY (name,id)
Result (by ids): 6
Problems: NULL names are filtered out because of the comparison, and when I have no comparison they are shown first.
What I think would solve these problems:
SELECT * FROM mytable WHERE othercol LIKE "hello" AND (IFNULL(name,"Something"),id)>("English name",1) ORDER BY (IFNULL(name,"Something"),id)
But I need "Something"
to be larger than any string I might encounter.
Expected result: 6, 3, 5
Advertisement
Answer
Finally found a solution, for anyone looking for a character larger than any other (when I’m posting this, the unicode table might get expanded), here’s your guy:
CAST(x'f48083bf' AS TEXT)
.
Example in my case:
SELECT * FROM mytable WHERE othercol LIKE "hello" AND (IFNULL(name,CAST(x'f48083bf' AS TEXT)),id)>("English name",1) ORDER BY (IFNULL(name,CAST(x'f48083bf' AS TEXT)),id)