I have a table with a column called year varchar(100). This column can contain data like
Year ------- 1901 0 circa 12580 125d4 great year 1012 3411 standard 12 saf 1234 Now I want to order by Year ascending or descending by finding the first 4 digits in the Year field. I want to:
- Get only those columns those have 4 or more digits (either alone or with some string)
- Extract first 4 digits (if more than 4 or with some integer) or get 4 digits (if column has only 4 digit value)
- Order by result set based on above two conditions
I want my result set in ascending order like:
Year 1012 1234 1258 1901 3411 And vise versa in descending order.
I have tried following:
SELECT * FROM table WHERE YEAR REGEXP '^[0-9]+$' AND LENGTH(YEAR) = 4 ORDER BY CAST(YEAR AS UNSIGNED) DESC; But this only returns columns having only 4 digits and orders by them, but not the result as I mentioned above.