views:

25

answers:

1

In Python, I can write a sort comparison function which returns an item in the set {-1, 0, 1} and pass it to a sort function like so:

sorted(["some","data","with","a","nonconventional","sort"], custom_function)

This code will sort the sequence according to the collation order I define in the function.

Can I do the equivalent in Postgres?

e.g.

SELECT widget FROM items ORDER BY custom_function(widget)

Edit: Examples and/or pointers to documentation are welcome.

+1  A: 

Yes you can, you can even create an functional index to speed up the sorting.

Edit: Simple example:

CREATE TABLE foo(
    id serial primary key,
    bar int
);
-- create some data
INSERT INTO foo(bar) SELECT i FROM generate_series(50,70) i;
-- show the result
SELECT * FROM foo;

CREATE OR REPLACE FUNCTION my_sort(int) RETURNS int 
LANGUAGE sql 
AS
$$
    SELECT $1 % 5; -- get the modulo (remainder)
$$;
-- lets sort!
SELECT *, my_sort(bar) FROM foo ORDER BY my_sort(bar) ASC;

-- make an index as well:
CREATE INDEX idx_my_sort ON foo ((my_sort(bar)));

The manual is full of examples how to use your own functions, just start playing with it.

Frank Heikens
I thought so, sorry for the rather "obvious" question but...how on earth do I do this? The documentation and Google don't seem to provide me with obvious answer. A few more details/examples would be greatly appreciated. Thanks!
Sean Woods
Check the simple example. Now it's up to you and your imagination :-)
Frank Heikens
Thanks for the extra example. Your function only takes one variable, though. In Python the sort function takes two variables. If variable 1 should go before variable 2, it returns -1. If they're equal, 0, and if var 2 should go before var 1, it returns 1. I still don't see the equivalent here.
Sean Woods
As I said, it's up to your imagination, PostgreSQL doesn't have (many) limitations. If you want a function with 2 parameters, just make one. If you need 10 parameters, just go for it. Start using pl/pgsql and make an if-else construction for your comparison.
Frank Heikens