Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MAX function in where clause mysql [duplicate]

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.

like image 549
user3176971 Avatar asked Mar 20 '14 15:03

user3176971


People also ask

Can we use Max in WHERE clause in MySQL?

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.

Can Max function be used in WHERE clause?

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.

How do I SELECT the highest number in MySQL?

You can use ORDER BY clause or aggregate function MAX() to select the maximum value.

Can you use WHERE clause twice in SQL?

But yes, you can use two WHERE.


2 Answers

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.

like image 153
spencer7593 Avatar answered Oct 23 '22 12:10

spencer7593


Use a subselect:

SELECT row  FROM table  WHERE id=(     SELECT max(id) FROM table ) 

Note: ID must be unique, else multiple rows are returned

like image 21
Fabian Bigler Avatar answered Oct 23 '22 13:10

Fabian Bigler