Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I sort a VARCHAR column in PostgreSQL that contains words and numbers?

I need to order a select query using a varchar column, using numerical and text order. The query will be done in a java program, using jdbc over postgresql.

If I use ORDER BY in the select clause I obtain:

1
11
2
abc

However, I need to obtain:

1
2
11
abc

The problem is that the column can also contain text.

This question is similar (but targeted for SQL Server):

How do I sort a VARCHAR column in SQL server that contains words and numbers?

However, the solution proposed did not work with PostgreSQL.

Thanks in advance, regards,

like image 626
Angel Palazon Avatar asked Nov 02 '10 18:11

Angel Palazon


People also ask

How do I sort varchar numbers?

'LPAD(lower(column_name))' is used to sort the varchar field numerically in MySQL. Let us see an example. Firstly, we will create a table. The CREATE command is used to create a table.

What sorting algorithm does Postgres use?

Postgres uses a well known sorting algorithm called Quick sort to accomplish in memory sorting. There are certain variations from a vanilla quick sort, you can lookup the source code to understand in much deeper detail.

How do I sort in descending order in PostgreSQL?

When sorting your result set in descending order, you use the DESC attribute in your ORDER BY clause as follows: SELECT last_name, first_name, city FROM contacts WHERE first_name = 'Joe' ORDER BY last_name DESC; This PostgreSQL ORDER BY example would return all records sorted by the last_name field in descending order.


1 Answers

I had the same problem and the following code solves it:

SELECT ...
  FROM table
  order by  
    CASE WHEN column < 'A' 
        THEN lpad(column, size, '0')
    ELSE column 
        END;

The size var is the length of the varchar column, e.g 255 for varying(255).

like image 114
mp_gt Avatar answered Oct 03 '22 23:10

mp_gt