Reputation: 2712
I've read many articles regarding how to use a row number in SQLite but none of them gave me the answer I need. I know how to select row number using this query:
SELECT (SELECT COUNT() FROM table WHERE title < t.title OR (title = t.title AND id<t.id)) as rowIndex, t.title FROM table AS t ORDER BY t.title;
but if I add COLLATE NOCASE
(which I need) at the end of the query then the result is completely different.
Upvotes: 4
Views: 21693
Reputation: 37
SELECT (SELECT COUNT(*)
FROM main AS t2
WHERE t2.col1 < t1.col1) +
(SELECT COUNT(*) FROM main AS t3
WHERE t3.col1 = t1.col1 AND t3.col1 < t1.col1)
AS rowNum, * FROM
Table_name t1 WHERE rowNum=0 ORDER
BY t1.col1 ASC
Upvotes: 0
Reputation: 2982
Your query contains an error: the alias "ja" is not defined.
Try it like this:
SELECT
( SELECT COUNT(*) + 1
FROM "table"
WHERE title < t.title OR (title = t.title AND id<t.id)
) as rowIndex,
t.title
FROM "table" t
ORDER BY t.title;
However, be aware that this sub-query construction will not scale well. For large datasets you might want to create a temp table and use ROWID instead (as discussed, for example, here).
EDIT: Test with COLLATE NOCASE:
CREATE TABLE "table" (id INTEGER, title TEXT COLLATE NOCASE);
INSERT INTO "table" VALUES
(1, "Book A"),
(2, "Book b"),
(3, "Book C"),
(4, "Book B"),
(5, "Book a");
The query yields:
1|Book A
2|Book a
3|Book b
4|Book B
5|Book C
EDIT:
If you do not want to declare the column COLLATE NOCASE, you have to make sure that you use COLLATE in the ORDER BY part as well as in the subquery:
SELECT
( SELECT COUNT(*) + 1
FROM "table"
WHERE title < t.title COLLATE NOCASE OR (title = t.title COLLATE NOCASE AND id<t.id)
) as rowIndex,
t.title
FROM "table" t
ORDER BY t.title COLLATE NOCASE;
Upvotes: 4