SQL SELECT TOP: Common Misuses and Best Practices

SELECT TOP is one of those SQL features that looks simple on the surface and then you realise most developers are using it completely wrong. 😅 I watched a junior dev pull the "top 10 customers by revenue" last week. Query ran fine. Except halfway through the result set, two customers had identical revenue figures, and he'd cut them off arbitrarily. His boss later asked why they'd missed a major account in their analysis. The fix? WITH TIES. One word. Changes everything. Here's what most people don't realise about SELECT TOP: 1. Without ORDER BY, you're getting random rows. The database doesn't promise any order, so your "top 10" might be different every time you run it. 2. WITH TIES includes additional rows that match the value of your last row. So if you want the top 3 products by price and two products tie for third, you get all of them. 3. PERCENT lets you grab a percentage of rows instead of a fixed number. Useful for sampling large datasets, though I've seen it misused more often than not. I've spent 15+ years optimising SQL queries, and this is one of those features that separates "it works" from "it actually works correctly." The difference between a query that passes a code review and one that creates silent data errors six months down the line. What's your approach? Are you using TOP in production, or have you moved to other pagination methods? https://lnkd.in/eChg5NEe

To view or add a comment, sign in

Explore content categories