1

I have faced some strange sort order behaviour between Postgres & mysql.

For example, i have created simple table with varchar column and inserted two records as below in both Postgres and Mysql.

create table mytable(name varchar(100));
insert into mytable values ('aaaa'), ('aa_a');

Now, i have executed simple select query with order by column.

Postgres sort order:

test=# select * from mytable order by (name) asc;
 name 
------
 aa_a
 aaaa
(2 rows)

Mysql sort order:

mysql> select * from mytable order by name asc;
+------+
| name |
+------+
| aaaa |
| aa_a |
+------+
2 rows in set (0.00 sec)

Postgres and mysql both returning same records with different order.

My question is which one correct?

How to get results in same order in both database?

Edited:

I tried with query with ORDER BY COLLATE, it solved my problem.

Tried like this

mysql> select * from t order by name COLLATE utf8_bin;
+------+
| name |
+------+
| aa_a |
| aaaa |
+------+
3 rows in set (0.00 sec)

Thanks.

3
  • Unrelated but: don't use (name) in Postgres. It is actually something different than name. But from my understanding, MySQL's order is wrong, because the _ should indeed come before a (Oracle and SQL Server sort the same way as Postgres - at least on my computer) Commented Jun 26, 2014 at 15:21
  • 1
    I will venture to guess that PostgreSQL is standards compliant and MySQL is not. Commented Jun 26, 2014 at 15:57
  • 1
    Have you tried sorting with the same (the actual keywords can be different in PostgreSQL & MySQL) collation? postgresql.org/docs/current/static/collation.html dev.mysql.com/doc/refman/5.1/en/charset-collate.html Commented Jun 27, 2014 at 8:02

1 Answer 1

2

There is no "correct" way to sort data.

You need to read up on "locales".

Different locales will provide (among other things) different sort orders. You might have a database using ISO-8859-1 or UTF-8 which can represent several different languages. Rules for sorting English will be different for those from French or German.

PostgreSQL uses the underlying operating-system's support for locales, and not all locales are available on all platforms. The alternative is to provide your own support, but then you can have incompatibilities within one machine.

I believe MySQL takes the second option, but I'm no expert on MySQL.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.