C# Sort and OrderBy comparison

No, they aren’t the same algorithm. For starters, the LINQ OrderBy is documented as stable (i.e. if two items have the same Name, they’ll appear in their original order). It also depends on whether you buffer the query vs iterate it several times (LINQ-to-Objects, unless you buffer the result, will re-order per foreach). For the … Read more

Ordering by the order of values in a SQL IN() clause

Use MySQL’s FIELD() function: SELECT name, description, … FROM … WHERE id IN([ids, any order]) ORDER BY FIELD(id, [ids in order]) FIELD() will return the index of the first parameter that is equal to the first parameter (other than the first parameter itself). FIELD(‘a’, ‘a’, ‘b’, ‘c’) will return 1 FIELD(‘a’, ‘c’, ‘b’, ‘a’) will … Read more

MySQL Orderby a number, Nulls last

MySQL has an undocumented syntax to sort nulls last. Place a minus sign (-) before the column name and switch the ASC to DESC: SELECT * FROM tablename WHERE visible=1 ORDER BY -position DESC, id DESC It is essentially the inverse of position DESC placing the NULL values last but otherwise the same as position … Read more