In this tutorial I will explain how to calculate max and min in sql.
To perform the queries I will use the SQL SELECT query in several examples.
Also, I’m going to show you examples on MAX and SELECT from simpler to advanced so that you can find the solution to your problem.
- How to calculate max in SQL?
- Know the SQL SELECT query
- Using the SQL MAX() function
- Examples of MAX SQL with SELECT
- SQL MAX function example 1
- Example of MAX and GROUP BY
- Advanced example of MAX and HAVING
- SELECT MAXSQL? What else?
How to calculate max in SQL?
To be able to calculate the maximum in SQL you will need to have a couple of clear knowledge:
- How the SELECT SQL query is used
- Know how to use SQL functions and specifically the MAX() function
Know the SQL SELECT query
As a quick review, the structure of a SELECT is:
SELECT columna1, columna2, ... FROM tabla [WHERE condiciones]
Using the SQL MAX() function
The SQL MAX function It is used in the same way as all SQL functions: by calling it by its name together with the parentheses.
The MAX function syntax is:
MAX( columna )
The function MAX calculates the maximum between the values in the column specified. Technically we say that it returns an “aggregate record” since it returns a result row of the calculation among all rows provided.
Knowing this let’s see the examples.
Examples of MAX SQL with SELECT
Now let’s get down to business, let’s see several examples of queries with MAX.
SQL MAX function example 1
The following function would return a row with a column “max_age” with the maximum value among all the rows in the “user” table.
SELECT MAX(edad) as edad_maxima FROM usuario;
Example of MAX and GROUP BY
Now imagine that we want to know what is the maximum age of the students of each course of a university.
We could make use of the following query:
SELECT MAX(edad) as edad_maxima, curso FROM alumnos GROUP BY curso;
Advanced example of MAX and HAVING
Finally I am going to leave you a more advanced query, making use of the max SQL function and the SQL HAVING clause. Specifically, I am going to select those courses that have at least one student who is over the age of 30:
SELECT c.* FROM alumno a INNER JOIN curso c ON a.id_curso = c.id GROUP BY c.id HAVING MAX(a.edad) > 30;
SELECT MAXSQL? What else?
Well I hope this helped you post about SQL MAX function. If so, it would help us a lot if you shared this content or left a comment that helps other users and motivates us to continue publishing.