Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aggregate functions in WHERE clause in SQLite

Simply put, I have a table with, among other things, a column for timestamps. I want to get the row with the most recent (i.e. greatest value) timestamp. Currently I'm doing this:

SELECT * FROM table ORDER BY timestamp DESC LIMIT 1

But I'd much rather do something like this:

SELECT * FROM table WHERE timestamp=max(timestamp)

However, SQLite rejects this query:

SQL error: misuse of aggregate function max()

The documentation confirms this behavior (bottom of page):

Aggregate functions may only be used in a SELECT statement.

My question is: is it possible to write a query to get the row with the greatest timestamp without ordering the select and limiting the number of returned rows to 1? This seems like it should be possible, but I guess my SQL-fu isn't up to snuff.

like image 204
Kyle Cronin Avatar asked Dec 24 '08 00:12

Kyle Cronin


People also ask

Can you use aggregate functions in WHERE clause?

An aggregate function can be used in a WHERE clause only if that clause is part of a subquery of a HAVING clause and the column name specified in the expression is a correlated reference to a group. If the expression includes more than one column name, each column name must be a correlated reference to the same group.

Can we use WHERE in GROUP BY clause?

GROUP BY Clause is utilized with the SELECT statement. GROUP BY aggregates the results on the basis of selected column: COUNT, MAX, MIN, SUM, AVG, etc. GROUP BY returns only one result per group of data. GROUP BY Clause always follows the WHERE Clause.

Can we use aggregate function in WHERE clause in Oracle?

Aggregate functions can appear in select lists and in ORDER BY and HAVING clauses. They are commonly used with the GROUP BY clause in a SELECT statement, where Oracle Database divides the rows of a queried table or view into groups.


1 Answers

SELECT * from foo where timestamp = (select max(timestamp) from foo)

or, if SQLite insists on treating subselects as sets,

SELECT * from foo where timestamp in (select max(timestamp) from foo)
like image 155
SquareCog Avatar answered Oct 03 '22 00:10

SquareCog