Kwissle

My real-time quiz battle game Kwissle.com

Crosstips.org

My fun Crossword solver project. Crosstips.org & Krysstips.se

Kung Fu

Fujian White Crane Kung Fu

Photos

Photoalbum, both old and new.

Twitter

Follow me on Twitter

Contact me

My contact details and how to contact me.

 

KungFuPeople.com
Do you train Kung Fu?
Or know someone who does?
Then check out KungFuPeople.com


Mobile version of this page Mobile version of this page


 
Work

Sorting transform function in PostgreSQL


3rd of August 2006

A database table that I've had to work with has a something called identifiers which are humanreable names of questions. There's a HTML template where the question designer can place the various questions in a human-sorted order. All questions get identifiers in the form of <something><number> like this: Head1 or Soma3 or Reg10 where Head, Soma and Reg are sections. Changing the nameing convention from Head1 to Head01 is too late because all the templates already expect Head1 not Head01. Initially I sorted the identifiers like this:

 SELECT id, identifier 
 FROM questions
 WHERE section=123
 ORDER BY identifier 

The result you would get is:

 Head1
 Head10
 Head2
 Head3
 ...

The human readable sort order should have been this:

 Head1
 Head2
 Head3
 ...
 Head10

To solve this now all I needed to do was to extract the two digit part and cast it as an integer. Like this:

 SELECT id, identifier,
   SUBSTRING(identifier FROM '[0-9]{1,2}')::INT AS identifier_int
 FROM questions
 WHERE section=123
 ORDER BY identifier_int, identifier

The reason I who a second order by key is because some identifiers look like this:

 Head9a
 Head9c
 Head9b



Comment

Peter Bengtsson - 7th January 2007  [«« Reply to this]
First time it works.
Peter Bengtsson - 7th January 2007  [«« Reply to this]
A second time. It will then work!
Peter Bengtsson - 7th January 2007  [«« Reply to this]
This time I can get it wrong if I want to.
Anonymous - 5th October 2008  [«« Reply to this]
No need to put it in the results:

SELECT id, identifier,
FROM questions
WHERE section=123
ORDER BY SUBSTRING(identifier FROM '[0-9]{1,2}')::INT, identifier
 
Name:
Email:
hide my email address.

Your email address will be encoded to prevent email-extraction spiders from reading it so you won't get spammed if you decide to show your email address.