[mysql] MAX function in where clause mysql

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.

This question is related to mysql sql max greatest-n-per-group

The answer is


Use a subselect:

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

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


You are using word 'max' as an alias for your column. Try to:

MAX(id) as mymax ... WHERE ID - mymax

SELECT firstName, Lastname, MAX(id) as max WHERE YOUR_CONDITIONS_HERE HAVING id=max(id) 

Some Mysql versions disallow 'limit' inside of a sub select. My answer to you (and me in the future) would be to use groups

select firstName,Lastname,id 
where {whatever}
group by id
having max(id)

This allows you to return whatever you want in the select area, without having an aggregate field.


This query should give you back the data you want. Replace foo with the table name you are using.

SQL Query:

select firstName,Lastname, id 
from foo 
having max(id) = id 

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.


The syntax you have used is incorrect. The query should be something like:

SELECT column_name(s) FROM tablename WHERE id = (SELECT MAX(id) FROM tablename)

Do you want the first and last name of the row with the largest id?

If so (and you were missing a FROM clause):

SELECT firstname, lastname, id
FROM foo
ORDER BY id DESC
LIMIT 1;

Examples related to mysql

Implement specialization in ER diagram How to post query parameters with Axios? PHP with MySQL 8.0+ error: The server requested authentication method unknown to the client Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver' phpMyAdmin - Error > Incorrect format parameter? Authentication plugin 'caching_sha2_password' is not supported How to resolve Unable to load authentication plugin 'caching_sha2_password' issue Connection Java-MySql : Public Key Retrieval is not allowed How to grant all privileges to root user in MySQL 8.0 MySQL 8.0 - Client does not support authentication protocol requested by server; consider upgrading MySQL client

Examples related to sql

Passing multiple values for same variable in stored procedure SQL permissions for roles Generic XSLT Search and Replace template Access And/Or exclusions Pyspark: Filter dataframe based on multiple conditions Subtracting 1 day from a timestamp date PYODBC--Data source name not found and no default driver specified select rows in sql with latest date for each ID repeated multiple times ALTER TABLE DROP COLUMN failed because one or more objects access this column Create Local SQL Server database

Examples related to max

Min and max value of input in angular4 application numpy max vs amax vs maximum mongodb how to get max value from collections Python find min max and average of a list (array) Max length UITextField How to find the highest value of a column in a data frame in R? MAX function in where clause mysql Check if all values in list are greater than a certain number How do I get the max and min values from a set of numbers entered? SQL: Group by minimum value in one field while selecting distinct rows

Examples related to greatest-n-per-group

How to select the rows with maximum values in each group with dplyr? MAX function in where clause mysql Pandas get topmost n records within each group SQL Left Join first match only Select info from table where row has max date FORCE INDEX in MySQL - where do I put it? GROUP BY having MAX date How can I select rows with most recent timestamp for each key value? Select row with most recent date per user How to select id with max date group by category in PostgreSQL?