0

I am trying to create a SQL query that queries a database and returns info on various airports.

The basic query works fine, however the results are returned in a random order.

SELECT * FROM airportdata WHERE airportcode LIKE 'LHR' OR airportcode LIKE 'HKG'

It is really important that they are returned in the order passed into the query (i.e. the airport data from LHR be the first result returned followed by the airport info for HKG), however I can't get find any ORDER BY that will work.

apparently FIND_IN_SET is what I should be using, however I've tried all variations and I can't get it to work!

SELECT * FROM airportdata WHERE airportcode LIKE 'LHR' OR airportcode LIKE 'HKG' ORDER BY FIND_IN_SET(airportcode,'LHR,HKG')

Can anyone see what I'm doing wrong? Thanks!

6
  • Perhaps with a CASE statement to build a sorting key? Commented Aug 26, 2018 at 12:13
  • "returned in the order passed into the query" — what does that mean? Commented Aug 26, 2018 at 12:16
  • I've amended to clarify what I mean! Cheers Commented Aug 26, 2018 at 12:19
  • And why are you using LIKE without any real pattern? Why isn't it just =? Commented Aug 26, 2018 at 12:19
  • So order by airportcode desc ? Commented Aug 26, 2018 at 12:20

2 Answers 2

2

I would recommend that you use IN. You can then use a

SELECT *
FROM airportdata
WHERE airportcode IN ('LHR', 'HKG')
ORDER BY position(airportcode in 'LHR,HKG')

(This is safe because airport codes should be 3 characters and not have commas.)

If you want to use LIKE (which supports wildcards), you can do:

SELECT ad.*
FROM airportdata ad JOIN
     (VALUES ('LHR', 1),
             ('HKG', 2)
     ) v(pattern, pos)
     ON v.airportcode LIKE pattern
ORDER BY pos;

This does run the risk of duplicates, because one code could (theoretically) match multiple patterns. If that is a real risk, you would need to explain which pattern you prefer.

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

Comments

1

use this query:

SELECT * 
FROM airportdata 
WHERE airportcode LIKE 'LHR' OR airportcode LIKE 'HKG' 
ORDER BY CASE WHEN airportcode LIKE 'LHR' THEN 1 ELSE 0 END

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.