Skip to content
Advertisement

Order by SQL line

How would I go about creating an SQL line that puts each car from new to old (Years) but also keeps it in alphabetical order

For example it needs to do this

2018 Acura Model X
2018 Acura Model X
2017 Acura Model X
2017 Acura Model X
2018 Audi Model X
2017 Audi Model X
2018 BMW Model X

This is how its displaying

MY View

Advertisement

Answer

You may try the following query:

SELECT *
FROM yourTable
ORDER BY
    SUBSTRING_INDEX(SUBSTR(name, 6), ' ', 1),   -- order ascending by model name
    LEFT(name, 4) DESC;                         -- order descending by model year

The call I make to SUBSTRING_INDEX extracts the second word from the model string. This is assumed to be the model name.

enter image description here

Demo

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement