<?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 Dhroov Gupta on Medium]]></title>
        <description><![CDATA[Stories by Dhroov Gupta on Medium]]></description>
        <link>https://medium.com/@dhroovgupta?source=rss-822a483b043d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*oaW238yJ7u7we0BOZ8Wwfg.png</url>
            <title>Stories by Dhroov Gupta on Medium</title>
            <link>https://medium.com/@dhroovgupta?source=rss-822a483b043d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 07:17:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dhroovgupta/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[All About Database Internals (Part-3): Indexing]]></title>
            <link>https://dhroovgupta.medium.com/all-about-database-internals-part-3-indexing-a75dfc9f06c2?source=rss-822a483b043d------2</link>
            <guid isPermaLink="false">https://medium.com/p/a75dfc9f06c2</guid>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[index]]></category>
            <category><![CDATA[database-design]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Dhroov Gupta]]></dc:creator>
            <pubDate>Thu, 13 Jul 2023 19:45:57 GMT</pubDate>
            <atom:updated>2023-07-13T19:45:57.822Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*BXp0MRSX55TNrpVubLFR8A.jpeg" /></figure><p>In the last part of this series, We talked about <a href="https://medium.com/@dhroovgupta/all-about-database-internals-part-2-how-database-stores-table-on-disk-866f71b2195">How Database Stores Tables on Disk</a> and why it is necessary to understand them. If you haven’t read it, I’ll recommend giving it a read once before this one.</p><p>In this article, We’ll discuss a very interesting topic Database internals: <em>INDEXING</em>.</p><h3>What are indexes?</h3><p>An index is a data structure that helps the database engine finds exactly where the page is located in heap memory.</p><p>As we have discussed Pages and heap memory in our previous article, The rows are stored in Pages and if we know exactly where this page exists, we can get our results much faster rather than scanning the whole heap memory.</p><p>Let’s deep dive into it to understand why we need an index.</p><h3>Why do we need Indexes?</h3><p>We discussed the performance impact on queries with and without indexes in our <a href="https://dhroovgupta.medium.com/all-about-database-internals-part-2-how-database-stores-table-on-disk-866f71b2195">previous article</a> in which we saw when we run the select query on the employee&#39;s table without an index, it runs the <strong>parallel sequential scan</strong> which means it uses multiple worker threads to scan the pages parallel. But still, it’s slower than using an index.</p><p>With an Index, The database engine traverses the B-Tree in <strong>O(log(n)) </strong>where<strong> </strong>n is the number of nodes in the tree. After finding the node, it has the pointer to the page where the row is present in Heap memory.</p><p>Traversing the B-Tree can still take <strong>multiple I/O operations</strong> to find the right node. But still, it’s very fast compared to sequential scans.</p><p>There is a very good <a href="https://medium.com/towards-data-science/how-b-tree-indexes-are-built-in-a-database-6f847fb3cfcc">article</a> about B-Tree that explains the behavior and the process of traversing.</p><h3>Primary vs Secondary Indexes</h3><p>There are typically two types of indexes in the database</p><h4>Primary Index</h4><p>A primary index is an index on the primary key on the table. In most database systems, the <strong>primary index is automatically created</strong> when a table is defined with a primary key. Also, primary keys are unique in nature so it makes sense to have an index to improve performance.</p><p>Depending on the database, the primary key will also be clustered or non-clustered index which means the rows are physically stored in the same order as the primary key values.</p><h4>Secondary Index</h4><p>A secondary index is an index on the column apart from the primary key. Unlike the primary index, there can be multiple secondary indexes in the table.</p><p>As the secondary index does not apply to the primary key, the column can have duplicate values. So it changes the behavior of the traversal.</p><p>When a secondary index contains duplicate values, The database engine includes an additional column called the <strong>row ID</strong> within the index structure.</p><p>The row ID is a unique identifier that allows the database engine to locate the actual row within the table.</p><p>PostgreSQL and MySQL have a slight difference in the implementation of handling primary and secondary indexes. Let’s deep dive into it.</p><h3>MySQL vs PostgreSQL Indexes</h3><p>As we have discussed Primary and Secondary indexes, There is a slight difference in handling between MySQL and PostgreSQL.</p><h4>MySQL</h4><ol><li>The primary index has the complete row data in the node of the B-tree.</li><li>The node of the secondary index contains the primary key of the row.</li><li>When the database engine traverses the secondary index and found the node, It will go to the primary index with the primary key and get the row data as MySQL doesn&#39;t use the heap to store the rows data.</li></ol><h4>PostgreSQL</h4><ol><li>In PostgreSQL, all the indexes are considered as secondary indexes.</li><li>The primary index is created on row ID which is a unique hidden ID for every row in the table.</li><li>PostgreSQL stores the complete row data in heap memory, unlike MySQL which stores it in the B-Tree node itself.</li><li>When the database engine traverses the secondary index and found the node, It will go to the primary index with the row ID.</li><li>In the primary index, the nodes contain the row ID and pointer to the page inside the heap.</li></ol><p>That’s it, we have covered the overview of the indexes and deep dive into some of the index core implementations.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a75dfc9f06c2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[All About Database Internals(Part-2): How Database Stores Table On Disk]]></title>
            <link>https://dhroovgupta.medium.com/all-about-database-internals-part-2-how-database-stores-table-on-disk-866f71b2195?source=rss-822a483b043d------2</link>
            <guid isPermaLink="false">https://medium.com/p/866f71b2195</guid>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[database-indexing]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Dhroov Gupta]]></dc:creator>
            <pubDate>Sun, 28 May 2023 21:28:21 GMT</pubDate>
            <atom:updated>2023-07-13T12:52:53.349Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*DzFN6CrpchrHc5yOhIskbA.jpeg" /></figure><p>In the last part of this series, We talked about <a href="https://medium.com/@dhroovgupta7/all-about-databases-internals-part-1-acid-aef9d494ec85">ACID properties</a> and why it is necessary to understand them.</p><p>In this article, We&#39;ll discuss a very interesting topic about Database internals: HOW<em> DATABASE STORES TABLES ON DISK.</em></p><h3>Overview</h3><p>We all know that relational databases stores data in the form of tables, and inside those tables some rows determine an entry of a single entity(Example: User, Employee).</p><p>But behind the scenes, the database engine stores these rows, and tables differently from what we see on the client side. Let&#39;s take a look.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/833/1*EiiJ7e489gDfKkS2KQUcZQ.png" /><figcaption>Pages Representation in Heap</figcaption></figure><p>The rows in the table are stored in <strong>Pages, </strong>these pages are a block of storage sitting in the <strong>Heap</strong> that can contain multiple rows. Now here things get interesting, when we query the database to fetch the row the database engine gets the <strong>whole page</strong> that has the row, not a single row.</p><p>Let&#39;s dive deep into some of the terms we used in this section.</p><h3>Page</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/387/1*DWP6AHgBiU9-Dbpm8nh-XQ.png" /><figcaption>Page Representation</figcaption></figure><p>A Page is a fixed-size block of data stored in the disk, they are stored <strong>contiguously</strong> which means they are next to each other in the storage disk so that the data retrieval process is efficient.</p><p>A single page can store multiple rows depending upon the size of the page and the size of a single row. By default, the size of the page in MySQL and Postgres are 16KB and 8KB respectively. We can configure it according to our needs.</p><h3>IO</h3><p>An IO means a call to disk to read/write data.</p><p>When we execute a query, the database engine will do an IO operation to fetch the pages from the disk. It can fetch more than one page in a single IO depending upon various factors like data size, and disk access patterns.</p><blockquote>IO is expensive, less IO means more efficient</blockquote><h3>Heap</h3><p>A heap is a storage structure, which is used to store the pages of the table on disk.</p><p>When the data is inserted into the table, the database engine typically appends the new rows to the last page of the heap on the disk. If the last page becomes full, a new page is allocated to accommodate the additional rows. This process continues as more data is inserted, resulting in multiple pages forming the heap.</p><h3>How query executes?</h3><p>In this section, we&#39;ll see how the database engine executes the query behind the scenes and its performance.</p><p><strong>Setup Database:</strong></p><pre>CREATE TABLE employees (id SERIAL, name VARCHAR(255), salary INT);<br>INSERT INTO employees (name, salary) SELECT substr(md5(random()::text), 0, 10), floor(random() * (1000 - 1 + 1) + 1)::int from generate_series(1, 1000000);</pre><p>We have created a table of <em>employees </em>with 1 million records of random values.</p><p>Now, let&#39;s execute a query to see the performance and how it is executed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kwb_bQDvMVJrUPl93yDN6w.png" /></figure><p>As we can see in the image, this select query took <em>183.5ms</em> which is quite high in terms of database.</p><p>Let&#39;s understand why it took so much time —</p><ul><li><strong>EXPLAIN ANALYZE</strong> query in Postgres shows the execution plan of the query.</li><li>As we can see, Postgres did the Parallel seq scan which means instead of doing a full table scan it used multiple worker processes to scan the whole table in parallel.</li><li>Postgres assigns a range of pages in a heap to each worker process, and then it scans all the pages and returns the pages which have the data required.</li><li>There were <strong>333337 rows</strong> removed after filtering as shown in the result which means all the pages were pulled from the heap and then in the memory, the Postgres engine filtered the rows based on the where clause.</li></ul><p>How can we improve the performance?</p><p>There is one thing we can use — <strong>INDEX</strong></p><h3><strong>Index</strong></h3><p>An Index is another data structure separate from the heap that has pointers to the heap data.</p><p>Once we find the index, we can directly go to that page in the heap and fetch the data required, we don&#39;t have to do a full table scan.</p><p>We can index one or more columns based on our needs.</p><p>Typically, data structures for the index are <strong>B-tree or B+ Tree.</strong></p><p>I&#39;ll write about B-tree in depth in the later part of the series.</p><p>Now, let&#39;s see the index in action and how it will improve the performance of the same query.</p><h3>How query executes with the index?</h3><p>Let&#39;s create the index on the primary key <strong>id.</strong></p><pre>CREATE INDEX on employees (id);<br>EXPLAIN ANALYZE SELECT name, salary from employees where id=923456;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oiLrxRkRCTRZqftPf9gRyw.png" /></figure><p>We ran the above statements and we can see it only took <strong><em>0.2ms </em></strong>to get the results.</p><p>Let&#39;s break down this execution plan shown in the image —</p><ul><li>Postgres did scan the index first to get the pointer of the page in the heap.</li><li>After getting the page from the heap, it filters the page in the memory and returned the requested data.</li></ul><p>That&#39;s it, this is a high-level view of how the database stores data and how it retrieves it with and without an index.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=866f71b2195" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[All About Database Internals(Part-1): ACID]]></title>
            <link>https://dhroovgupta.medium.com/all-about-databases-internals-part-1-acid-aef9d494ec85?source=rss-822a483b043d------2</link>
            <guid isPermaLink="false">https://medium.com/p/aef9d494ec85</guid>
            <category><![CDATA[acid]]></category>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Dhroov Gupta]]></dc:creator>
            <pubDate>Thu, 11 May 2023 20:46:57 GMT</pubDate>
            <atom:updated>2023-06-29T19:17:58.158Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*m3zQtuPpySDkOgUmYCGdfg.jpeg" /><figcaption>ACID Properties</figcaption></figure><p>In this article series, I&#39;ll talk about some database internals that helps you understand some fundamentals of how it actually works behind the scenes.</p><p><strong>NOTE</strong>: I&#39;ll be using Postgres for the examples.</p><h3>Introduction</h3><p>In this part of the series, I&#39;ll talk about <strong>ACID. </strong>It&#39;s very important to know what is it and why this is a necessary feature to have especially in relational databases.</p><p><strong>ACID</strong> stands for <em>Atomicity, Consistency, Isolation, and Durability</em></p><p>It ensures that the transaction will leave the database in a valid state even in the event of unexpected errors.</p><p>Let&#39;s dig deeper into this</p><h3>Transaction</h3><p>It is a set of <strong>Database</strong> <strong>Queries </strong>which act as a single unit of work.</p><p>We can do multiple operations (INSERT, UPDATE, DELETE) on any table.</p><p>Example:</p><p>This is a table called <em>bank_account.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/1*p2rjHskFI5CpEdrJCxe56g.png" /><figcaption>bank_account Table</figcaption></figure><pre>BEGIN TRANSACTION;<br>SELECT * FROM bank_account where id = 1;<br>UPDATE bank_account SET balance = 1500 where id = 1;<br>COMMIT;</pre><p>Let&#39;s break this set of commands and understand each statement:</p><blockquote>BEGIN TRANSACTION;</blockquote><p>This statement tells the database engine to start the transaction. Every query after this will only be reflected in the database after we <strong>commit</strong> it.</p><blockquote>SELECT * FROM bank_account where id = 1;</blockquote><p>This is a simple select query to get the information of the account owner of ID 1.</p><blockquote>UPDATE bank_account SET balance = 1500 where id = 1;</blockquote><p>This is an update query that will update the balance of the account owner to 1500.</p><blockquote>COMMIT;</blockquote><p>Now, this is a very important part of the transaction. After writing all the queries in the transactions, <strong>we have to commit</strong> the changes so that the data will reflect in the database. Without committing the transaction the changes will not get updated to the database.</p><h3>Atomicity</h3><p>It means that the transaction is <strong>one unit of work</strong>, It will be either successful or rollback in case of any error.</p><p>The queries inside the transaction should be successfully executed in order to complete the transaction.</p><p>If one of the queries is unsuccessful due to any reason, The transaction will fail and all the previous queries will be rollback.</p><p>Example:</p><p>Let&#39;s take the previous table bank_account</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/1*p2rjHskFI5CpEdrJCxe56g.png" /><figcaption>bank_account Table</figcaption></figure><pre>BEGIN TRANSACTION;<br>UPDATE bank_account SET balance = 3000 where id = 1;<br>UPDATE bank_account SET balance = 1500 where id = &#39;ABCD&#39;; //Error<br>ROLLBACK;</pre><p>In this transaction, We&#39;ll get the error because <em>id=’ABCD’</em> is invalid where-clause as this is an invalid input type. So the entire transaction will fail and the previous query will roll back and there will be no changes to the table.</p><h3>Consistency</h3><p>It means that the data remains correct before and after the transaction completes. If we update the balance of the user&#39;s account in the transaction, then we should get the updated value in the select query after the transaction completes.</p><p>Example:</p><pre>BEGIN TRANSACTION;<br>UPDATE bank_account SET balance = 3000 where id = 1;<br>COMMIT;<br><br>SELECT balance from bank_account where id = 1; /* =&gt; 3000 */</pre><h3>Isolation</h3><p>This is an important feature to understand here, Isolation means if there are two transactions running parallel then one transaction cannot change the outcome of the other transaction.</p><p>But there are different types of Isolation levels that we need to understand because that can change the behavior of the transaction.</p><ol><li><strong>Read uncommitted — </strong>In this type of Isolation level, the data can change in between the transaction if another transaction update that row. It is called <strong>dirty read. </strong>Note<strong> — Postgres </strong>handle dirty read by default but it&#39;s important to know.</li><li><strong>Read committed</strong> — In this type of Isolation level, the data cannot change in one transaction even if another transaction updates that row until it gotten committed. Let&#39;s see this example.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MjDDW76syNMtbainKPkyVw.png" /><figcaption>Read Committed Example</figcaption></figure><p>In this example, We can we are running two transactions and before committing the left transaction, we were getting an old balance. But after committing it, we are getting the updated balance.</p><p>The problem with this isolation level is if the transaction rollback, then we lost the updates.</p><p>3. <strong>Repeatable read</strong> — This is one level higher in isolation level, In the case even if transaction-2 commits, Transaction-1 will not see the updated data and that&#39;s what we want, No other transaction can change the outcome of another. Let’s see this example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aXUpi2AuS1OYTNAfD0ltNg.png" /><figcaption>Repeatable Read Example</figcaption></figure><p>In this example, the left side of the screen is running the transaction with an isolation level of repeatable read. So, even if the right-side transaction tries to update the row and commits, it doesn&#39;t change the result for the left-side transaction.</p><p>But the problem with this isolation level is <strong>Phantom Reads, </strong>which means if any transaction inserted a new row then the other transaction result can change even if repeatable read isolation level.</p><p><strong>Note:</strong> Phantom Reads only happens in MySQL, not in Postgres.</p><p>4. <strong>Serializable</strong> — This is the safest isolation level we can have, In this type of isolation level transactions are run as if they are serialized one after the other.</p><p>See this image to understand the types of isolation levels and what we can achieve from them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*8T3oXNG4QMTpmYd_GGFJgQ.png" /></figure><h3><strong>Durability</strong></h3><p>It is the final part of ACID, Durability basically ensures that our transactions that have been committed must be persisted in any failure or database down. So, if we restart the database our data will be there.</p><p>There are a few techniques that databases use to ensure durability —</p><ol><li>WAL (Write Ahead Log) — When we do a query, the database engine writes the data to memory first and flushes the data to disk in a single IO to improve performance. Also, it writes the log to disk so that if the database crashes, then using those logs the data can be created again.</li><li>OS Cache — A Write request to OS goes to the OS cache first, So if the OS crashes then we can lose our data. In order to bypass this, we can use <strong>Fsync </strong>OS<strong> </strong>command which forces write to disk. But it can slow down commits.</li></ol><h3>Conclusion</h3><p>ACID properties (Atomicity, Consistency, Isolation, and Durability) provide a set of guidelines for ensuring that database transactions are reliable and consistent, and that data is protected from errors and inconsistencies. These properties are essential for maintaining data integrity and accuracy, especially in critical applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aef9d494ec85" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>