
-----------------
Why this function:

PostgreSQL, at least until version 7.4, has rather weak support for
various collating sequences -- what you get when you do

  select ... order by column.

The sorting is closely tied to indexes used throughout the database
cluster and is specified by locale settings at the initdb time.
Yet, people asked for ways of specifying the collating rules at runtime,
even if the sorting will not use indexes. 
it  is reasonable request to want one select to order by
using English rules, another one to run with German rules and yet
another with Czech ones, without having to dump, initdb, restore.

------------
How it works:

In this distribution you will find file nls_sort.c. It contains the
definition of function nls_sort(text, text) which takes a string
parameter and a locale name and returns string describing the ordering.
So you can run

  select * from table order by nls_sort(name, 'en_US.UTF-8')

or

  select * from table order by nls_sort(name, 'fa_IR.UTF-8')

or

  select * from table order by nls_sort(name, 'C')

and get what you expect -- the result is sorted the same way as it
would be with LC_COLLATE=locate sort on the command line.

Internally, the function sets the locale for LC_COLLATE category, runs
strxfrm on the first parameter and encodes the result as octal values.
Thus, it depends on your PostgreSQL collate setting (that which you
did upon initdb, you can check it with show lc_collate) to sort
numbers in the natural way. I believe this is reasonable assumption.
------------------------------------------------------
Note:
	using setlocale in this function cause a little overhead.
	considering that postgresql uses locale function to sort strings and
	glibc locale does not support more that one locale at the same time, we
	have to use setlocale and this is the cost we pay for having collation
	order in postgresql.
	
	investigating glibc source code, I found that there are some functions 
	such as strxfrm_l, strcoll_l that let you use locale functions without
	running setlocale, it seems the performance of these functions is much
	better that runnig setlocale and then strxfrm or strcoll. 

	But you must know that these functions only available on linux
	platforms and if portability is more important for you, you can
	not use these functions.
