sql / expert
Snippet
Explicit Null Ordering with NULLS FIRST/LAST
Standard SQL sorting behavior for NULL values varies by implementation. Using 'NULLS FIRST' or 'NULLS LAST' explicitly controls where NULL values appear in the result set, ensuring consistent behavior across different database systems regardless of their defaults.
snippet.sql
1
2
3
SELECT product_name, discount_priceFROM inventoryORDER BY discount_price DESC NULLS LAST, product_name ASC;
Breakdown
1
ORDER BY discount_price DESC
Sorts prices from highest to lowest.
2
NULLS LAST
Ensures that products with no discount (NULL) appear at the end of the list.
3
product_name ASC
Secondary sort criteria to maintain deterministic ordering.