Add Identity field in already filled table

Asked

Viewed 210 times

2

How do I resolve the situation below:

I have a table where the data were entered in the following order:

INSERT INTO teste(Nome) VALUES('C')
INSERT INTO teste(Nome) VALUES('D')
INSERT INTO teste(Nome) VALUES('B')
INSERT INTO teste(Nome) VALUES('A')

In this table already filled I will create a field Alphanumeric identity which you do not have. When you create this column, SQL itself will fill the alphanumeric column. Will it number as per the order that was inserted or will it pick random order to apply the Identity?

I needed that result:

ID      Nome
1        C
2        D
3        B
4        A

2 answers

1

Will it number according to the order that was inserted or will pick random order to apply the Identity?

In SQL Server a table is a set of data without any order. Even if there is a column with a supposed sequence, it is still a data set with no order. Only by listing the content can this order be requested to be executed according to column content(s).

The existence of index also does not mean that SELECT will return the result ordered by the index. Moreover, this is clear from the documentation of the clause ORDER BY: The order in which Rows are returned in a result set are not Guaranteed unless an ORDER BY clause is specified.

In the documentation of heap tables reads as follows:: Data is stored in the heap without specifying an order. Usually data is initially stored in the order in which is the Rows are inserted into the table, but the Database Engine can move data Around in the heap to store the Rows efficiently; so the data order cannot be Predicted.

That is to say, cannot be said that the numbering in column Identity will be in the same sequence in which the lines have been included.

  • Good answer, well grounded

0


In this case yes, it will use as parameter the order in which it was inserted. The index of the table is used to define this order.

Print do teste

  • Thank you for the clarification.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.