By
Published: 27 Jun 2005
I have a table in which I do a SELECT DISTINCT on a date column. I am trying to write a query that returns only one value (MAX value) if there are more than one distinct dates in that column. What is the most efficient way of writing this SQL query?
Well, I'm not sure about the "most efficient" way, since efficiency in general depends on which database system you're using, whether there are indexes, and so on.
Your query would be something like this:
select case when ( select count(distinct datecol)
from yourtable )
> 1
then ( select max(datecol)
from yourtable )
else null
end
Notice that if there are not more than 1 distinct values in datecol, the query returns NULL. You didn't say what you wanted in that situation.
Dig Deeper on Oracle and SQL
Read SQL expert Rudy Limeback's advice for counting combinations in a table with SQL's GROUP BY clause
Continue Reading
Read about the Mimer Validator, a tool used to verify your SQL code, in this tip from SQL expert Rudy Limeback.
Continue Reading
Read an example of an SQL case expression from our SQL expert Rudy Limeback.
Continue Reading