I’m still learning SQL so I was wondering if there is a better way of doing the following.
I need to get row data for the lowest and highest values in a column (lets call it columnA).
I would use:
SELECT *
FROM table
ORDER BY columnA
DESC LIMIT 1
Problem is I get only one result due to the LIMIT 1 but there may be identical lowest / highest values in ColumnA that have different values in the other columns. I need those other rows too.
There is SELECT(MAX) but I believe that will also only produce one row of data.
The ways I can think do this are by putting the highest / lowest columnA values into a variable and then back into a second query OR use a LEFT JOIN on alias tables to do this in single query but is there any more direct method?
The simplest way is to perform a sub-query:
You can even query both extremes at once:
I haven’t tested the next one (don’t know if MySQL supports
UNIONinsub-queries), but it should work as well, might be a bit more
efficient (depending on your data size).