Saturday, September 29, 2012

Find the smallest or largest value in SQL

In Oracle we can use least function to find the smallest one among many values. The number of input variables are flexible. Similarly, to find the largest one among many values, we use greatest function. The following are examples.
select least(0,1,2,3,4,4,5,6,7,9) from dual;

--------------------------
                         0
select greatest(0,1,2,3,4,4,5,6,7,9) from dual;
-----------------------------
                         9
The following example shows that least/greatest functions take multiple columns as inputs and return the result for each row.  Min/max functions  take only one column as parameter and return the result for the all the rows.
select p0, p1,p2, least(p0,p1,p2), greatest(p0,p1,p2) from TBL_TEST_DATA where rownum < 10;

        P0         P1         P2 LEAST(P0,P1,P2) GREATEST(P0,P1,P2)
---------- ---------- ---------- --------------- ------------------
   1086.62    1089.03    1084.38         1084.38            1089.03
   1214.19    1213.58    1200.94         1200.94            1214.19
   1268.42    1263.25    1257.68         1257.68            1268.42
   1505.11    1511.73    1515.61         1505.11            1515.61
    758.84     764.72     753.37          753.37             764.72
   1521.24    1532.53    1528.63         1521.24            1532.53
   1184.88    1181.19    1185.01         1181.19            1185.01
   1260.55    1266.51    1273.23         1260.55            1273.23
    1483.4    1484.26     1469.9          1469.9            1484.26
select min(p0), min(p1), min(p2),  max(p0), max(p1), max(p2)  from MV_SP_VIX_CORR where rownum < 10;

   MIN(P0)    MIN(P1)    MIN(P2)    MAX(P0)    MAX(P1)    MAX(P2)
---------- ---------- ---------- ---------- ---------- ----------
    758.84     764.72     753.37    1521.24    1532.53    1528.63


No comments: