Fixed SQL query (the bug was not a problem on postgresql >= 9.1)