Explain Codes LogoExplain Codes Logo

Sort by Minimum Value of Two Columns

sql
best-practices
performance
sql-performance
Anton ShumikhinbyAnton Shumikhin·Jan 13, 2025
TLDR

Here's the straightforward solution; use LEAST in the ORDER BY clause to sort by minimum value of two columns:

SELECT * FROM your_table ORDER BY LEAST(col1, col2);

Remember to replace your_table, col1, col2 with your own SQL table and column names, okay? If you're into reverse sort (because why not?), just add DESC:

ORDER BY LEAST(col1, col2) DESC;

No LEAST? No problem!

SQL Server is a bit picky; it doesn't support LEAST. But worry not, a CASE expression can do the trick:

/* Mother of all case statements - starts */ SELECT * FROM your_table ORDER BY CASE WHEN col1 < col2 OR col2 IS NULL THEN col1 ELSE col2 END; /* Mother of all case statements - ends */

NULLOSAURUSrex Strikes! Handling NULLs with ANSI Standard

Damn those NULL values. Good news, though. COALESCE is not just a fancy SQL term; it adheres to the ANSI SQL standards and is the NULLOSAURUSrex slayer:

// Amaze your friends. Teach your grandma. ORDER BY CASE WHEN COALESCE(col1, col2) < COALESCE(col2, col1) THEN col1 ELSE col2 END;

Handle datetime like a boss using a reference date compatible with the ANSI standard date format, aka '1753-01-01':

// Because old is always gold, right? ORDER BY CASE WHEN COALESCE(Date1, '1753-01-01') < COALESCE(Date2, '1753-01-01') THEN Date1 ELSE Date2 END;

Running Circles Around Nested Selects

For more complex queries, a nested SELECT can help you find the minimum date and sort efficiently:

// Say hello to nested SELECT. KEEP CALM AND NEST ON. SELECT *, (SELECT MIN(d) FROM (VALUES (Date1), (Date2)) AS a(d)) AS MinDate FROM your_table ORDER BY MinDate;

Who said elegance and efficiency can't coexist in SQL? Nesting SELECT gives you both!

Calculate Minimum Datetime Value Like a Pro

You're dealing with multiple datetime columns? No sweat. DATEDIFF and ABS are your knights in shining armor:

// Make the calculation. Be the calculation. SELECT *, ABS(DATEDIFF(day, '1753-01-01', COALESCE(Date1, '1753-01-01'))) AS Diff1, ABS(DATEDIFF(day, '1753-01-01', COALESCE(Date2, '1753-01-01'))) AS Diff2 FROM your_table ORDER BY CASE WHEN Diff1 < Diff2 THEN Date1 ELSE Date2 END;

This technique applies to both numerical and date values, preserving a consistent sorting order even when NULL values want to spoil the party (yeah, they do that).

SQL Performance: The Need for Speed

We all know time is money. Thinking about performance? CASE expressions are usually efficient, but remember nested queries can slow you down. Choose wisely, my friend.

Don't Fall in the Pitfalls

When handling NULL values, COALESCE is your safety net. It's more standard-compliant than ISNULL, ensuring your scripts are compatible across SQL systems.

Remember, unhandled NULL values can lead to unexpected results. Tame them with a well-crafted CASE statement or the magic of COALESCE.