473,396 Members | 1,714 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Ordering by IN

Hi,
I was wondering if it's possible to order the result set by some of
the set contained in an IN clause.

For example.
SELECT * FROM v_fol_unit_pub_utmpt WHERE folder_folder_object = 100120
AND unit IN ( 90072, 90005, 90074, 90075 ) AND unit_pub_type IN ( 2 )
AND utmpt IN ( 1 );

Results in.

folder_folder_object | unit | unit_type | unit_quantity |
unit_pub_type | utmpt
----------------------+-------+-----------+---------------+---------------+-------
100120 | 90005 | 101 | 1 |
2 | 1
100120 | 90072 | 101 | 1 |
2 | 1
100120 | 90074 | 101 | 1 |
2 | 1

When ideally I'd like to maintain the order as per ordered list of unit
ids passed in as the parameters.
Like so;

folder_folder_object | unit | unit_type | unit_quantity |
unit_pub_type | utmpt
----------------------+-------+-----------+---------------+---------------+-------
100120 | 90072 | 101 | 1 |
2 | 1
100120 | 90005 | 101 | 1 |
2 | 1
100120 | 90074 | 101 | 1 |
2 | 1
Is this even possible?

Thanks

Nov 23 '05 #1
3 1419
On Aug 25, 2004, at 2:18 AM, Hadley Willan wrote:
Hi,
*** I was wondering if it's possible to order the result set by some
of the set contained in an IN clause.


I had to do something like this recently. Ended up with a pl/pgsql
function, looked a lot like this:

create or replace function array_find (int8, int8[]) returns int4 as
'declare
data alias for $1;
arr alias for $2;
cnt int4;
begin
cnt := 1;
while arr[cnt] is not null loop
if data = arr[cnt] then
return cnt;
end if;
cnt := cnt + 1;
end loop;

return null;
end;'
language 'plpgsql';

Then, using your original query:

SELECT * FROM v_fol_unit_pub_utmpt
WHERE folder_folder_object = 100120 AND
unit IN ( 90072, 90005, 90074, 90075 ) AND
unit_pub_type IN ( 2 ) AND
utmpt IN ( 1 )
ORDER BY array_find(unit, '{90072, 90005, 90074, 90075}');

Notice that the values are repeated in the ORDER BY clause, in the form
of an array. VeryImportant. Also note that I'm assuming the datatype
of "unit" is an int8... you'll want to adjust the arguments of the
function appropriately for the actual datatype.

With my luck, somebody will respond with a "but postgres already has an
array_find-like function"... but if it does, I couldn't find it.

eric
---------------------------(end of broadcast)---------------------------
TIP 4: Don't 'kill -9' the postmaster

Nov 23 '05 #2
It might not be pretty but:

SELECT * FROM v_fol_unit_pub_utmpt WHERE folder_folder_object = 100120
AND unit IN ( 90072, 90005, 90074, 90075 ) AND unit_pub_type IN ( 2 )
AND utmpt IN ( 1 ) ORDER BY unit = 90072 desc, unit = 90005 desc, unit =
90074 desc;

It probably won't work very well if you need to specify more then about
10 IDs to order by.
I just discovered Postgres supports this syntax:

ORDER BY unit in ( 90072, 90005, 90074 ) desc

It seems to order the IDs in the reverse order they are listed in the IN
clause. I don't fully understand the behavior of the above case though,
it seems to do weird things with different queries. Give it a shot
though.

On Wed, 2004-08-25 at 18:18 +1200, Hadley Willan wrote:
Hi,
I was wondering if it's possible to order the result set by some
of the set contained in an IN clause.

For example.
SELECT * FROM v_fol_unit_pub_utmpt WHERE folder_folder_object = 100120
AND unit IN ( 90072, 90005, 90074, 90075 ) AND unit_pub_type IN ( 2 )
AND utmpt IN ( 1 );

Results in.

folder_folder_object | unit | unit_type | unit_quantity |
unit_pub_type | utmpt
----------------------+-------+-----------+---------------
+---------------+-------
100120 | 90005 | 101 | 1 |
2 | 1
100120 | 90072 | 101 | 1 |
2 | 1
100120 | 90074 | 101 | 1 |
2 | 1

