I need to get the first record which has a not null frequency order by length ASC. Incase there is no not null frequency record, then fetch the top length ASC record.
Here is what I tried:
select word, length, frequency
from `dataset`
where `word` LIKE '%aeto%'
and `length` >= 3
ORDER BY length ASC,frequency desc;
select word, length, frequency
from `dataset`
where `word` LIKE '%aeto%'
and `length` >= 3
ORDER BY CASE WHEN frequency IS NULL THEN length
ELSE frequency
END
, length asc, `frequency` desc
Final solution what I can think of in my mind is:
- Run query to get a record where not null frequency and order by length ASC. Incase we do not have one, then try the first query and get the first result.
Expected Result:
As per sample , I need PHAETON as result, If I omit PHAETON and PRAETORIAN (both has non null frequency), then I need PRAETOR as the result
Table Structure and Data : https://dbfiddle.uk/32lmcKAj
2
Answers
You can substitute frequency null values by some latest value coalesce(frequence,0.0).
Then order result BY coalesce(frequency,0.0) desc, length asc.
See examples:
Frequency is not null
Frequency is null, take length for order
Case when search
word
not exist in tablefiddle
Combine two queries, one gets the first record with non-null frequency, the other gets the first record with null frequency. Then select the first one if it exists.
DEMO