简体   繁体   中英

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,

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, eg 255 for varying(255).

You can use regular expression to do this kind of thing:

select THECOL from ...
order by
  case
    when substring(THECOL from '^\d+$') is null then 9999
    else cast(THECOL as integer)
  end,
  THECOL

First you use regular expression to detect whether the content of the column is a number or not. In this case I use '^\\d+$' but you can modify it to suit the situation.

If the regexp doesn't match, return a big number so this row will fall to the bottom of the order.

If the regexp matches, convert the string to number and then sort on that.

After this, sort regularly with the column.

I'm not aware of any database having a "natural sort", like some know to exist in PHP. All I've found is various functions:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM