I'm sorting song names from a SQLite database, and I'd like to sort ignoring any leading "The ". So, for example:
1 Labradors are Lovely
2 The Last Starfighter
3 Last Stop before Heaven
This answer solves this need in the simple case:
SELECT name FROM songs
ORDER BY
CASE WHEN instr(lower(name),'the ')=1 THEN substr(name,5)
ELSE name
END
COLLATE NOCASE;
However, I'm already using a complex transformation on the name
column. Combining the two I get this ugly, non-DRY code:
SELECT n, name
FROM songs
ORDER BY
CASE WHEN name GLOB '[0-9]*' THEN 1
ELSE 0
END,
CASE WHEN name GLOB '[0-9]*' THEN CAST(name AS INT)
ELSE CASE WHEN instr(lower(name),'the ')=1 THEN
replace(
replace(
replace(
replace(
substr(name,5),
'.',''
),
'(',''
),
'''',''
),
' ',' '
)
ELSE
replace(
replace(
replace(
replace(name,'.',''),
'(',''
),
'''',''
),
' ',' '
)
END
END
COLLATE NOCASE;
Is there a way to use a variable or something during the query so that I can DRY up the code, and only have all that punctuation-replacement taking place in one location instead of two different case branches?