
For an instructor lead, in-depth look at learning SQL click below.
SQL (Structured Query Language) is used in managing data in relational databases. Often you might want to find the highest or the lowest value within a table and SQL has built-in functions to help you with this task. These functions are called MAX and MIN.
Finding the Highest Value with MAX
MAX function returns the highest value in a column.
|
1 2 3 4 |
SELECT MAX(column_name) FROM table_name; |
In this example, the SQL statement will find the highest value in the “column_name” from the “table_name”.
Example
Let’s consider a table “Sales”, which has a column “Amount”. If you want to get the highest “Amount”, you will need to use the MAX function as follows:
|
1 2 3 4 |
SELECT MAX(Amount) FROM Sales; |
Using MAX with WHERE clause
The MAX function can also be used with the WHERE clause to find the highest value in a column that meet certain condition. For instance if you wanted to find the highest sale in the year 2020, your query would be:
|
1 2 3 4 5 |
SELECT MAX(Amount) FROM Sales WHERE Year =2020; |
Finding the Lowest Value with MIN
The MIN function in SQL is used to find the lowest value in a column.
|
1 2 3 4 |
SELECT MIN(column_name) FROM table_name; |
This SQL statement will find the lowest value in the “column_name” from the “table_name”.
Example
Using the same “Sales” table from the above example. If we want to find the sale with the lowest “Amount”, you can use the MIN function as follows:
|
1 2 3 4 |
SELECT MIN(Amount) FROM Sales; |
Using MIN with WHERE clause
The MIN function can also be used with the WHERE clause to find the lowest value in a column that meet certain condition. For example, if we want to find the lowest sale in the year 2020, the SQL statement would look like this:
|
1 2 3 4 5 |
SELECT MIN(Amount) FROM Sales WHERE Year =2020; |
By using the MAX and MIN functions, you can easily find the highest and lowest values in a column in SQL. As you can see, the possibilities are endless when it comes to data analysis with SQL.
