How can I use max() function in where clause of a mysql query, I am trying:
select firstName,Lastname,MAX(id) as max where id=max;
this is giving me an error:
Unknown column 'max' in 'where clause'
Any Help? Thanks in advance.
MySQL MAX() Function with WHERE ClauseThe WHERE clause allows us to filter the result from the selected records. The following statement finds the maximum income in all rows from the employee table. The WHERE clause specifies all those rows whose emp_age column is greater than 35.
Overview. The MAX() function is used with the WHERE clause to gain further insights from our data. In SQL, the MAX() function computes the highest or maximum value of numeric values in a column.
You can use ORDER BY clause or aggregate function MAX() to select the maximum value.
But yes, you can use two WHERE.
We can't reference the result of an aggregate function (for example MAX()
) in a WHERE
clause of the same SELECT
.
The normative pattern for solving this type of problem is to use an inline view, something like this:
SELECT t.firstName , t.Lastname , t.id FROM mytable t JOIN ( SELECT MAX(mx.id) AS max_id FROM mytable mx ) m ON m.max_id = t.id
This is just one way to get the specified result. There are several other approaches to get the same result, and some of those can be much less efficient than others. Other answers demonstrate this approach:
WHERE t.id = (SELECT MAX(id) FROM ... )
Sometimes, the simplest approach is to use an ORDER BY with a LIMIT. (Note that this syntax is specific to MySQL)
SELECT t.firstName , t.Lastname , t.id FROM mytable t ORDER BY t.id DESC LIMIT 1
Note that this will return only one row; so if there is more than one row with the same id value, then this won't return all of them. (The first query will return ALL the rows that have the same id value.)
This approach can be extended to get more than one row, you could get the five rows that have the highest id values by changing it to LIMIT 5
.
Note that performance of this approach is particularly dependent on a suitable index being available (i.e. with id
as the PRIMARY KEY or as the leading column in another index.) A suitable index will improve performance of queries using all of these approaches.
Use a subselect:
SELECT row FROM table WHERE id=( SELECT max(id) FROM table )
Note: ID must be unique, else multiple rows are returned
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With