Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLite returning data in custom order

I'm using an SQLite query (in an iOS application) as follows:

SELECT * FROM tblStations WHERE StationID IN ('206','114','113','111','112','213','214','215','602','603','604')

However, I'm getting the resulting data in either descending or ascending order, when what I really want is for the data to be returned in the order I've specified in the IN clause.

Is this possible?

like image 200
Bad Boy Avatar asked Feb 14 '26 08:02

Bad Boy


1 Answers

A trivial way to sort the results

NSArray *stationIDs = @[@206,@114,@113,@111,@112,@213,@214,@215,@602,@603,@604];

NSArray *stations = @[@{@"Id":@(604)},@{@"Id":@(603)},@{@"Id":@(602)},@{@"Id":@(215)},
                      @{@"Id":@(214)},@{@"Id":@(213)},@{@"Id":@(112)},@{@"Id":@(111)},
                      @{@"Id":@(113)},@{@"Id":@(114)},@{@"Id":@(206)}];

stations = [stations sortedArrayUsingComparator:
            ^NSComparisonResult(NSDictionary * dict1, NSDictionary *dict2)
{
    NSUInteger index1 = [stationIDs indexOfObject:dict1[@"Id"]];
    NSUInteger index2 = [stationIDs indexOfObject:dict2[@"Id"]];
    return [@(index1) compare:@(index2)];
}];
like image 57
Anupdas Avatar answered Feb 16 '26 21:02

Anupdas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!