SQL MAX Function | Return Largest Value in Column

SQL MAX is an inbuilt function in SQL Server. It returns the largest value of a column in a table. It finds the record which has the maximum value in a recordset. In this article, we will discuss the SQL MAX Function. Also, we will discuss an example of using it.

Syntax

SELECT MAX(column_name) FROM table_name WHERE condition;

  • column_name: The column from which to find the maximum value.
  • table_name: The selected table to find from.
  • condition: You can also optionally specify a WHERE condition to specify rows.
SQL MAX Function

Demo Table

For instance, consider the demo table to refer to all the queries in this article.

mysql> SELECT * FROM employees;
+----+--------+--------+------------+-------+
| id | name   | salary | experience | team  |
+----+--------+--------+------------+-------+
|  1 | David  |  20000 |          4 | Alpha |
|  2 | Monica |  25000 |          7 | Beta  |
|  3 | John   |  15000 |          3 | Beta  |
|  4 | Mary   |  18000 |          4 | Gamma |
|  5 | Ross   |  30000 |          6 | Alpha |
+----+--------+--------+------------+-------+

Examples

Let’s consider a few examples of using the MAX Function in SQL.

Example 1: Finding the Maximum Column Value

For instance, if we need to find the maximum salary from our table, we can use the following query:

SELECT MAX(salary) FROM employees;

The above query returns the maximum salary from the table. The output of the query is:

mysql> select MAX(salary) from employees;
+-------------+
| MAX(salary) |
+-------------+
|       30000 |
+-------------+

Example 2: Specifying a Where Condition

Also, you can specify a WHERE Condition in the query. The function will return the maximum value of the selected column from the rows matching the where condition. For instance, consider the following example:

mysql> SELECT MAX(experience) FROM employees WHERE team = 'Alpha';
+-----------------+
| MAX(experience) |
+-----------------+
|               8 |
+-----------------+

Although the maximum experience in the table is 7, the maximum experience from the rows with team Alpha is 6.

Conclusion

In conclusion, we discussed the SQL MAX Function. You can read more about it on the Official Microsoft Documentation. Also, you can read more about SQL on Concatly.

Spread the Knowledge

Leave a Reply

Your email address will not be published. Required fields are marked *