HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

Is using of subqueries more efficient than using Limit offset and order by in MySQL?

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
orderoffsetlimitthanefficientmoremysqlusingandsubqueries

Problem

For instance, we have a problem of finding the employee with the second highest salary in the table.
This is my table

id  name    dept    salary
1   Ram     HR      10000
2   Amrit   MRKT    20000
3   Ravi    HR      30000
4   Nitin   MRKT    40000
5   Varun   IT      50000


Then I would write a subquery like this.

select e_name,salary from employee
    where salary = (select max(salary) from employee
                    where salary <> (select max(salary) from employee));


And I would use limit and offset like this:

select e_name, salary from employee order by salary desc limit 1 offset 1;


Which of the following would be more efficient? and why?

Solution

There's a lot of variables when it comes to performance and query tuning, so there's no guaranteed answer to which one will be more performant for your data at any given time without testing and observing their query plans.

But in general, the second example using LIMIT and OFFSET is likely to be more efficient since it only queries the employee table once as opposed to three times in your first example.

Context

StackExchange Database Administrators Q#294650, answer score: 6

Revisions (0)

No revisions yet.