How to use Set Operator MINUS to Select Rows with Max Value In SQL

To retrieve unique rows from the first query that do not appear in the second query using the MINUS set operator in SQL:

Query:

SELECT * FROM Teacher
MINUS
SELECT t1.* FROM Teacher t1, Teacher t2
WHERE t1.Salary < t2.Salary;

Output:

Using Set Operator MINUS

Explanation:

Like the previous subquery, we’ll find the row with a salary less than that of any other teacher’s salary. Then we will do the set difference operation of the table that we have found (Rows not having maximum salary) on Teacher table to find the complement of table which we found to find the rows having a maximum salary.

How to Select Row With Max Value on a Column in SQL?

SQL is a powerful language for managing and handling relational databases. A common query requirement in relational databases is to get rows with the max value in a particular column. Here, we’ll look at different ways to do this, depending on different situations and database environments.

In this article, we will see SQL queries to select row with maximum value in one column.

Similar Reads

Demo SQL Database

Create a table “Teacher” given below which will be used in the examples below:...

Methods to Select Rows with Maximum Value in a Column in SQL

There are several methods to select rows with maximum value in a column in SQL like:...

1. Using Aggregate Function to Select Rows with Max Value

It is probably the easiest way to solve the problem. Here we’ll use the built-in aggregate function MAX....

2. Using Keyword ALL to Select Rows with Max Value

To select rows where a specific column value is greater than all values in the same column using the ALL keyword in SQL:...

3. Using Keyword NOT EXISTS to Select Rows with Max Value

Here we will use the modified definition of maximum – ‘Maximum Salary will not be less than any other salary’....

4. Using NOT IN to Select Rows with Max Value

Its logic is similar to the previous query but simpler to understand as the subquery is independent and not correlated....

5. Using Set Operator MINUS to Select Rows with Max Value

To retrieve unique rows from the first query that do not appear in the second query using the MINUS set operator in SQL:...

6. Using Left Outer Join to Select Rows with Max Value

To retrieve all records from the left table and matching records from the right table using a LEFT OUTER JOIN in SQL:...

Conclusion

Selecting rows with the maximum value in a column is a common SQL task, and by utilizing effective sorting and column organization, you can enhance the readability and usability of your query results....