Use insertUsing() to execute INSERT INTO ... SELECT queries for copying data between database tables in SQL.
Fetching records into PHP memory and re-inserting them into another table via loops is slow. insertUsing() runs a single INSERT INTO ... SELECT query directly inside the database.
use Illuminate\Support\Facades\DB;
// Fast database-level copy without loading records into PHP RAM
DB::table('archived_orders')->insertUsing(
['order_id', 'total', 'created_at'],
DB::table('orders')->select('id', 'total', 'created_at')->where('status', 'completed')
);
- Executes high-speed INSERT INTO ... SELECT statements directly in database
- Avoids loading records into PHP memory buffers
- Ideal for data archiving, activity logging, and snapshot tables
Related Tips
View all tips →Optimize Date Queries by Replacing whereYear() with whereBetween()
Replace whereYear() and whereMonth() on large database tables with whereBetween() date ranges to enable SQL index lookups.
Sort Eloquent Results by Subquery Columns with orderByDesc()
Use query builder subqueries inside orderBy() and orderByDesc() to sort models by aggregated or related table columns directly in SQL.