首页 > 数据库 >SQL Server: How to insert million numbers to table fast?

SQL Server: How to insert million numbers to table fast?

时间:2023-09-14 10:01:41浏览次数:34  
标签:insert set union million number fast numbers select


Yesterday I attended at local community evening where one of the most famous Estonian MVPs – Henn Sarv – spoke about SQL Server queries and performance. During this session we saw very cool demos and in this posting I will introduce you my favorite one – how to insert million numbers to table.

The problem is: how to get one million numbers to table with less time? We can solve this problem using different approaches but not all of them are quick. Let’s go now step by step and see how different approaches perform.

NB! The code samples here are not original ones but written by me as I wrote this posting.
Using WHILE

First idea for many guys is using WHILE. It is robust and primitive approach but it works if you don’t think about better solutions. Solution with WHILE is here.

declare @i as int 

set @i = 0 


while(@i < 1000000) 

begin 

 insert into numbers values(@i) 

 set @i += 1 

end



When we run this code we have to wait. Well… we have to wait couple of minutes before SQL Server gets done. On my heavily loaded development machine it took 6 minutes to run. Well, maybe we can do something.
Using inline table

As a next thing we may think that inline table that is kept in memory will boost up performance. Okay, let’s try out the following code.

declare @t TABLE (number int) 

declare @i as int 

set @i = 0 


while(@i < 1000000) 

begin 

 insert into @t values(@i) 

 set @i += 1 

end 


insert into numbers select * from @t 


Okay, it is better – it took “only” 01:30 to run. It is better than six minutes but it is not good yet. Maybe we can do something more? 

Optimizing WHILE



If we investigate the code in first example we can find one hidden resource eater. All these million inserts are run in separate transaction. Let’s try to run inserts in one transaction.

declare @i as int 

set @i = 0 


begin transaction 

while(@i < 1000000) 

begin 

 insert into numbers values(@i) 

 set @i += 1 

end 

commit transaction 


Okay, it’s a lot better – 18 seconds only! 

Using only set operations



Now let’s write some SQL that doesn’t use any sequential constructs like WHILE or other loops. We will write SQL that uses only set operations and no long running stuff like before.

declare @t table (number int) 

insert into @t 

 select 0 

 union all 

 select 1 

 union all 

 select 2 

 union all 

 select 3 

 union all 

 select 4 

 union all 

 select 5 

 union all 

 select 6 

 union all 

 select 7 

 union all 

 select 8 

 union all 

 select 9 


insert into numbers 

 select 

 t1.number + t2.number*10 + t3.number*100 + 

 t4.number*1000 + t5.number*10000 + t6.number*100000 

 from 

 @t as t1, 

 @t as t2, 

 @t as t3, 

 @t as t4, 

 @t as t5, 

 @t as t6



Bad side of this SQL is that it is not as intuitive for application programmers as previous examples. But when you are working with databases you have to know how some set calculus as well. The result is now seven seconds!
Results

As last thing, let’s see the results as bar chart to illustrate difference between approaches.

Results: How to get million numbers to table?

I think this example shows very well how usual optimization can give you better results but when you are moving to sets – this is something that SQL Server and other databases understand better – you can get very good results in performance.

标签:insert,set,union,million,number,fast,numbers,select
From: https://blog.51cto.com/u_16261339/7467826

相关文章

  • FastAPI学习-12. 请求Cookie 参数
    前言你可以像定义 Query 参数和 Path 参数一样来定义 Cookie 参数。声明 Cookie 参数首先,导入 Cookie:fromfastapiimportCookie,FastAPI声明 Cookie 参数的结构与声明 Query 参数和 Path 参数时相同。第一个值是参数的默认值,同时也可以传递所有验证参数......
  • Query Guide-Query From Insert
    Query查询Query定义了Siddhi中的处理逻辑。它使用来自一个或多个流、命名窗口、表和/或命名聚合的事件,以流方式处理事件,并将输出事件生成到流、命名窗或表中。目的查询提供了一种方法,可以按照事件到达的顺序处理事件,并使用有状态和无状态的复杂事件处理和流处理操作生成输出。语法......
  • 在线问诊 Python、FastAPI、Neo4j — 创建症状节点
    目录参考创建药品节点。importloggingfromutils.neo4j_providerimportdriverlogging.root.setLevel(logging.INFO)#并生成CQLdefgenerate_cql()->str:cql="""CREATE(symptom1:Symptom{name:"膝盖疼"}),(symptom2......
  • java中Mysql Insert 的高效应用
    在Java中,使用MySQL进行高效的插入操作可以采取以下几种方法:1.使用批量插入:通过使用批量插入语句,可以一次性插入多条数据,减少与数据库的交互次数,提高插入效率。可以使用JDBC的`addBatch()`方法将多个插入语句添加到批处理中,然后使用`executeBatch()`方法执行批处理。2.使用预编译......
  • com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Java 8 date/time
    问题复现Java8date/timetypejava.time.LocalDateTimenotsupportedbydefault:addModule"com.fasterxml.jackson.datatype:jackson-datatype-jsr310"toenablehandling....在默认情况下Java8不支持LocalDateTime需要添加com.fasterxml.jackson.datatype:jackson-d......
  • [FASTDDS]02-安装fast-gen
    [FASTDDS]02-安装fast-gen原创https://blog.51cto.com/u_6650004/6114605安装fast-gen fast-gen安装指引fast-gen是一个java程序,因此需要安装openjdk和gradle。登录后复制exportFAST_DDS_ROOT=/home/V01/uidq8207/work/code/third_party/Fast-DDS-GIT/sudoap......
  • RTMP视频服务器EasyDSS互联网视频直播点播平台如何基于FastDFS、ffmpeg、videojs实现
    互联网视频直播点播EasyDSS平台能实现视频流媒体的上传、转码、存储、录像、推流、拉流、直播等功能,在场景上,可以应用到互联网教育、在线课堂、游戏直播、视频点播、无人机等领域。 视频点播平台是指提供用户上传、存储和播放视频内容的在线平台。它可以让用户随时随地观看各......
  • ClickHouse使用之四 ——外部数据源导入通用方案之insert into select from
    需求:1、在工作中,我们常常需要将外部hive或者mysql、oracle等数据源导入到clickhouse中,对于多种外部数据源,是否有通用的数据导入方案?2、我们在clickhouse上维持一张查询主表,但外部数据源表是hive增量表,新增数据需要同步更新到clickhouse上,是否有不通过第三方组件的插入方式......
  • FastAPI 参数体检RequestBody
    一、概述一般对于RequestBody不会通过get提交,对于get提交的参数一般称为是查询参数。所以,如果是通过POTS,PUT等方式提交的参数信息,我们一般是放到RequestBody来提交到我们的后端。对于如何接收和校验请求体,FastApi提供的形式是使用:frompydanticimportBaseModel示例如下:im......
  • m基于Faster R-CNN网络的烟雾检测系统matlab仿真,带GUI操作界面
    1.算法仿真效果matlab2022a仿真结果如下:2.算法涉及理论知识概要经过R-CNN和FastRCNN的积淀,RossB.Girshick在2016年提出了新的FasterRCNN,在结构上,FasterRCNN已经将特征抽取(featureextraction),proposal提取,boundingboxregression(rectrefine),classification都整合在了......