MariaDB: MAX Function
This MariaDB tutorial explains how to use the MariaDB MAX function with syntax and examples.
Description
The MariaDB MAX function returns the maximum value of an expression.
Syntax
The syntax for the MAX function in MariaDB is:
SELECT MAX(aggregate_expression) FROM tables [WHERE conditions];
OR the syntax for the MAX function when grouping the results by one or more columns is:
SELECT expression1, expression2, ... expression_n, MAX(aggregate_expression) FROM tables [WHERE conditions] GROUP BY expression1, expression2, ... expression_n;
Parameters or Arguments
- expression1, expression2, ... expression_n
- Expressions that are not encapsulated within the MAX function and must be included in the GROUP BY clause at the end of the SQL statement.
- aggregate_expression
- This is the column or expression from which the maximum value will be returned.
- tables
- The tables that you wish to retrieve records from. There must be at least one table listed in the FROM clause.
- WHERE conditions
- Optional. These are conditions that must be met for the records to be selected.
Applies To
The MAX function can be used in the following versions of MariaDB:
- MariaDB 10
Example - With Single Expression
Let's look at some MariaDB MAX function examples and explore how to use the MAX function in MariaDB.
First, we'll go though an example of how to use the MAX function with a single expression in MariaDB.
For example:
SELECT MAX(file_size) AS "Largest File" FROM pages WHERE site_name = 'TechOnTheNet.com';
In this MAX function example, we will find the maximum value for the file_size column where the site_name is 'TechOnTheNet.com''. We've aliased the MAX(file_size) expression as "Largest File". As a result, "Largest File" will display as the column title when the result set is returned.
Example - Using GROUP BY
Next, let's look at how to use the GROUP BY clause with the MAX function in MariaDB.
If you are returning columns that are no encapsulated in the MAX function, you must use the GROUP BY clause.
For example:
SELECT site_id, MAX(file_size) AS "Largest File" FROM pages where site_id < 50 GROUP BY site_id;
In this MAX function example, we must use a GROUP BY clause because the site_id field is not encapsulated in the MAX function. The site_id column must, herefore, be listed in the GROUP BY section at the end of the SQL statement.
Advertisements