I have the below SQL that takes only data from the Name column up to the point where a space or hyphen appears. I would like to order the results by the output of the case statement but can’t find a way to do it.
select
case
when strpos("Name",' ') > 0 then substr("Name", 0, strpos("Name", ' '))
when strpos("Name",'-') > 0 then substr("Name", 0, strpos("Name", '-'))
else "Name"
end as StrippedName
from myTable
order by "StrippedName"
2
Answers
You could use a subquery:
What you’re doing is perfectly fine as long as you double-quote the name of the
case
result in both theselect
list and theorder by
. Mismatching the quotes makes thecase
produce a column namedstrippedname
, whileorder by
looks for aStrippedName
and doesn’t find it, throwing anIf you drop the quotes in both places or use them in both, it’ll work just fine: demo at db<>fiddle
A reminder from the doc on PostgreSQL lexical structure:
You can also use a column position instead of its name:
order by 1
It’s possible to reduce your entire
case
down to a single substring with a POSIX regular expression:It’s looking for a sequence of characters that aren’t a hyphen
, so it’ll return everything up to the first position of either (or the whole thing if neither is found). Using a
-
or a space+
rather than a*
makes it skip leading delimiters, looking for non-empty matches.