Skip to content

Instantly share code, notes, and snippets.

@alfred-dub
Last active August 15, 2017 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save alfred-dub/1b3df8f9774d90069ddd62249c51ef2e to your computer and use it in GitHub Desktop.
Save alfred-dub/1b3df8f9774d90069ddd62249c51ef2e to your computer and use it in GitHub Desktop.
Natural ordering of migrations' versions using MySQL and Postgre
SELECT
SUBSTRING_INDEX(number, '.', 1) AS FIRST_INT,
SUBSTRING_INDEX(SUBSTRING_INDEX(number, '.', 2), '.', -1) AS SECOND_INT,
SUBSTRING_INDEX(number, '.', -1) AS THIRD_INT,
number as VERSION,
description as TITLE
FROM _version
ORDER BY
LENGTH(SUBSTRING_INDEX(number, '.', 1)) DESC,
SUBSTRING_INDEX(number, '.', 1) DESC,
LENGTH(SUBSTRING_INDEX(SUBSTRING_INDEX(number, '.', 2), '.', -1)) DESC,
SUBSTRING_INDEX(SUBSTRING_INDEX(number, '.', 2), '.', -1) DESC,
LENGTH(SUBSTRING_INDEX(number, '.', -1)) DESC,
SUBSTRING_INDEX(number, '.', -1) DESC
SELECT
number as VERSION,
split_part(number, '.', 1) AS FIRST_INT,
split_part(number, '.', 2) AS SECOND_INT,
split_part(number, '.', 3) AS THIRD_INT,
description as TITLE
FROM _version
ORDER BY
split_part(number, '.', 1)::int DESC
split_part(number, '.', 2)::int DESC
split_part(number, '.', 3)::int DESC
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment