Most databases have something like a GREATEST
function, which can be useful some times. At least these databases don't have such a function:
- Derby
- SQL Server
- Sybase ASE
- Sybase SQL Anywhere
For SQL Server and Sybase SQL Anywhere, the function can be simulated using subqueries and UNION ALL
, as can be seen in this question here. An example:
-- SELECT GREATEST(field1, field2, field3) FROM my_table
SELECT (SELECT MAX(c) FROM
(SELECT my_table.field1 AS c UNION ALL
SELECT my_table.field2 UNION ALL
SELECT my_table.field3) T) AS greatest
FROM my_table
But this doesn't work in Sybase ASE. Apparently, the subqueries don't have access to the outer query's my_table
reference. The error I get is
The column prefix 'my_table' does not match with a table name or alias name used in the query. Either the table is not specified in the FROM clause or it has a correlation name which must be used instead
Note, this problem does not appear with Sybase SQL Anywhere. Any idea what's wrong here and how I could re-write the query?
I'd like to avoid
- Stored functions, as I may not have the necessary grants to create them
- Lengthy
CASE
expressions, as the expression length of the combined permutation of all comparisons needed with nestedCASE
expressions is at leastO(n^2)
whenn
is the number of parameters forGREATEST