Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order by not working when insert in temp table

I have a query, and when I execute it in SQL Server 2012, the ORDER BY clause is not working. Please help me in this. Regards.

DECLARE @Data table (Id int identity(1,1), SKU varchar(10), QtyRec int,Expiry date,Rec date)
DECLARE @Qty int = 20

INSERT @Data 
VALUES
    ('001A', 5 ,'2017-01-15','2015-11-14'),
    ('001A', 8 ,'2017-01-10','2015-11-14'),
    ('001A', 6 ,'2015-12-15','2015-11-15'),
    ('001A', 25,'2016-01-01','2015-11-16'),
    ('001A', 9 ,'2015-12-20','2015-11-17');

SELECT * 
INTO #temp 
FROM @Data 
ORDER BY Id DESC

SELECT * 
FROM #temp
like image 507
Alina Dilshad Avatar asked Nov 14 '15 13:11

Alina Dilshad


People also ask

Can we use ORDER BY in temp table?

Microsoft does not use the ORDER BY clause when inserting records into any table, including table valued functions.

Why ORDER BY is not working in SQL?

Solution. The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP, OFFSET or FOR XML is also specified. This used to work, back in the SQL Server 2000 days, but not in modern versions.

Can we use ORDER BY in insert query?

Yes. The actual order in which rows are inserted into the target table is dependent on the execution plan.

How do I sort a temp table in SQL Server?

What we can do is to add a PRIMARY KEY (by default it is marked as clustered) to your table and make the column IDENTITY : CREATE TABLE #MainCalcTemp ( [RowID] INT IDENTITY(100,1) ,... ); Now, the rows will be inserted following your define order each time.


2 Answers

SQL tables represent unordered sets.

When you SELECT from a table, then the results are unordered. The one exception is when you use an ORDER BY in the outer query. So, include an ORDER BY and the results will be in order.

EDIT:

You can eliminate the work for the sort by introducing a clustered primary key.

create table #temp (
    Id int identity(1,1) primary key clustered, 
    SKU varchar(10),
    QtyRec int,
    Expiry date,
    Rec date
);

Then when you do:

insert into #temp(SKU, QtyRec, Expiry, Rec)
    select SKU, QtyRec, Expiry, Rec
    from @Data
    order by id;

The clustered primary key in #temp is guaranteed to be in the order specified by the order by. Then the query:

select *
from #temp
order by id;

will return the results in order, using the clustered index. No sort will be needed.

like image 113
Gordon Linoff Avatar answered Sep 23 '22 16:09

Gordon Linoff


A SELECT ... INTO clause will help reach your expected output. I usually use temp tables in this way along with a column with a Row number using the ROW_NUMBER() function. It automatically orders the selected rows to the temp table. Or more simply, you can use the ORDER BY clause.

like image 34
Chanuka Naveen Koswatta Avatar answered Sep 19 '22 16:09

Chanuka Naveen Koswatta