When ideally I'd like to maintain the order as per ordered list of
unit ids passed in as the parameters.
Like so;

folder_folder_object | unit | unit_type | unit_quantity |
unit_pub_type | utmpt
----------------------+-------+-----------+---------------
+---------------+-------
100120 | 90072 | 101 | 1 |
2 | 1
100120 | 90005 | 101 | 1 |
2 | 1
100120 | 90074 | 101 | 1 |
2 | 1
Is this even possible?

Thanks

--
Mike Benoit <ip**@snappymail.ca>
---------------------------(end of broadcast)---------------------------
TIP 9: the planner will ignore your desire to choose an index scan if your
joining column's datatypes do not match

Nov 23 '05 #3
Mike Benoit <ip**@snappymail.ca> writes:
I just discovered Postgres supports this syntax:

ORDER BY unit in ( 90072, 90005, 90074 ) desc

It seems to order the IDs in the reverse order they are listed in the IN
clause. I don't fully understand the behavior of the above case though,
it seems to do weird things with different queries. Give it a shot
though.


That's just sorting by the boolean value of whether unit is in the set or not.
It's not doing what you want.

You could do something like

SELECT *
FROM a JOIN ( select 90072 as unit
union all select 90005
union all select 90074) as x using (unit)

But even that is NOT going to be guaranteed to work. If it happens to choose a
nested loop from the union against a then I think it would result in the right
order. But if it decides to use a hash join or merge join then it's going to
result in other orderings.

You would have to make that more elaborate and cumbersome with

SELECT *
FROM a JOIN ( select 90072 as unit, 1 as pos
union all select 90005,2
union all select 90074,3
) as x using (unit)
ORDER BY pos
If you load the very useful contrib/intarray module you could use the clean
nice notation:

ORDER BY idx(array[90072,90005,90074], unit)

--
greg
---------------------------(end of broadcast)---------------------------
TIP 2: you can get off all lists at once with the unregister command
(send "unregister YourEmailAddressHere" to ma*******@postgresql.org)

Nov 23 '05 #4

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

Similar topics

2
by: Ken Fine | last post by:
(originally posted to one of macromedia's groups; no help, so hopefully someone here can help me out. I'm using VBScript ASP.) When designing administrative interfaces to websites, we often need...
2
by: masood.iqbal | last post by:
What is the standard C/C++ lexicograhic ordering of punctuation characters with respect to each other and the alphanumeric characters? --Masood
2
by: D. Dante Lorenso | last post by:
First I created a function that selected the next available pin code from a table of pre-defined pin codes: CREATE FUNCTION "public"."get_next_pin_code" () RETURNS varchar AS' DECLARE...
2
by: Ken Durden | last post by:
Is there any way to control ordering of items in intellisense via attributes? For example, I have the following enum: public enum ESeverity { Acceptable, Low, Medium,
3
by: Ryan | last post by:
My project uses the /ORDER specifier to order functions as specified in file containing the decorated names of packaged functions (COMDATs). I am in the process of upgrading from VC6 to VC.NET 2003....
1
by: Matt Roberts | last post by:
Please accept my apologies if this is answered elsewhere in the archives or docs but I have searched without luck. I've always assumed that default ordering of selects are based on a first in...
20
by: Brian Tkatch | last post by:
An ORDER BY a simple-integer inside a FUNCTION, results in SQL0440N, unless the FUNCTION expects an INTEGER as its parameter. For example: DECLARE GLOBAL TEMPORARY TABLE A(A CHAR(1)) INSERT INTO...
33
by: Benjamin M. Stocks | last post by:
Hello all, I've heard differing opinions on this and would like a definitive answer on this once and for all. If I have an array of 4 1-byte values where index 0 is the least signficant byte of a...
23
by: illegal.prime | last post by:
Hi all, is there a key value collection in .Net that maintains the ordering in which I add items. I'm finding that I'm creating a number of classes that contain a name and then some object. I...
4
ChrisWang
by: ChrisWang | last post by:
Dear all, I am reading the book "Core Python Programming". In the chapter talking about modules, it says the modules should follow this ordering: import Python Standard Library modules ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
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...

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.