devxlogo

GROUP BY and UNION may return unsorted resultsets

GROUP BY and UNION may return unsorted resultsets

In SQL Server 6.5 and previous versions, the GROUP BY clause in a SELECT statement was carried out by temporarily sorting the resultset before grouping similar rows, therefore the end result was always sorted. For this reasons, many programmers omitted the ORDER BY clause, because the result was sorted anyway

SQL Server 7.0 has modified how the GROUP BY is internally resolved, and in some cases it groups rows using temporary hash tables. In this case the returned rows aren’t sorted on the field specified in the GROUP BY clause. The bottom line is: if you want that a sorted result from a SELECT statement with a GROUP BY clause in SQL Server 7, you must explicitly provide the ORDER BY clause.

The same warning applies to UNION queries without the ALL keyword. Under previous SQL Server versions these queries always required an internal sort, thus the result was always sorted. This isn’t necessarily true in SQL Server 7.

See also  How to Create and Deploy QR Codes Online: A Comprehensive Guide
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist