开发者

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, e.g 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:

  • Natural order sort in Postgres
  • Comment in the PostgreSQL ORDER BY documentation
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