<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Nikhilbaxi on Medium]]></title>
        <description><![CDATA[Stories by Nikhilbaxi on Medium]]></description>
        <link>https://medium.com/@nikhilbaxi3?source=rss-a8226d719ecf------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*v1riLsamH-H4Mu6y</url>
            <title>Stories by Nikhilbaxi on Medium</title>
            <link>https://medium.com/@nikhilbaxi3?source=rss-a8226d719ecf------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 10:08:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nikhilbaxi3/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Python `executemany()` with SQL Server: How to Insert Thousands of Rows Efficiently]]></title>
            <link>https://medium.com/@nikhilbaxi3/python-executemany-with-sql-server-how-to-insert-thousands-of-rows-efficiently-4f18c3822ae0?source=rss-a8226d719ecf------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f18c3822ae0</guid>
            <category><![CDATA[database-design]]></category>
            <category><![CDATA[mssql]]></category>
            <category><![CDATA[sql-server]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[pyodbc]]></category>
            <dc:creator><![CDATA[Nikhilbaxi]]></dc:creator>
            <pubDate>Fri, 21 Aug 2026 18:09:30 GMT</pubDate>
            <atom:updated>2026-09-06T19:04:33.368Z</atom:updated>
            <content:encoded><![CDATA[<p>When working with SQL Server from Python, inserting a few rows is easy.</p><p>But what happens when your application needs to insert **10,000, 100,000, or even 1 million rows**?</p><p>A common first implementation looks like this:</p><pre>for row in data:<br>  cursor.execute(query, row)</pre><p>It works. It&#39;s simple. And for small datasets, it&#39;s perfectly fine.</p><p>The problem appears when the volume grows.</p><p>Every database operation has overhead: parameter binding, network communication, server-side processing, and driver-level work. Repeating that process thousands of times can turn a simple data-loading operation into a significant performance bottleneck.</p><p>This is where Python&#39;s `cursor.executemany()` becomes useful.</p><p>And when you&#39;re using **pyodbc with Microsoft SQL Server**, there&#39;s another feature worth knowing about:</p><pre>cursor.fast_executemany = True</pre><p>In this article, we&#39;ll look at how `execute()` and `executemany()` differ, how `fast_executemany` can improve bulk-insert performance, how to handle transactions safely, and how to choose an appropriate batch size.</p><h4>## 1. The Problem: Inserting Many Rows</h4><p>Let&#39;s assume we have an `employees` table:</p><pre>CREATE TABLE employees (<br> id INT IDENTITY(1,1) PRIMARY KEY,<br> name VARCHAR(100),<br> department VARCHAR(100),<br> salary DECIMAL(10, 2)<br>);</pre><p>Our Python application receives data like this:</p><pre>employees = [<br> (&quot;John&quot;, &quot;Engineering&quot;, 75000),<br> (&quot;Alice&quot;, &quot;HR&quot;, 65000),<br> (&quot;Bob&quot;, &quot;Finance&quot;, 70000),<br> (&quot;David&quot;, &quot;Engineering&quot;, 80000),<br>]</pre><p>We want to insert all of these records into SQL Server.</p><p><strong>## 2. The Simple Approach: `cursor.execute()`</strong></p><p>The most straightforward solution is to execute the SQL statement once for every row.</p><pre>query = &quot;&quot;&quot;<br>  INSERT INTO employees (name, department, salary)<br>  VALUES (?, ?, ?)<br>&quot;&quot;&quot;<br><br>for employee in employees:<br>  cursor.execute(query, employee)<br><br>connection.commit()</pre><p>For four records, this is completely reasonable.</p><p>But imagine we have:</p><pre>employees = load_100000_employees()</pre><p>Now the loop executes the statement **100,000 times**.</p><p>The problem isn&#39;t necessarily the SQL statement itself.</p><p>The problem is the repeated execution overhead.</p><p>Conceptually, we&#39;re doing:</p><pre>Python<br> |<br> | execute()<br> v<br>SQL Server<br><br>Python<br> |<br> | execute()<br> v<br>SQL Server<br><br>Python<br> |<br> | execute()<br> v<br>SQL Server<br><br>... repeated thousands of times</pre><p>For large datasets, this can become expensive.</p><p><strong>## 3. Enter `executemany()`</strong></p><p>Instead of calling `execute()` repeatedly, we can provide the database driver with multiple sets of parameters.</p><pre>query = &quot;&quot;&quot;<br> INSERT INTO employees (name, department, salary)<br> VALUES (?, ?, ?)<br>&quot;&quot;&quot;<br>cursor.executemany(query, employees)<br>connection.commit()</pre><p>Now the intention is much clearer:</p><p>&gt; Execute this parameterized statement for all these rows.</p><p>The data remains separate from the SQL statement:</p><pre>employees = [<br> (&quot;John&quot;, &quot;Engineering&quot;, 75000),<br> (&quot;Alice&quot;, &quot;HR&quot;, 65000),<br> (&quot;Bob&quot;, &quot;Finance&quot;, 70000),<br>]</pre><p>And the query remains parameterized:</p><pre>query = &quot;&quot;&quot;<br> INSERT INTO employees (name, department, salary)<br> VALUES (?, ?, ?)<br>&quot;&quot;&quot;</pre><p>This is preferable to constructing SQL strings manually.</p><p><strong>## 4. Why Not Build One Huge SQL Statement?</strong></p><p>Someone might ask:</p><p>&gt; Why not just construct one enormous `INSERT` statement?</p><p>For example:</p><pre>INSERT INTO employees (name, department, salary)<br>VALUES<br>(&#39;John&#39;, &#39;Engineering&#39;, 75000),<br>(&#39;Alice&#39;, &#39;HR&#39;, 65000),<br>(&#39;Bob&#39;, &#39;Finance&#39;, 70000);</pre><p>Although multi-row inserts can be useful, dynamically generating SQL from application data introduces problems.</p><p>For example:</p><pre>query = f&quot;&quot;&quot;<br>INSERT INTO employees (name, department, salary)<br>VALUES (&#39;{name}&#39;, &#39;{department}&#39;, {salary})<br>&quot;&quot;&quot;</pre><p>This is a bad pattern.</p><p>It can introduce SQL injection vulnerabilities and problems with escaping quotes, special characters, data types, and NULL values.</p><p>Parameterized queries are much safer:</p><pre>cursor.executemany(<br> &quot;&quot;&quot;<br> INSERT INTO employees (name, department, salary)<br> VALUES (?, ?, ?)<br> &quot;&quot;&quot;,<br> employees<br>)</pre><p>Let the database driver handle parameter binding.</p><p><strong>## 5. `fast_executemany`: The SQL Server Performance Booster</strong></p><p>If you&#39;re using **pyodbc**, one of the most interesting options for SQL Server bulk inserts is:</p><pre>cursor.fast_executemany = True</pre><p>For example:</p><pre>cursor.fast_executemany = True<br>cursor.executemany(<br> &quot;&quot;&quot;<br> INSERT INTO employees (name, department, salary)<br> VALUES (?, ?, ?)<br> &quot;&quot;&quot;,<br> employees<br>)<br>connection.commit()</pre><p>This changes how pyodbc handles `executemany()` and can significantly improve performance for large batches.</p><p>The important point is that:</p><pre>executemany()</pre><p>and:</p><pre>fast_executemany = True</pre><p>are related, but they aren&#39;t the same thing.</p><p>Think of it as:</p><pre>executemany()<br> |<br> +-- Execute a parameterized operation for many rows<br> |<br> +-- fast_executemany=True<br> |<br> +-- Optimize how pyodbc sends those rows</pre><p>For SQL Server workloads involving many parameterized inserts, this can make a substantial difference.</p><p><strong>## 6. Complete Python Example</strong></p><p>Let&#39;s put everything together.</p><p>First, install pyodbc:</p><pre>pip install pyodbc</pre><p>Then create a connection:</p><pre>import pyodbc<br><br>connection = pyodbc.connect(<br> &quot;DRIVER={ODBC Driver 18 for SQL Server};&quot;<br> &quot;SERVER=localhost;&quot;<br> &quot;DATABASE=MyDatabase;&quot;<br> &quot;UID=myuser;&quot;<br> &quot;PWD=mypassword;&quot;<br> &quot;TrustServerCertificate=yes;&quot;<br>)<br>cursor = connection.cursor()</pre><p>Now prepare the data:</p><pre>employees = [<br> (&quot;John&quot;, &quot;Engineering&quot;, 75000),<br> (&quot;Alice&quot;, &quot;HR&quot;, 65000),<br> (&quot;Bob&quot;, &quot;Finance&quot;, 70000),<br> (&quot;David&quot;, &quot;Engineering&quot;, 80000),<br>]</pre><p>Execute the batch:</p><pre>query = &quot;&quot;&quot;<br> INSERT INTO employees (name, department, salary)<br> VALUES (?, ?, ?)<br>&quot;&quot;&quot;<br>cursor.fast_executemany = True<br>cursor.executemany(query, employees)<br>connection.commit()</pre><p>Finally:</p><pre>cursor.close()<br>connection.close()</pre><p>A complete version:</p><pre>import pyodbc<br><br>connection = pyodbc.connect(<br> &quot;DRIVER={ODBC Driver 18 for SQL Server};&quot;<br> &quot;SERVER=localhost;&quot;<br> &quot;DATABASE=MyDatabase;&quot;<br> &quot;UID=myuser;&quot;<br> &quot;PWD=mypassword;&quot;<br> &quot;TrustServerCertificate=yes;&quot;<br>)<br>cursor = connection.cursor()<br><br>employees = [<br> (&quot;John&quot;, &quot;Engineering&quot;, 75000),<br> (&quot;Alice&quot;, &quot;HR&quot;, 65000),<br> (&quot;Bob&quot;, &quot;Finance&quot;, 70000),<br> (&quot;David&quot;, &quot;Engineering&quot;, 80000),<br>]<br><br>query = &quot;&quot;&quot;<br> INSERT INTO employees (name, department, salary)<br> VALUES (?, ?, ?)<br>&quot;&quot;&quot;<br><br>try:<br>  cursor.fast_executemany = True<br>  cursor.executemany(query, employees)<br>  connection.commit()<br>except Exception:<br>  connection.rollback()<br>  raise<br>finally:<br> cursor.close()<br> connection.close()</pre><p>This is a much better starting point for production code than repeatedly calling `execute()` inside a loop.</p><p><strong>## 7. Don&#39;t Forget Transactions</strong></p><p>Performance isn&#39;t the only concern.</p><p>You also need to think about what happens when something goes wrong.</p><p>Suppose you&#39;re inserting 10,000 records.</p><p>If you commit every record individually:</p><pre>for employee in employees:<br>  cursor.execute(query, employee)<br>  connection.commit()</pre><p>you&#39;re creating a huge amount of transaction overhead.</p><p>It also creates an awkward failure scenario.</p><p>What happens if record 7,532 fails?</p><p>You could end up with thousands of records already committed.</p><p>Instead, you can execute the batch and commit once:</p><pre>try:<br> cursor.fast_executemany = True<br> cursor.executemany(query, employees)<br>connection.commit()<br>except Exception:<br> connection.rollback()<br> raise</pre><p>Now the application has a much clearer transaction boundary.</p><p><strong>## 8. What About Millions of Rows?</strong></p><p>This is where things get more interesting.</p><p>You might have:</p><pre>data = load_one_million_records()</pre><p>Should you do this?</p><pre>cursor.executemany(query, data)</pre><p>Maybe.</p><p>But blindly sending an enormous batch isn&#39;t always the best design.</p><p>A better approach can be to process the data in chunks.</p><p>For example:</p><pre>BATCH_SIZE = 5000<br>for start in range(0, len(data), BATCH_SIZE):<br>  batch = data[start:start + BATCH_SIZE]<br>cursor.executemany(query, batch)<br>connection.commit()</pre><p>With `fast_executemany`:</p><pre>cursor.fast_executemany = True<br>BATCH_SIZE = 5000<br>for start in range(0, len(data), BATCH_SIZE):<br>  batch = data[start:start + BATCH_SIZE]<br>cursor.executemany(query, batch)<br>connection.commit()</pre><p>This gives you a reasonable balance between:</p><p>* performance<br>* memory consumption<br>* transaction size<br>* error handling<br>* operational control</p><p><strong>## 9. Choosing a Batch Size</strong></p><p>There isn&#39;t a universal batch size that works for every application.</p><p>You might start with:</p><pre>BATCH_SIZE = 1000</pre><p>Then test:</p><pre>BATCH_SIZE = 5000</pre><p>Then:</p><pre>BATCH_SIZE = 10000</pre><p>And compare the results.</p><p>The optimal value depends on factors such as:</p><p>* row size<br>* number of columns<br>* indexes<br>* triggers<br>* constraints<br>* network latency<br>* SQL Server configuration<br>* driver version<br>* available memory<br>* transaction log behavior<br>* hardware</p><p>Don&#39;t choose a batch size just because someone on the internet said &quot;10,000 is optimal.&quot;</p><p>**Benchmark your actual workload.**</p><p><strong>## 10. Benchmarking `execute()` vs `executemany()`</strong></p><p>Let&#39;s create a simple benchmark.</p><p>We&#39;ll generate 10,000 rows:</p><pre>data = [<br> (f&quot;Employee {i}&quot;, &quot;Engineering&quot;, 50000 + i)<br> for i in range(10000)<br>]</pre><p>### Approach 1: `execute()` in a loop</p><pre>import time<br>start = time.perf_counter()<br>for row in data:<br> cursor.execute(query, row)<br>connection.commit()<br>elapsed = time.perf_counter() - start<br>print(f&quot;execute(): {elapsed:.2f} seconds&quot;)</pre><p>### Approach 2: `executemany()`</p><pre>start = time.perf_counter()<br>cursor.executemany(query, data)<br>connection.commit()<br>elapsed = time.perf_counter() - start<br>print(f&quot;executemany(): {elapsed:.2f} seconds&quot;)</pre><p>### Approach 3: `fast_executemany`</p><pre>cursor.fast_executemany = True<br>start = time.perf_counter()<br>cursor.executemany(query, data)<br>connection.commit()<br>elapsed = time.perf_counter() - start<br>print(f&quot;fast_executemany: {elapsed:.2f} seconds&quot;)</pre><p><strong>## 11. Don&#39;t Publish Someone Else&#39;s Benchmark as Your Own</strong></p><p>This is an important point if you&#39;re writing a technical article.</p><p>You will find many examples online claiming things like:</p><pre>execute() → 60 seconds<br>executemany() → 10 seconds<br>fast_executemany → 2 seconds</pre><p>Those numbers may be completely different on your machine.</p><p>A benchmark depends on:</p><pre>Python version<br> +<br>pyodbc version<br> +<br>ODBC Driver version<br> +<br>SQL Server version<br> +<br>network latency<br> +<br>hardware<br> +<br>table indexes<br> +<br>row size<br> +<br>batch size<br> +<br>transaction configuration</pre><p>So don&#39;t present made-up numbers as universal performance results.</p><p>Instead, benchmark your own environment.</p><p>A useful benchmark table could look like this:</p><p>| Method | Rows | Time | Rows/sec |<br>| ------------------ | -----: | ----: | -------: |<br>| `execute()` loop | 10,000 | X sec | X |<br>| `executemany()` | 10,000 | X sec | X |<br>| `fast_executemany` | 10,000 | X sec | X |</p><p>Calculate throughput using:</p><pre>rows_per_second = len(data) / elapsed</pre><p>This gives you a much more meaningful comparison.</p><p><strong>## 12. A Reusable Bulk Insert Function</strong></p><p>Instead of putting the logic directly into your application code, create a reusable function.</p><pre>def bulk_insert(cursor, query, data, batch_size=5000):<br>  cursor.fast_executemany = True<br><br>  for start in range(0, len(data), batch_size):<br>    batch = data[start:start + batch_size]<br>    cursor.executemany(query, batch)</pre><p>Then:</p><pre>try:<br>  bulk_insert(<br>    cursor,<br>    query,<br>    employees,<br>    batch_size=5000<br>  )<br><br>  connection.commit()<br>except Exception:<br>  connection.rollback()<br>  raise</pre><p>This makes the database layer easier to maintain.</p><p><strong>## 13. A More Production-Friendly Version</strong></p><p>For larger applications, I&#39;d also add validation and logging.</p><pre>import logging<br>logger = logging.getLogger(__name__)<br><br>def bulk_insert(cursor, query, data, batch_size=5000):<br>  if not data:<br>    return 0<br>  <br>  cursor.fast_executemany = True<br>  total = len(data)<br>  for start in range(0, total, batch_size):<br>    batch = data[start:start + batch_size]<br>    cursor.executemany(query, batch)<br>    logger.info(<br>      &quot;Inserted batch: %d-%d of %d&quot;,<br>      start + 1,<br>      min(start + batch_size, total),<br>      total<br>    )<br>  return total</pre><p>Usage:</p><pre>try:<br>  inserted = bulk_insert(<br>    cursor,<br>    query,<br>    data,<br>    batch_size=5000<br>  )<br>connection.commit()<br>logger.info(&quot;Successfully inserted %d rows&quot;, inserted)<br><br>except Exception:<br> connection.rollback()<br> logger.exception(&quot;Bulk insert failed&quot;)<br> raise</pre><p>Now you have:</p><p>* batching<br>* logging<br>* transactions<br>* error handling<br>* reusable code</p><p><strong>## 14. Common Mistakes</strong></p><p>## Mistake 1: Using string formatting for SQL</p><p>Avoid:</p><pre>query = f&quot;&quot;&quot;<br>INSERT INTO employees<br>VALUES (&#39;{name}&#39;, &#39;{department}&#39;, {salary})<br>&quot;&quot;&quot;</pre><p>Prefer:</p><pre>query = &quot;&quot;&quot;<br>INSERT INTO employees (name, department, salary)<br>VALUES (?, ?, ?)<br>&quot;&quot;&quot;<br>cursor.execute(query, (name, department, salary))</pre><p>And for multiple rows:</p><pre>cursor.executemany(query, data)</pre><p>## Mistake 2: Committing inside the loop</p><p>Avoid:</p><pre>for row in data:<br>  cursor.execute(query, row)<br>  connection.commit()</pre><p>This can introduce significant transaction overhead.</p><p>Instead:</p><pre>cursor.executemany(query, data)<br>connection.commit()</pre><p>Or use controlled batches when the dataset is very large.</p><p>## Mistake 3: Assuming `executemany()` automatically means maximum performance</p><p>This is an important distinction.</p><p>`executemany()` is not a magic &quot;bulk loader.&quot;</p><p>Performance depends on the database driver and how it implements the operation.</p><p>With pyodbc and SQL Server, test:</p><pre>cursor.fast_executemany = True</pre><p>against the default behavior.</p><p>## Mistake 4: Using one gigantic batch</p><p>This:</p><pre>cursor.executemany(query, millions_of_rows)</pre><p>might work, but it isn&#39;t automatically the best approach.</p><p>Large batches can increase:</p><p>* memory usage<br>* transaction size<br>* transaction log pressure<br>* failure recovery time<br>* operational complexity</p><p>Use benchmarking to find an appropriate batch size.</p><p><strong>## 15. `executemany()` vs `BULK INSERT`</strong></p><p>At this point, you might wonder:</p><p>&gt; Is `executemany()` always the best way to load data into SQL Server?</p><p>No.</p><p>For extremely large datasets, SQL Server&#39;s bulk-loading mechanisms may be more appropriate.</p><p>For example:</p><pre>BULK INSERT</pre><p>can be useful when loading data from files.</p><p>There are also other approaches depending on your architecture, including:</p><p>* `bcp`<br>* SQL Server bulk-copy APIs<br>* staging tables<br>* table-valued parameters<br>* SSIS<br>* ETL pipelines</p><p>The right choice depends on your use case.</p><p>A useful rule of thumb is:</p><pre>Small number of rows<br> ↓<br>execute()<br>Many parameterized rows<br> ↓<br>executemany()<br>Many rows + pyodbc + SQL Server<br> ↓<br>executemany() + fast_executemany<br>Very large ETL/file loads<br> ↓<br>Consider dedicated bulk-loading mechanisms</pre><p>This isn&#39;t a strict rule, but it&#39;s a useful starting point.</p><p><strong>## 16. What I Would Use in a Real Application</strong></p><p>For a typical Python service that needs to insert thousands of records into SQL Server, I&#39;d start with:</p><pre>query = &quot;&quot;&quot;<br> INSERT INTO employees (<br> name,<br> department,<br> salary<br> )<br> VALUES (?, ?, ?)<br>&quot;&quot;&quot;<br>BATCH_SIZE = 5000<br>try:<br> cursor.fast_executemany = True<br>for start in range(0, len(data), BATCH_SIZE):<br> batch = data[start:start + BATCH_SIZE]<br>cursor.executemany(query, batch)<br>connection.commit()<br>except Exception:<br> connection.rollback()<br> raise</pre><p>Then benchmark it.</p><p>Don&#39;t assume that 5,000 is optimal.</p><p>Test:</p><pre>1,000<br>5,000<br>10,000<br>25,000</pre><p>and measure:</p><pre>total execution time<br>rows/second<br>memory usage<br>transaction log impact</pre><p>Choose the configuration based on actual results.</p><p><strong># 17. The Bigger Lesson</strong></p><p>The important lesson isn&#39;t simply:</p><p>&gt; &quot;Use `executemany()`.&quot;</p><p>The bigger lesson is to understand **where the bottleneck is**.</p><p>If your application processes 100,000 rows, the database isn&#39;t necessarily spending most of its time executing the `INSERT` itself.</p><p>You may also be paying for:</p><pre>Python loop<br> ↓<br>Driver<br> ↓<br>Parameter binding<br> ↓<br>Network<br> ↓<br>SQL Server<br> ↓<br>Transaction<br> ↓<br>Transaction log<br> ↓<br>Indexes / constraints / triggers</pre><p>When you optimize bulk operations, you need to consider the entire path.</p><p>`executemany()` helps reduce application-side repetition.</p><p>`fast_executemany` can further optimize parameterized batch operations in pyodbc.</p><p>Batching gives you control over resource usage.</p><p>Transactions give you consistency.</p><p>And benchmarking tells you whether the optimization actually worked.</p><p><strong>## Conclusion</strong></p><p>If you&#39;re inserting a handful of rows into SQL Server, `cursor.execute()` is perfectly adequate.</p><p>But when your application starts processing thousands or hundreds of thousands of rows, repeatedly executing the same statement can become a serious performance bottleneck.</p><p>That&#39;s where `cursor.executemany()` becomes valuable:</p><pre>cursor.executemany(query, data)</pre><p>And when using pyodbc with SQL Server, it&#39;s worth testing:</p><pre>cursor.fast_executemany = True</pre><p>For larger workloads, combine it with sensible batching:</p><pre>for start in range(0, len(data), 5000):<br>  cursor.executemany(query, data[start:start + 5000])</pre><p>And protect the operation with a transaction:</p><pre>try:<br> ...<br> connection.commit()<br>except Exception:<br> connection.rollback()<br> raise</pre><p>Most importantly, **measure before and after**.</p><p>The best batch size, driver configuration, and loading strategy depend on your actual workload.</p><p>Don&#39;t optimize based purely on assumptions.</p><p>Run the benchmark.</p><p>Measure the throughput.</p><p>Then choose the approach that works best for your system.</p><p>---</p><p>### Key Takeaways</p><p>* Use `execute()` for small numbers of operations.<br>* Use `executemany()` when executing the same parameterized statement for many rows.<br>* With pyodbc + SQL Server, test `fast_executemany = True`.<br>* Avoid committing inside a row-by-row loop.<br>* Use transactions to maintain consistency.<br>* Use batching for very large datasets.<br>* Benchmark different batch sizes instead of assuming one is optimal.<br>* For massive ETL workloads, consider SQL Server&#39;s dedicated bulk-loading mechanisms.<br>* Never build SQL queries by concatenating untrusted input.</p><p>Bulk database operations aren&#39;t just about writing fewer lines of Python.</p><p>They&#39;re about reducing unnecessary work between your application and the database.</p><p>And sometimes, a single line like:</p><pre>cursor.fast_executemany = True</pre><p>can be the difference between a bulk operation that takes minutes and one that finishes dramatically faster.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f18c3822ae0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding range() vs xrange() in Python]]></title>
            <link>https://medium.com/@nikhilbaxi3/understanding-range-vs-xrange-in-python-82d16eee52b3?source=rss-a8226d719ecf------2</link>
            <guid isPermaLink="false">https://medium.com/p/82d16eee52b3</guid>
            <category><![CDATA[xrange]]></category>
            <category><![CDATA[range]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Nikhilbaxi]]></dc:creator>
            <pubDate>Fri, 12 Jun 2026 17:09:40 GMT</pubDate>
            <atom:updated>2026-06-12T17:09:40.557Z</atom:updated>
            <content:encoded><![CDATA[<p>While learning Python, I came across range() and xrange(). They look similar, but there is an important difference, especially if you work with older Python code.</p><p>range() is used to generate a sequence of numbers, usually in loops.</p><pre>for i in range(5):<br>    print(i)</pre><p>Output:</p><pre>0<br>1<br>2<br>3<br>4</pre><p>In Python 2, xrange() was a memory-efficient version of range().</p><pre>for i in xrange(5):<br>    print(i)</pre><p>Instead of creating the entire list in memory, it generated values as needed.</p><h3>Key Difference</h3><p>In Python 2:</p><ul><li>range() returns a list.</li><li>xrange() returns an iterator-like object and uses less memory.</li></ul><p>Example:</p><pre>range(1000000)   # Creates a large list<br>xrange(1000000)  # Generates values on demand</pre><h3>What About Python 3?</h3><p>Python 3 removed xrange().</p><p>The current range() behaves like the old xrange(), making it memory efficient by default.</p><pre>r = range(1000000)<br>print(type(r))</pre><p>Output:</p><pre>&lt;class &#39;range&#39;&gt;</pre><h3>Conclusion</h3><p>If you’re using Python 3, you only need range(). It provides the same memory-efficient behavior that xrange() offered in Python 2. Knowing the difference is still useful when reading legacy code or answering interview questions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82d16eee52b3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Event Loop with Microtasks and Macrotasks in JavaScript]]></title>
            <link>https://medium.com/@nikhilbaxi3/understanding-event-loop-with-microtasks-and-macrotasks-in-javascript-fbb5cc8ee6d8?source=rss-a8226d719ecf------2</link>
            <guid isPermaLink="false">https://medium.com/p/fbb5cc8ee6d8</guid>
            <category><![CDATA[event-loop]]></category>
            <category><![CDATA[mutationobserver]]></category>
            <category><![CDATA[javascript-development]]></category>
            <category><![CDATA[micro-tasks]]></category>
            <category><![CDATA[messagechannel]]></category>
            <dc:creator><![CDATA[Nikhilbaxi]]></dc:creator>
            <pubDate>Sun, 19 Apr 2026 08:04:06 GMT</pubDate>
            <atom:updated>2026-04-19T08:04:06.835Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’ve ever seen JavaScript print values in an unexpected order, you’ve probably run into the event loop.</p><p>A common example looks like this:</p><pre>console.log(&quot;start&quot;);<br><br>setTimeout(() =&gt; {<br>  console.log(&quot;timeout&quot;);<br>}, 0);<br><br>Promise.resolve().then(() =&gt; {<br>  console.log(&quot;promise&quot;);<br>});<br><br>console.log(&quot;end&quot;);</pre><p>Many developers expect this output:</p><pre>start<br>timeout<br>promise<br>end</pre><p>But the actual output is:</p><pre>start<br>end<br>promise<br>timeout</pre><p>Why?</p><p>The answer lies in JavaScript’s event loop and the difference between microtasks and macrotasks.</p><h3>JavaScript Is Single-Threaded</h3><p>JavaScript executes one thing at a time.</p><p>That means if one piece of code is running, another piece has to wait.</p><p>However, JavaScript can still handle asynchronous operations like timers, API calls, and promises because it uses queues.</p><p>The event loop decides which queue to process next.</p><h3>What Are Macrotasks?</h3><p>Macrotasks are regular asynchronous tasks.</p><p>These tasks are placed into the macrotask queue and are executed only after:</p><ol><li>The current synchronous code is complete</li><li>All pending microtasks are complete</li></ol><p>Common examples of macrotasks include:</p><ul><li>setTimeout</li><li>setInterval</li><li>DOM events like clicks</li><li>setImmediate in some environments</li><li>MessageChannel callbacks</li></ul><p>Example:</p><pre>setTimeout(() =&gt; {<br>  console.log(&quot;macrotask&quot;);<br>}, 0);</pre><p>Even with a delay of 0, the callback does not run immediately.</p><p>It still waits for the current code and microtasks to finish.</p><h3>What Are Microtasks?</h3><p>Microtasks are smaller, higher-priority tasks.</p><p>They are executed immediately after the current synchronous code finishes, before the event loop picks the next macrotask.</p><p>Common examples of microtasks include:</p><ul><li>Promise.then()</li><li>Promise.catch()</li><li>Promise.finally()</li><li>queueMicrotask()</li><li>MutationObserver</li></ul><p>Example:</p><pre>Promise.resolve().then(() =&gt; {<br>  console.log(&quot;microtask&quot;);<br>});</pre><p>Because promises use the microtask queue, they run before setTimeout callbacks.</p><h3>Understanding the Execution Order</h3><p>Let’s revisit the original example:</p><pre>console.log(&quot;start&quot;);<br><br>setTimeout(() =&gt; {<br>  console.log(&quot;timeout&quot;);<br>}, 0);<br><br>Promise.resolve().then(() =&gt; {<br>  console.log(&quot;promise&quot;);<br>});<br><br>console.log(&quot;end&quot;);</pre><p>Execution happens in this order:</p><ol><li>console.log(&quot;start&quot;) runs</li><li>setTimeout callback is added to the macrotask queue</li><li>Promise callback is added to the microtask queue</li><li>console.log(&quot;end&quot;) runs</li><li>Synchronous code finishes</li><li>All microtasks run</li><li>Then the first macrotask runs</li></ol><p>That is why the output becomes:</p><pre>start<br>end<br>promise<br>timeout</pre><h3>Easy Rule to Remember</h3><p>A simple rule is:</p><blockquote><em>Synchronous code first, then microtasks, then macrotasks.</em></blockquote><h3>Why This Matters</h3><p>Understanding microtasks and macrotasks helps you:</p><ul><li>Debug asynchronous code faster</li><li>Avoid confusing execution order bugs</li><li>Perform better in interviews</li><li>Understand how promises really work</li><li>Write more predictable JavaScript</li></ul><p>This concept becomes even more important when working with frameworks like Angular, React, or Node.js, where promises, timers, and async behavior appear everywhere.</p><h3>What Is the Event Loop?</h3><p>The event loop is the mechanism in JavaScript that decides what code should run next.</p><p>JavaScript is single-threaded, which means it can only execute one thing at a time. The event loop makes asynchronous behavior possible by continuously checking whether the call stack is empty and whether there are pending tasks waiting in queues.</p><p>The process generally looks like this:</p><ol><li>Run all synchronous code</li><li>Run all pending microtasks</li><li>Run the next macrotask</li><li>Repeat</li></ol><p>A simple mental model is:</p><pre>Call Stack → Microtask Queue → Macrotask Queue</pre><p>The event loop keeps repeating this cycle for as long as the application is running.</p><h3>What Is MessageChannel?</h3><p>MessageChannel is a browser API that creates two connected ports that can send messages to each other.</p><p>Callbacks triggered by MessageChannel are treated as macrotasks, similar to setTimeout.</p><p>Example:</p><pre>const channel = new MessageChannel();<br><br>channel.port1.onmessage = () =&gt; {<br>  console.log(&quot;MessageChannel callback&quot;);<br>};<br><br>console.log(&quot;start&quot;);<br><br>channel.port2.postMessage(&quot;hello&quot;);<br><br>console.log(&quot;end&quot;);</pre><p>Output:</p><pre>start<br>end<br>MessageChannel callback</pre><p>Why?</p><ol><li>start runs immediately</li><li>postMessage() schedules a macrotask</li><li>end runs immediately</li><li>Then the event loop processes the onmessage callback</li></ol><p>MessageChannel is often used internally by libraries and frameworks because it can schedule tasks faster and more consistently than setTimeout(..., 0).</p><p>For example, older versions of React used MessageChannel internally for scheduling work.</p><h3>What Is MutationObserver?</h3><p>MutationObserver is a browser API that watches for changes in the DOM.</p><p>It can detect things like:</p><ul><li>Elements being added or removed</li><li>Attribute changes</li><li>Text changes inside elements</li></ul><p>Its callback is placed in the microtask queue, so it runs before macrotasks like setTimeout.</p><p>Example:</p><pre>const div = document.createElement(&quot;div&quot;);<br><br>const observer = new MutationObserver(() =&gt; {<br>  console.log(&quot;DOM changed&quot;);<br>});<br><br>observer.observe(div, {<br>  attributes: true<br>});<br><br>div.setAttribute(&quot;class&quot;, &quot;active&quot;);<br><br>console.log(&quot;end&quot;);</pre><p>Output:</p><pre>end<br>DOM changed</pre><p>Why?</p><ol><li>setAttribute() changes the DOM immediately</li><li>The MutationObserver callback is scheduled as a microtask</li><li>end logs first because it is still part of the current synchronous code</li><li>After synchronous code finishes, the microtask queue runs</li></ol><p>MutationObserver is commonly used for:</p><ul><li>Watching dynamic UI updates</li><li>Detecting when elements are inserted into the page</li><li>Integrating with third-party scripts</li><li>Building browser extensions</li><li>Tracking changes in large applications like Angular or React</li></ul><h3>Final Thoughts</h3><p>The event loop can feel confusing at first, but once you understand the queue priority, the behavior becomes much easier to predict.</p><p>Remember:</p><ul><li>Synchronous code runs first</li><li>Then microtasks run</li><li>Then macrotasks run</li></ul><p>Once you understand that rule, most JavaScript async questions become much easier to solve.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fbb5cc8ee6d8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Trade Strategies: Basic-Basic: Moving Average Crossovers ]]></title>
            <link>https://medium.com/@nikhilbaxi3/trade-strategies-basic-basic-moving-average-crossovers-103b7931b6ff?source=rss-a8226d719ecf------2</link>
            <guid isPermaLink="false">https://medium.com/p/103b7931b6ff</guid>
            <category><![CDATA[indicators]]></category>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[charts]]></category>
            <category><![CDATA[basics]]></category>
            <category><![CDATA[moving-average-crossover]]></category>
            <dc:creator><![CDATA[Nikhilbaxi]]></dc:creator>
            <pubDate>Fri, 27 Dec 2024 19:07:20 GMT</pubDate>
            <atom:updated>2024-12-27T19:07:20.297Z</atom:updated>
            <content:encoded><![CDATA[<h3>Trade Strategies: Basic-Basic: Moving Average Crossovers.📊📈</h3><p><strong>Disclaimer:</strong> You might not like it, but I want to share it anyway — also record it for my own memory. I could be a little wrong about what I’m doing, and you might love or hate my opinion about it. Either way, feel free to comment. Cheers!!</p><p>I am the kind of person who learns by doing stuff and failing many times. So during the COVID period, I thought of making myself learn the stock market. I am still learning.</p><p>I made all the rookie mistakes, and still do, like:<br> — Panic buying and selling.<br> — Buy &amp; Sell from friends, family &amp; colleagues suggestions.<br> — Brought in Intraday at the wrong time, and sold at the wrong time.</p><p>If you have not played with your hard-earned adult money you may not understand it, Or if you have made a profit in the stock market.</p><p>I am not an expert in reading indicators, but this Moving Average Crossovers, casually explained to me by my mother-in-law between tea and snacks, surprisingly helped me make good decisions.</p><h3><strong>Moving Average Cross Over:</strong></h3><p>Picture your chart with an “X” or “+” mark to show when to buy and sell. this somewhat does that.</p><p>If you’re struggling to picture it, don’t worry — here’s a chart to make it crystal clear:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BFPJf2RnG-E69yjln9iBYA.png" /><figcaption>Moving Average Cross indicator</figcaption></figure><h3>What is a Moving Average?</h3><p>A moving average (MA) is a statistical calculation that smooths out price data to create a trend-following indicator.</p><p>Now here in the chart, the colour of the line green and red is of choice and you can change it to something else.</p><p>The Green line is for the min days: here 10 days<br>The Red line is for the max days: here 30 days<br>The + or the X here is of importance</p><p><strong>You Sell when the green line crosses the red line from the top.<br>You Buy when the red line crosses the green line from the top.</strong></p><p>So simple right that’s it… That is all you need to know.<br>try adding this indicator to your charts and see the difference.</p><p><strong>Please read the below lines too</strong></p><p>Now this is only one chart and one indicator, this may not tell you the exact story, also this doesn’t work sometimes — it tells you to sell and buy in a short time interval, as shown in the chart. but please do your study on this indicator. there are many YouTube videos and blogs that will help you learn</p><p>Once you know how to use one indicator you will learn how to combine it with multiple ones and then apply it to make your decision.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=103b7931b6ff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Visual Studio Code: Secrets of Regular Expression Search]]></title>
            <link>https://medium.com/@nikhilbaxi3/visual-studio-code-secrets-of-regular-expression-search-71723c2ecbd2?source=rss-a8226d719ecf------2</link>
            <guid isPermaLink="false">https://medium.com/p/71723c2ecbd2</guid>
            <category><![CDATA[search]]></category>
            <category><![CDATA[regex]]></category>
            <category><![CDATA[vs-code-editor]]></category>
            <category><![CDATA[vscode]]></category>
            <dc:creator><![CDATA[Nikhilbaxi]]></dc:creator>
            <pubDate>Sat, 16 Sep 2023 11:39:02 GMT</pubDate>
            <atom:updated>2023-09-16T11:39:02.664Z</atom:updated>
            <content:encoded><![CDATA[<p>Visual Studio Code (VS Code) is a popular code editor that developers use. Today I would like to delve into powerful functionalities of vs-code to enhance your coding experience and hopefully improve your productivity.</p><h3>Power of Regular Expression Search:</h3><p>Regular expressions (regex) are patterns that allow you to search text based on certain rules. let’s look on what’s is the efficient way to do this.</p><p>To Activate Regular Expression search we have to click on the .* button on the search bar as shown in the below image</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/459/1*k_X5uNfzUxf4bIkRRHrq8A.png" /><figcaption>To Activate the regex search</figcaption></figure><h3>Basic Regular Expression Syntax</h3><ul><li>.: Matches any single character except a new line.</li><li>*: Matches zero or more occurrences of the preceding character or group.</li><li>+: Matches one or more occurrences of the preceding character or group.</li><li>?: Matches zero or one occurrence of the preceding character or group.</li><li>^: Matches the start of a line.</li><li>$: Matches the end of a line.</li><li>[...]: Matches any one of the characters inside the brackets.</li><li>[^...]: Matches any character not inside the brackets.</li><li>(...|...): Matches either the left or right expression.</li></ul><h3><strong>Syntax for Pattern Matching</strong></h3><ul><li>\b: Word Boundary<br>\bword\b matches the whole word &quot;word&quot; within a string.</li><li>\s: Whitespace<br>\s matches any whitespace character (space, tab, newline).</li><li>\S: Non-Whitespace<br>\S matches any non-whitespace character.</li><li>\w: Word Character<br>\w matches any word character (alphanumeric or underscore).</li><li>\W: Non-Word Character<br>\W matches any non-word character.</li><li>.: Any Character<br>. matches any single character except a newline.</li><li>^: Start of String<br>^word matches &quot;word&quot; only at the start of a string.</li><li>$: End of String<br>word$ matches &quot;word&quot; only at the end of a string.</li><li>[]: Character Class<br>[aeiou] matches any vowel.<br>[0-9] matches any digit.<br>[^aeiou] matches any character that is not a vowel.</li><li>|: Alternation<br>word1|word2 matches either &quot;word1&quot; or &quot;word2&quot;.</li><li>(): Grouping<br>(abc)+ matches one or more occurrences of &quot;abc&quot;.</li><li>*: Zero or More<br>a* matches zero or more occurrences of &quot;a&quot;.</li><li>+: One or More<br>a+ matches one or more occurrences of &quot;a&quot;.</li><li>?: Zero or One<br>colou?r matches &quot;color&quot; or &quot;colour&quot;.</li><li>{}: Quantifiers<br>a{3} matches exactly three occurrences of &quot;a&quot;.<br>a{2,4} matches two to four occurrences of &quot;a&quot;.</li><li>\d: Digit<br>\d matches any digit (equivalent to [0-9]).</li><li>\D: Non-Digit<br>\D matches any non-digit.</li><li>\A: Start of String (similar to ^, but unaffected by multiline mode)</li><li>\Z: End of String or Before Newline at the End</li><li>\n, \t, \r: Newline, Tab, Carriage Return</li></ul><p>Ohh My these are certainly a lot of those,<br>but the best ones I usually use are:</p><ol><li>(.+) : This is used to find the content between the unknown <br>For example, we need to find where the API call is defined.</li></ol><p>Consider the Api defined in your app is like:<br>`/api/user/${userId}/address/` or `/api/user/123/address/`</p><p>It is really difficult because we have different user-id</p><p>Here, we can search like:<br>`<strong>/api/user/(.+)/address</strong>/`</p><p>2. Another one will be like we usually type multiple letters like<br>like and we need a way to find this in my whole code<br>the way to do this is:<br>`<strong>\b(\w+)\s+\1\b</strong>`<br>this will find all the duplicate words for you</p><p>3. To find all lines with both “apple” and “banana”:<br>`(apple.*banana)|(banana.*apple)`</p><h3>Conclusion</h3><p>Mastering regular expression search in Visual Studio Code empowers you to tailor your coding environment to your liking. Regular expressions enable precise and flexible search capabilities.</p><p>Incorporate these tips and tricks into your workflow to optimize your coding experience in VS Code.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=71723c2ecbd2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>