0

I'm fairly new to Oracle SQL, but already it's logic is beginning to confuse me. I'm trying to select all columns from a table where a particular column PRICE has the minimum value.

This works:

SELECT MIN(PRICE) FROM my_tab;

This returns me the minimum value. But why can't I select all the columns in that row? The following won't work:

SELECT * FROM my_tab WHERE PRICE = MIN( PRICE );

What am I missing here? Cheers folks!

*EDIT*

Here is the full code I'm having trouble with:

SELECT * FROM ( SELECT c.NAME, o.* FROM customers c JOIN customer_orders o ON c.CUST_NBR = o.CUST_NBR ) AS t WHERE t.PRICE = ( SELECT MIN( t.PRICE) FROM t );

David Aldridge
  • 51,479
  • 8
  • 68
  • 96
Boon
  • 1,073
  • 1
  • 16
  • 42

3 Answers3

2
SELECT * FROM TABLE WHERE PRICE = (SELECT MIN(PRICE) FROM TABLE)

--Edited 

WITH 
TABLE AS 
(QUERY) 
SELECT * FROM TABLE
WHERE PRICE = (SELECT MIN(PRICE) FROM TABLE)
Santhosh
  • 1,771
  • 1
  • 15
  • 25
  • This doesn't work. The table I'm selecting from is already from a select statement. Will that cause a problem? I posted my code in a comment already but for some reason it was removed – Boon Apr 04 '13 at 15:15
0

You can also use a subquery to get the result:

select t1.*
from my_tab t1
inner join
(
  SELECT MIN(PRICE) MinPrice
  FROM my_tab
) t2
  on t1.price = t2.minprice
Taryn
  • 242,637
  • 56
  • 362
  • 405
0

See previous SO question, and especially answer by "Vash" which is best for your purposes. Note that you probably want to avoid a subselect since Oracle may be smart enough to use an index on the price if available to look at only one record.

Most databases, but apparently not Oracle, have either TOP 1 or LIMIT clauses for questions like these.

Community
  • 1
  • 1
Andrew Lazarus
  • 18,205
  • 3
  • 35
  • 53