I know there is no guarantee without an ORDER BY clause, but are there any techniques to tune SQL Server tables so they’re more likely to return rows in clustered index order, without having to specify ORDER BY every single time I want to run a super-quick ad hoc query? For example, would rebuilding my clustered index or updating statistics help?
Out of all the many tables we use, I’ve only noticed two ever giving me results in an unpredicted order. This is really just an annoyance, but it would be nice to be able to minimize it. In case this is relevant because of page boundary issues or something like that, I should mention that one of the tables that has inconsistent ordering, is the longest table we have that has a clustered index on an identity column.
Edit: deleted the specific example, because I think the example made this read more like a “help me with this query” question, when I just wanted to use the example to illustrate the abstract question.
If you want the result set to be ordered in a specific way, use
ORDER BY.If you want the query to be accessed using a specific index, you may want to use an INDEX table hint, but they are strongly discouraged.
In your particular example, accessing a very large accesslog table that is clustered by an IDENTITY to query all rows for a particular UserId is the last thing you want. You want to have an index by UserId and you want the query to use that index. As a side note, access log tables clustered by an IDENTITY are usually not a good choice, because the typical access is by time range (accesses between t1 and t2) or by other attribute (by userId, like in your example, or by machineId, or similar). None of these is ever satisfied by a clustered index on an IDENTITY column.