Explain Codes LogoExplain Codes Logo

How do I return rows with a specific value first?

sql
advanced-sorting
performance-optimization
sql-indexes
Alex KataevbyAlex Kataev·Jan 1, 2025
TLDR

Employ the ORDER BY clause alongside a CASE statement to prioritize rows with specific values.

Check the snippet below:

-- When SQL grants you control over result set order -- Insert obligatory meme reference: Turns out SQL does pick favorites. SELECT * FROM table_name ORDER BY CASE WHEN column_name = 'desired_value' THEN 0 ELSE 1 END;

This ushers rows where column_name equals 'desired_value' to the beginning of the results.

Hitch your site to specific value: First-class return

For advanced sorting requirements—prioritizing multiple values, default sorting—consider these:

  • Prioritize several values using additional WHEN clauses:
-- Yes you can choose more than one favorite SELECT * FROM table_name ORDER BY CASE WHEN column_name = 'first_choice' THEN 0 WHEN column_name = 'second_best' THEN 1 ELSE 2 END;
  • To sort remaining non-prioritized data, combine CASE with other columns:
-- For those who believe that everybody should get a chance to be first SELECT * FROM table_name ORDER BY CASE WHEN column_name = 'desired_value' THEN 0 ELSE 1 END, next_column ASC;
  • A boolean expression directly in ORDER BY makes for concise coding:
-- Because who said sorting has to be complicated? SELECT * FROM table_name ORDER BY (column_name = 'desired_value') DESC, next_column;

Rising up to the occasion: Advanced SQL Sorting

Rely on indexes for efficient order

Indexes are your aid to make ORDER BY queries efficient for large data sets. Ensure the database has relevant indexes matching your ORDER BY criteria for peak performance.

Watch for performance pitfalls

Remember, ordering large datasets, especially with a CASE statement, can bring in potential performance issues. Keeping performance in check:

  1. Leverage indexes on the sorting column.
  2. Sidestep complicated CASE statements teeming with conditions.
  3. Consider storing the sort order in a separate column for complex logic.

ASC and DESC for detailed order control

Remember, ASC and DESC can be paired with your CASE statement allowing you to decide whether to push the prioritized values to the top or bottom of the result set.