<?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 Praya P on Medium]]></title>
        <description><![CDATA[Stories by Praya P on Medium]]></description>
        <link>https://medium.com/@praya.p1923?source=rss-ed21c8d1664c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*1rcBs6ZO_fjUy-iR</url>
            <title>Stories by Praya P on Medium</title>
            <link>https://medium.com/@praya.p1923?source=rss-ed21c8d1664c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 11:15:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@praya.p1923/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[Optimization in SQL]]></title>
            <link>https://medium.com/@praya.p1923/optimization-in-sql-87bd22567d53?source=rss-ed21c8d1664c------2</link>
            <guid isPermaLink="false">https://medium.com/p/87bd22567d53</guid>
            <dc:creator><![CDATA[Praya P]]></dc:creator>
            <pubDate>Sun, 20 Sep 2026 18:01:26 GMT</pubDate>
            <atom:updated>2026-09-20T18:01:26.028Z</atom:updated>
            <content:encoded><![CDATA[<p>Optimization refers to the process of making something good, effective, and functional, so query optimization in SQL is the process of writing or structuring SQL statements so that the database can execute them with the lowest amount of memory, CPU, and disk Input Output, resulting in faster response times.</p><p>Following are some of the powerful and actionable techniques used to optimize SQL performance</p><ol><li><strong>Smart Data Retrieval</strong></li></ol><ul><li><strong><em>Avoid SELECT * </em>:</strong> Specify only the exact columns you need. Fetching extra columns wastes memory, clutters network bandwidth, and blocks the database from using covering indexes.</li></ul><pre>--   Unoptimized query <br>SELECT * from products;<br><br>--   Optimized query <br>SELECT product_id, product_name, product_price FROM products;</pre><ul><li><strong><em>Filter early with WHERE</em></strong><em> </em><strong>:</strong> Use the WHERE clause to filter out unwanted rows immediately before doing any heavy processing or joining. Do not use HAVING for conditions that don&#39;t involve aggregated data.</li></ul><pre>-- Unoptimized query <br>SELECT * FROM employees WHERE YEAR(hire_date) = 2024;<br><br>-- Optimized query <br>SELECT * FROM employees <br>WHERE hire_date &gt;= &#39;2024-01-01&#39; AND hire_date &lt; &#39;2025-01-01&#39;;</pre><ul><li><strong><em>Avoid Unnecessary use of LIMIT </em>: </strong>It is important to limit the number of rows we are retrieving, not just columns. The queries usually slow down when the number of rows increases. We can use <strong>LIMIT </strong>to reduce the number of rows returned. This feature prevents us from unintentionally retrieving thousands of rows of data when we only need to work with a few. The <strong>LIMIT </strong>function is especially helpful for validation queries or inspecting the output of a transformation we&#39;re working on. It’s ideal for experimentation and understanding how our code behaves. However, it may not be suitable for automated data models, where we need to return the entire dataset.</li></ul><pre>SELECT name <br>FROM customers <br>ORDER BY customer_group DESC <br>LIMIT 99;</pre><p><strong>2. Efficient Joins &amp; Subqueries</strong></p><ul><li><strong><em>Use explicit INNER JOIN </em>:</strong> Prefer INNER JOIN over a generic WHERE CROSS JOIN or LEFT JOIN if you only want matching rows, as it allows the optimizer more flexibility. An <strong>inner join</strong> returns only the rows with a match in both tables. If a record exists in one table but not the other, that record will be excluded from the result.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*X_87aPoQb5JS06UnH489hQ.avif" /><figcaption>Inner Join : Image source <a href="https://www.datacamp.com/cheat-sheet/sql-joins-cheat-sheet"><strong><em>SQL-Join cheat sheet</em></strong></a><strong><em>.</em></strong></figcaption></figure><ul><li><strong><em>Prefer EXISTS over IN</em> : </strong>When working with subqueries, we often need to check if a value exists in a set of results. We can do this with two IN or EXISTS, but EXISTS is generally more efficient, especially for larger datasets.</li><li>The IN clause reads the entire subquery result set into memory before comparing. On the other hand, the EXISTS clause stops processing the subquery as soon as it finds a match.</li><li>Here we have an example of how to use this clause</li></ul><pre>SELECT * <br>FROM orders dela<br>WHERE EXISTS (SELECT 1 FROM customers c WHERE c.customer_id = dela.customer_id AND c.country = &#39;Japan&#39;);</pre><ul><li><strong><em>Optimize subqueries</em></strong> : In some cases, we are writing a query and feel we need to dynamically perform some filtering, aggregation, or joins of data. We don’t want to do several queries; instead, we want to keep it to a single query.<br>For those cases, we can use Subqueries. Subqueries in SQL are queries nested inside another query, typically in the SELECT, UPDATE , INSERT or DELETE statements.<br>Subqueries can be powerful and fast, but they can also cause performance issues if they are not used carefully. As a rule, we should minimize the use of subqueries and follow a set of best practices:</li><li><strong>Replace subqueries with joins when possible.</strong> Joins are generally faster and more efficient than subqueries.</li><li><strong>Use CTEs for readability, Temp Tables for performance:</strong> Use Common Table Expressions<strong> (CTEs)</strong> to organize logic, but switch to Temporary Tables if you are interacting with large intermediate datasets multiple times within the same script</li></ul><pre>-- Unoptimized subquery <br>SELECT customer_id FROM customers WHERE customer_id IN (SELECT customer_id FROM orders);<br><br>--  Optimized existence check <br>SELECT customer_id FROM customers c WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id);</pre><p><strong>4. Use Proper Indexing</strong></p><p>Imagine we are searching for a book in a library without a catalog. We’d have to check every shelf and every row until we finally found it. Indexes in a database are similar to catalogs. They help us quickly locate the data we need without scanning the entire table.</p><p><strong>How indexes work</strong></p><p>Indexes are data structures that improve the speed at which data is retrieved. They work by creating a sorted copy of the indexed columns, which allows the database to quickly pinpoint the rows that match our query, saving us a lot of time.</p><p>There are three main types of indexes in databases:</p><ul><li><strong>Clustered indexes</strong> — Physically order data based on column values and are best used for sequential or sorted data with no duplicates, such as primary keys.</li><li><strong>Non-clustered indexes</strong> — Create two separate columns, making them suitable for mapping tables or glossaries.</li><li><strong>Full-text indexes</strong> — Used to search large text fields, like articles or emails, by storing the positions of terms within the text.</li></ul><p>So, how can we use indexes to improve the performance of SQL queries? Let’s see some best practices:</p><ul><li><strong>Index frequently queried columns</strong>. If we usually search a table using customer_id or item_id , indexing those columns will greatly impact speed. Check below how to create an index:</li></ul><pre>CREATE INDEX index_customer_id ON customers (customer_id);</pre><p><strong>5. Limit the use of DISTINCT</strong></p><p>Imagine that we are working on an analysis for sending a promotional offer to customers from unique cities. The database has multiple orders from the same customers. The first thing that pops into our mind is using the DISTINCT clause.</p><p>This function is handy for certain cases but can be resource-intensive, especially on large datasets. There are a few alternatives to DISTINCT:</p><ul><li><strong>Identify and remove duplicate data during data cleaning processes</strong>. This prevents duplicates from creeping into our database in the first place.</li><li><strong>Use GROUP BY instead of DISTINCT when possible : </strong>GROUP BY<em> </em>can be more efficient, especially when combined with aggregate functions.</li></ul><pre>-- Inefficient query <br>SELECT DISTINCT city FROM customers;<br><br>-- Optimized query <br>SELECT city FROM customers GROUP BY city;</pre><p><strong>6. Avoid Unnecessary Ordering and Grouping</strong></p><p>As data practitioners, we like to have our data ordered and grouped so we can gain insights more easily. We usually use ORDER BY and GROUP BY in our SQL queries.</p><p>However, both clauses can be computationally expensive, especially when dealing with large datasets. When sorting or aggregating data, the database engine must often perform a full scan of the data and then organize it, identify the groups, and/or apply aggregate functions, typically using resource-intensive algorithms.</p><p>To optimize the queries, we can follow some of these tips:</p><ul><li><strong>Minimize sorting</strong>. We should only use ORDER BY when necessary. If sorting is not essential, omitting this clause can help us dramatically reduce processing time.</li><li><strong>Use indexes.</strong> When possible, we should make sure that the columns involved in ORDER BY and GROUP BY are indexed.</li><li><strong>Push sorting to the application layer</strong>. If it is possible, we should push the sorting operation to the application layer rather than the database.</li><li><strong>Pre-aggregate data</strong>. For complex queries involving GROUP BY, we could pre-aggregate the data at an earlier stage , so the database doesn’t need to compute the same aggregates repeatedly.</li></ul><p><strong>Conclusion</strong></p><p>In this article, we have explained various strategies and best practices for optimizing SQL queries, from indexing and joins to subqueries and database-specific features. By applying these techniques, you can significantly improve the performance of your queries and make databases run more efficiently.</p><p>Optimizing SQL queries is an ongoing process. As your data grows and your application evolves, you’ll need to continually monitor and optimize your queries to ensure they’re running at optimal performance.</p><p>“Big thanks to Imarticus Learning — Data Science and Analytics with GEN AI course , which helped me to start my data enthusist journey”</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87bd22567d53" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>