James Stafford
James Stafford

Reputation: 1054

order by number of commas

I am trying to order results from a select statement by the number of commas existing in one of the column.

is there a way to exclusively order by commas in mysql.

Upvotes: 1

Views: 501

Answers (2)

michiruf
michiruf

Reputation: 423

You could use a simple workaround (that may be not very efficient):

ORDER BY
    LENGTH(column) - LENGTH(REPLACE(column, ',', '')) asc

I don't know whether other solutions exist, sorry.

Upvotes: 0

Brett
Brett

Reputation: 2823

You can order your results by the number of comma's in a specific field with a query like the following:

select * from table order by length(areaCodeField)-length(replace(areaCodeField, ",", ""))) desc

The order by piece of the query will count all of the characters in the field and then subtract all of the characters not counting the commas. This leaves you with the number of commas.

Upvotes: 2

Related Questions