When using a single insert statement to add multiple records into a table as shown below, it does not follow the same order when selecting. I understand that it does not affect anything but may I know why is this the case?
CREATE TABLE [category] ( [category_id] int IDENTITY(1,1) PRIMARY KEY, [category_name] varchar(255) NOT NULL UNIQUE );
INSERT INTO [category] (category_name) VALUES ('Laptops and Accessories'), ('AI Development Kit'), ('Cameras and Lens'); SELECT * FROM [category]
Output:
I’m using SQL Server.
Advertisement
Answer
Your select statement explicitly says: “I do not care about the order!” – it does so by omitting the ORDER BY
clause.
If you say SELECT * FROM [category] ORDER BY [category_id]
you will get an ordered result set along the lines of
1, 'Laptops and Accessories' 2, 'AI Development Kit' 3, 'Cameras and Lens'
Which is exatly the order you gave in your INSERT
statement.
SELECT
s in SQL without an ORDER BY
clause are not only not expected to be in some order, they are also not expected to have the same order when called multiple times.