Sqlite Max Function

SQLite: max Function

This SQLite post explains how to use the SQLite max function with syntax and examples.

Description

The SQLite max function returns the maximum value of an expression.

Syntax

The syntax for the max function in SQLite 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 SQLite:

  • SQLite 3.8.6, SQLite 3.8.x, SQLite 3.7.x, SQLite 3.6.x

Example - With Single Expression

Let's look at some SQLite max function examples and explore how to use the max function in SQLite.

For example, you might wish to know how the maximum salary of all employees.

SELECT max(salary) AS "Highest Salary"
FROM employees;

In this max function example, we've aliased the max(salary) expression as "Highest Salary".

Example - Using GROUP BY

In some cases, you will be required to use the GROUP BY clause with the max function.

For example, you could also use the max function to return the city and the maximum salary in th at city where the state is 'CA'.

SELECT city, max(salary) AS "Highest salary"
FROM employees
WHERE state = 'CA'
GROUP BY city;

Because you have listed one column in your SELECT statement that is not encapsulated in the max function, you must use a GROUP BY clause. The city field must, therefore, be listed in the GROUP BY section.