Quantcast
Channel: Optimising some SQL to get all rows corresponding to the minimum value of a column - Database Administrators Stack Exchange
Viewing all articles
Browse latest Browse all 2

Answer by Willem Renzema for Optimising some SQL to get all rows corresponding to the minimum value of a column

$
0
0

The documentation provides a couple ways to get what you want, which will perform well.

SELECT TableA.col1, TableA.col2FROM TableAINNER JOIN (    SELECT    MIN(col3) AS col3    FROM TableA    WHERE col4 = 0    AND col5 = 1) lowest_col3_TableAON lowest_col3_TableA.col3 = TableA.col3WHERE TableA.col4=0AND TableA.col5=1

Or

SELECT TableA.col1, TableA.col2FROM TableALEFT OUTER JOIN TableA lower_col3_TableAON lower_col3_TableA.col4 = 0AND lower_col3_TableA.col5 = 1AND lower_col3_TableA.col3 < TableA.col3WHERE TableA.col4=0AND TableA.col5=1AND lower_col3_TableA.col3 IS NULL

For this second query, the last line of AND lower_col3_TableA.col3 IS NULL doesn't necessarily need to be col3, but DOES need to be a column that is defined with NOT NULL. Usually the leftmost part of the primary key is best.


Viewing all articles
Browse latest Browse all 2

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>