Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
111 views
in Technique[技术] by (71.8m points)

SQL language use 'Desc'

I test my SQL language find one question, When I delete 'desc' the SQL running so fast but when I add 'desc', the SQL running so slowly. How could I optimize my SQL language. Thank you very much.

DELETE FROM [WHRW_BATCH] 
WHERE [Start_TM] NOT IN (SELECT TOP 10000 [Start_TM] 
                         FROM [WHRW_BATCH] 
                         ORDER BY [Start_TM] DESC
question from:https://stackoverflow.com/questions/65881985/sql-language-use-desc

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This looks like SQL Server syntax. In that database, I would suggest an updatable CTE:

WITH todelete AS (
      SELECT wb.*,
             ROW_NUMBER() OVER (ORDER BY Start_TM DESC) as seqnum 
      FROM WHRW_BATCH wb
     )
DELETE FROM todelete
    WHERE seqnum > 10000;

This will keep the 10,000 most recent records.

If the table is quite large (i.e. most records are being deleted), then you might find a temporary table is faster:

select top (10000) wb.*
into temp_whrw_batch
from WHRW_BATCH wb
order by Start_TM desc;

Then remove all rows from the table and re-insert:

truncate table WHRW_BATCH;

insert into WHRW_BATCH
    select *
    from temp_whrw_batch;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...