Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are you able to use a custom Postgres comparison function for ORDER BY clauses?

Tags:

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.

like image 486
Sean Woods Avatar asked Sep 11 '10 16:09

Sean Woods


People also ask

How does Postgres ORDER BY default?

ASC order is the default. Ascending order puts smaller values first, where “smaller” is defined in terms of the < operator. Similarly, descending order is determined with the > operator.

Is Postgres ORDER BY case insensitive?

PostgreSQL is a case-sensitive database by default, but provides various possibilities for performing case-insensitive operations and working with collations.

Does Postgres guarantee order?

You have it right. The only order that is guaranteed is the order that your "ORDER BY" imposes. If there are permutations possible within that order these could all be a valid output.


1 Answers

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.

  • SQL: http://www.postgresql.org/docs/current/static/xfunc-sql.html
  • PL/pgSQL: http://www.postgresql.org/docs/current/static/plpgsql.html
like image 198
Frank Heikens Avatar answered Oct 22 '22 05:10

Frank Heikens