This website uses cookies

Read our Privacy policy and Terms of use for more information.

Run a SQL query twice. Get different row orders.

That's not a bug. Databases don't guarantee row order unless you ask for it. The engine optimizes execution based on indexes, data volume, and memory. Those optimizations can change between queries.

If order matters, you have to say so.

In Python, we use sorted() with a key function. SQL uses ORDER BY. Simple enough. But here's where SQL pulls ahead: sorting by multiple columns with mixed directions.

Want newest dates first, then alphabetical within each date? In SQL:

ORDER BY signup_date DESC, name ASC

In Python? You need cmp_to_key or multiple sorting passes. SQL's per-column DESC and ASC modifiers are cleaner.

This week's post walks through ORDER BY with Python comparisons at every step.

Next week: Filtering rows with WHERE.

-Jamal

Keep Reading