How to select the row which matches a complex WHERE clause and has the minimum value in a given column?

StackOverflow https://stackoverflow.com/questions/22135081

  •  19-10-2022
  •  | 
  •  

Question

I need to select a row from a table which must satisfy the following conditions:

  • It needs to match a quite complex WHERE clause
  • It needs to have the minimum value in column X

Thus far, the only working solution I have is this:

SELECT <columns>
FROM <table>
WHERE <complex WHERE clause>
AND <columnX> = (SELECT MIN(<columnX>) FROM <table> WHERE <same WHERE clause as before>)

This strikes me as quite ugly and cumberstome, having to repeat the same (complex) WHERE clause two times.

Do you know any better way to achieve this?

Was it helpful?

Solution 3

Turned out the easiest solution was ordering...

SELECT TOP 1 <columns>
FROM <table>
WHERE <complex WHERE clause>
ORDER BY <ColumnX> ASC

OTHER TIPS

Correct me if I'm wrong, I would use a CTE (Common Table Expression) to write the complex query and have the where clause reference to it.

Hope that helps.

You could define a view or temporary table, the performance difference varying heavily on the actual problem (you could try both):

CREATE VIEW v AS
SELECT <columns>
FROM <table>
WHERE <complex WHERE clause>;

SELECT * FROM v
WHERE <columnX> = SELECT min(<columnX> FROM v);

Or even better, taking advantage of the window functions:

SELECT *
FROM (
    SELECT
        <columns>,
        MIN(<columnX>) OVER () AS minX
    FROM <table>
    WHERE <complex WHERE clause>
) t
WHERE <columnX> = minX;

http://sqlfiddle.com/#!3/0a52b/6/0

This latter should certainly read the table only once.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top