Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to batch updates in Sequel?

Is it possible to make many updates in a single call using Sequel?

For instance, making about 200 updates could take several minutes on my server, but if I forge a single SQL query it runs in a matter of seconds. I wonder if Sequel could be used to forge that SQL query or even better, do the whole operation one shot by itself.

like image 704
RooSoft Avatar asked May 03 '12 14:05

RooSoft


People also ask

Can we do bulk update in SQL?

Applications can perform bulk update, delete, fetch, or insertion operations on the underlying table at the data source with a call to SQLBulkOperations. Calling SQLBulkOperations is a convenient alternative to constructing and executing an SQL statement.

What is batch update in SQL?

A batch update is a set of multiple update statements that is submitted to the database for processing as a batch. Sending multiple update statements to the database together as a unit can, in some situations, be much more efficient than sending each update statement separately.

Can you do multiple sets in SQL update?

We use the SQL UPDATE syntax to modify or update existing data in a table or view in SQL Server. We can use this statement to modify a single unit of data field as well as multiple sets of data fields based on our requirements.

How do you update multiple items in SQL?

There are a couple of ways to do it. INSERT INTO students (id, score1, score2) VALUES (1, 5, 8), (2, 10, 8), (3, 8, 3), (4, 10, 7) ON DUPLICATE KEY UPDATE score1 = VALUES(score1), score2 = VALUES(score2);


2 Answers

The solution I've come across involves the update_sql method. Instead of doing the operation itself, it output raw SQL queries. To batch multiple updates, just join these with ; in between, call the run method with the resulting string and you're all set.

The batching solution is WAY faster than multiple updates.

like image 200
RooSoft Avatar answered Nov 09 '22 23:11

RooSoft


You can use Datset#import http://sequel.jeremyevans.net/rdoc/classes/Sequel/Dataset.html#method-i-import "Inserts multiple records into the associated table. This method can be used to efficiently insert a large number of records into a table in a single query if the database supports it. Inserts are automatically wrapped in a transaction."

here's an example of how to use it:

DB = Sequel.connect(...)
DB[:movies].import([:id, :director, :title, :year], [[1, "Orson Welles", "Citizen Kane", 1941],[2, "Robert Wiene", "Cabinet of Dr. Caligari, The", 1920]])
like image 26
Chris Kolodin Avatar answered Nov 09 '22 23:11

Chris Kolodin