473,626 Members | 3,392 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

selecting a column according to a minimum

Take a look at the following example:

table T(i INTEGER, j INTEGER)

I want to get the value of i where j is minimal and some conditions apply.

(1)
SELECT i FROM T
WHERE [condition]
AND j
IN (SELECT min(j) FROM T WHERE [condition])

The best would be if such a syntax was allowed (which it isn't):
SELECT i, min(j) FROM T WHERE [condition]

How can I rewrite the SELECT statement in (1) such that [condition] doesn't
have to be typed in twice? Or how can I achieve the same thing in some other
way? (I am open to other solutions as well as long as they are inside the
limits of Oracle PL/SQL.)
Jul 19 '05 #1
8 12570
SELECT i FROM
(SELECT MIN(j) OVER() as minj, j , i FROM T
WHERE [condition]) AS X WHERE minj = j

Whether that is faster or slower than your original depends on the
Oracle's internals which I don't know.

Cheers
Serge
Jul 19 '05 #2
"Agoston Bejo" <gu***@freemail .hu> wrote:
Take a look at the following example:

table T(i INTEGER, j INTEGER)

I want to get the value of i where j is minimal and some conditions apply.

(1)
SELECT i FROM T
WHERE [condition]
AND j
IN (SELECT min(j) FROM T WHERE [condition])

The best would be if such a syntax was allowed (which it isn't):
SELECT i, min(j) FROM T WHERE [condition]

How can I rewrite the SELECT statement in (1) such that [condition] doesn't
have to be typed in twice? Or how can I achieve the same thing in some other
way? (I am open to other solutions as well as long as they are inside the
limits of Oracle PL/SQL.)

Will this do what you want?

Select i.min(j) from T
where [condition].
GROUP BY i;


Jul 19 '05 #3
Turkbear <jo****@dot.spa mfree.com> wrote:
"Agoston Bejo" <gu***@freemail .hu> wrote:
Take a look at the following example:

table T(i INTEGER, j INTEGER)

I want to get the value of i where j is minimal and some conditions apply.

(1)
SELECT i FROM T
WHERE [condition]
AND j
IN (SELECT min(j) FROM T WHERE [condition])

The best would be if such a syntax was allowed (which it isn't):
SELECT i, min(j) FROM T WHERE [condition]

How can I rewrite the SELECT statement in (1) such that [condition] doesn't
have to be typed in twice? Or how can I achieve the same thing in some other
way? (I am open to other solutions as well as long as they are inside the
limits of Oracle PL/SQL.)

Will this do what you want?

Select i.min(j) from T
where [condition].
GROUP BY i;

No it won't I now realize..It will return all i and, for each i, the Min(j) - the OP wants only those i that have as j the
min(j).
value.

Sorry...

Jul 19 '05 #4
Actually, here is what I could come up with:

select i from
(SELECT i, j FROM T WHERE [condition] ORDER BY j )
WHERE ROWNUM = 1

Is this very inefficient?

"Agoston Bejo" <gu***@freemail .hu> wrote in message
news:cl******** **@news.caesar. elte.hu...
Take a look at the following example:

table T(i INTEGER, j INTEGER)

I want to get the value of i where j is minimal and some conditions apply.

(1)
SELECT i FROM T
WHERE [condition]
AND j
IN (SELECT min(j) FROM T WHERE [condition])

The best would be if such a syntax was allowed (which it isn't):
SELECT i, min(j) FROM T WHERE [condition]

How can I rewrite the SELECT statement in (1) such that [condition] doesn't have to be typed in twice? Or how can I achieve the same thing in some other way? (I am open to other solutions as well as long as they are inside the
limits of Oracle PL/SQL.)

Jul 19 '05 #5
"Agoston Bejo" <gu***@freemail .hu> wrote in message news:<cl******* ***@news.caesar .elte.hu>...
Actually, here is what I could come up with:

select i from
(SELECT i, j FROM T WHERE [condition] ORDER BY j )
WHERE ROWNUM = 1

Is this very inefficient?


According to oracle doc the rownum is computed before the "order by" statement
is applied.

Perhaps better:

select i,j from
(select i,j,row_number( ) over (order by j) rn)
where rn=1;

Bye
Martin
Jul 19 '05 #6
Martin Dachselt wrote:
"Agoston Bejo" <gu***@freemail .hu> wrote in message news:<cl******* ***@news.caesar .elte.hu>...
Actually, here is what I could come up with:

select i from
(SELECT i, j FROM T WHERE [condition] ORDER BY j )
WHERE ROWNUM = 1

Is this very inefficient?
According to oracle doc the rownum is computed before the "order by" statement
is applied.


Not if the order by is in a inline view:

baer@DEMO10G>cr eate table test (i integer, j integer);

Table created.

baer@DEMO10G>be gin
2 for x in 1..100 loop
3 insert into test values (x, 100-x);
4 end loop;
5 end;
6 /

PL/SQL procedure successfully completed.

baer@DEMO10G>co mmit;

Commit complete.

baer@DEMO10G>se lect i from (select i,j from test order by j)
2 where rownum=1;

I
----------
100

baer@DEMO10G>se lect min (j) from test;

MIN(J)
----------
0

baer@DEMO10G>se lect i from test where j=0;

I
----------
100


Perhaps better:

select i,j from
(select i,j,row_number( ) over (order by j) rn)
where rn=1;

Not without additional input for the optimizer:

baer@DEMO10G>se lect i,j from
2 (select i,j,row_number( ) over (order by j) rn from test)
3* where rn=1
Execution Plan
----------------------------------------------------------
0 SELECT STATEMENT Optimizer=CHOOS E (Cost=3 Card=100 Bytes=390
0)

1 0 VIEW (Cost=3 Card=100 Bytes=3900)
2 1 WINDOW (SORT PUSHED RANK) (Cost=3 Card=100 Bytes=500)
3 2 TABLE ACCESS (FULL) OF 'TEST' (TABLE) (Cost=2 Card=100
Bytes=500)


baer@DEMO10G>se lect i from (select i,j from test order by j) where rownum=1;

Execution Plan
----------------------------------------------------------
0 SELECT STATEMENT Optimizer=CHOOS E (Cost=3 Card=1 Bytes=13)
1 0 COUNT (STOPKEY)
2 1 VIEW (Cost=3 Card=100 Bytes=1300)
3 2 SORT (ORDER BY STOPKEY) (Cost=3 Card=100 Bytes=500)
4 3 TABLE ACCESS (FULL) OF 'TEST' (TABLE) (Cost=2 Card=1
00 Bytes=500)


Note the appearence of STOPKEY: The optimizer nows that with rownum=XY
you will likely not take all of the result. This might lead the optimizer
to favour a first_rows plan.

Regards,

Holger
Jul 19 '05 #7
>
baer@DEMO10G>se lect i from test where j=0;

I
----------
100
Yeah, you are right. Note the appearence of STOPKEY: The optimizer nows that with rownum=XY
you will likely not take all of the result. This might lead the optimizer
to favour a first_rows plan.

Strange: costs and execution time seems bo be equal, even for big
tables.
I thought the optimizer is guessing disk and cpu usage.

select * from (
select id,to_char(date time,'yyyy-mm-dd hh24:mi:ss') from fdetailrecord
order by id
) where rownum < 5;

Execution Plan
----------------------------------------------------------
0 SELECT STATEMENT Optimizer=CHOOS E (Cost=82560 Card=4 Bytes=2
10937680)

1 0 COUNT (STOPKEY)
2 1 VIEW (Cost=82560 Card=8789070 Bytes=210937680 )
3 2 SORT (ORDER BY STOPKEY) (Cost=82560 Card=8789070 Bytes
=123046980)

4 3 TABLE ACCESS (FULL) OF 'FDETAILRECORD' (Cost=61711 C
ard=8789070 Bytes=123046980 )
select * from (
select id,to_char(date time,'yyyy-mm-dd hh24:mi:ss'),ro w_number() over
(order by id) rn from fdetailrecord
) where rn < 5;

Execution Plan
----------------------------------------------------------
0 SELECT STATEMENT Optimizer=CHOOS E (Cost=82560 Card=8789070 B
ytes=325195590)

1 0 VIEW (Cost=82560 Card=8789070 Bytes=325195590 )
2 1 WINDOW (SORT PUSHED RANK) (Cost=82560 Card=8789070 Bytes
=123046980)

3 2 TABLE ACCESS (FULL) OF 'FDETAILRECORD' (Cost=61711 Car
d=8789070 Bytes=123046980 )
One advantage of the solution with analytic functions, is that you can
do:
select * from (
select id,to_char(date time,'yyyy-mm-dd hh24:mi:ss'),ro w_number() over
(order by id) rn from fdetailrecord
) where rn between 5 and 10;

Cu

Martin
Jul 19 '05 #8
Martin Dachselt wrote:
[..]

Strange: costs and execution time seems bo be equal, even for big
tables. Not in my tests. The difference was small, but analytics always came last
(same table as in my previous post, but this time with 10 million rows).
The runtime was about 6.5 s for the rownum solution and 7s for the analytics
solution.
I thought the optimizer is guessing disk and cpu usage.
But they won't make any difference. A full scan is a fullscan, no matter
what you try. But note the difference in the cardinality and bytes between
the your plans. With rownum, the plan is expected to return exactly the
number of rows you asked for. With analytics, oracle cannot now how much
data you're going to retrieve, so it's pessimistic and expects the worst.

One advantage of the solution with analytic functions, is that you can
do:
select * from (
select id,to_char(date time,'yyyy-mm-dd hh24:mi:ss'),ro w_number() over
(order by id) rn from fdetailrecord
) where rn between 5 and 10;


But not really what the OP asked for, is it? And this one is equivalent
in every respect (except that it's slightly faster on my machine):

select * from (
select i, rownum rn from (select i,j from test order by j)
where rownum<= 10)
where rn between 5 and 10
/

To return to the original question:
select i from test where i between 10 and 15
and j in (select min(j) from test where i between 10 and 15)

is a working example of what the OP regarded as not possible (at least in 10g it works).
And with proper indexes in place this is pretty fast, too.

Perhaps we can get the OP to explain his problem better?

Regards,
Holger
Jul 19 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

14
13432
by: Sanjay Minni | last post by:
What is the datatype to be used for Primary Key columns for most optimised access given that - There will be a single column primary key only - The values will only be integers (but as strings) at least 12 digits (characters) long - all positions will be occupied (no leading 0's) - Tables may have upto 1m+ rows
3
2777
by: James Lee | last post by:
I am doing a simple query like col1, col2, date, col4 from table1. All four colums are of type blob. For date column, I store a string like this: Fri Feb 13 11:01:24 2004 I store records as they come in so the oldest record is at the top of the table. When I select and display, I want to display them in reverse order (newest record at the top) but I can't sort on date with strings like that.
16
6162
by: Dan V. | last post by:
How do you do a css 2 column layout with header and footer, with the 2nd column auto-stretching so entire page looks good for 800 x 600 resolution as min. and 1024 x 768 resolution as a max? Ideally the layout would be centered so it scales better visually. This would be great for me. Thanks,
1
1596
by: Wilfried Mestdagh | last post by:
Hi, If you doubleclick on a dbgrid title separator the column automticly resize to his minumum width. How to do this in code ? -- rgds, Wilfried http://www.mestdagh.biz
1
15006
by: neelu | last post by:
I have four columns in listview. SR Number Part# DES Qty Weight 59 9410106800 Nut 10 0.03 60 90304ge800 Helmet 5 0.325 61 9635439604 Cap 15 0.421 62 25340h1245 Shoes 2 0.001 I want that when I click on column part# it sort the list View
0
1178
by: Steven W | last post by:
I'm trying to setup a datagrid in a custom control where I can select the row with the Select column hidden and have it call the "SelectIndexChanged" event. In the "SelectIndexChanged" I just want to populate a textbox with an item out of the selected row. I've implemented what seems to be the standard approach such as shown below to accomplishing this and the event works when selecting the select column link, when I make it visible,...
1
3336
by: Bob Loveshade | last post by:
I am looking for an example that shows how to select and highlight multiple rows in a DataGrid. My DataGrid is part of a Web User Control which is contained in an ASPX page. I haven't been able to find any examples which demonstrate how to do this. My Code:
2
6074
by: Eugene Anthony | last post by:
I have a table that has a DateTime column which uses a DataTime datatype. How do I retrieve the minimum and maximum year using ms sql? Eugene Anthony *** Sent via Developersdex http://www.developersdex.com ***
0
1772
by: rajesh | last post by:
Hi , i want to select the first minimum date in the column d for each distinct column a value. how i can do that in a sql query. xyztable Column a Column b Column c Column d
0
8262
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8502
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7192
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6122
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5571
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4090
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4196
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2623
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1807
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.