is it possible to change database order on purpose?

Stephen Hulbert 41 Reputation points
2023-09-11T16:01:57.3233333+00:00

SQL is famously non-deterministic.

That is, unless explicitly specified, you cannot guarantee the returned sort order.

We have changes to T-SQL specifications provided by the client.

Very often these require a join to a fresh table.

About as often the join columns do not uniquely identify the new record and so there is duplication.

A solution to this is to give up and just number the rows using ROW_NUMBER, taking the first one.

Unfortunately unless the PARTITION and ORDER BY uniquely identify the rows, it's not guaranteed which rows will be numbered 1.

Since SQL is mostly deterministic, though, and seems to be in the same environment, it's difficult to illustrate that this is a problem.

The differences only really manifest when run, say, from SSIS against a different server as opposed to interactively in SSMS.

Which is somewhat trying.

So, my question is, what determines database order, and is there anything i can do to force it to change.

 use master

Guesses at boilerplate answers not reading the question: how do i change the order of columns/anything about "order by"/discussion of ROW_NUMBER/discussion of PARTITION

SQL Server Other
0 comments No comments
{count} votes

Accepted answer
  1. Erland Sommarskog 121.4K Reputation points MVP Volunteer Moderator
    2023-09-11T21:11:31.55+00:00

    So, my question is, what determines database order, and is there anything i can do to force it to change.

    Your ORDER BY clauses, and if there isn't any, or the ORDER BY is not unique, there is nothing that determines the order. You get what you get. Yes, if you are doing something like a Clustered Index Scan, you are likely to get rows in the order they are physically sorted. Then again, if you join in on a merry-go-round scan, you could get something else. If there is parallelism, the result could be from any thread.

    Throw in sorting on something non-unique, and all bets are off.

    If you want a deterministic result, you need to write deterministic queries which only have one possible result.

    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Anonymous
    2023-09-12T06:58:48.4333333+00:00

    Hi @Stephen Hulbert

    The order by statement can determine the ordering.

    https://learn.microsoft.com/en-us/sql/t-sql/queries/select-order-by-clause-transact-sql?view=sql-server-ver16

    ROW_NUMBER is to create a new column and sort it in a new column.

    I think this requires a case-by-case analysis of a specific issue.

    Best regards,

    Percy Tang

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.