<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="https://feeds.feedblitz.com/feedblitz_rss.xslt"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:webfeeds="http://webfeeds.org/rss/1.0"  xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0">
<channel>
	<title>Baeldung - SQL</title>
	<atom:link href="https://www.baeldung.com/sql/feed" rel="self" type="application/rss+xml" />
	<link>https://www.baeldung.com/sql</link>
	<description></description>
	<lastBuildDate>Wed, 04 Nov 2026 22:51:54 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
<meta xmlns="http://www.w3.org/1999/xhtml" name="robots" content="noindex" />
<item>
<feedburner:origLink>https://www.baeldung.com/sql/mysql-file-import-cmd-line</feedburner:origLink>
		<title>Import an SQL File Using the Command Line in MySQL</title>
		<link>https://feeds.feedblitz.com/~/925427168/0/baeldung/sql~Import-an-SQL-File-Using-the-Command-Line-in-MySQL</link>
		
		<dc:creator><![CDATA[Kapil Khandelwal]]></dc:creator>
		<pubDate>Sat, 27 Sep 2025 02:17:01 +0000</pubDate>
				<category><![CDATA[database-manipulation]]></category>
		<category><![CDATA[Databases]]></category>
		<category><![CDATA[Autocommit]]></category>
		<category><![CDATA[MySQL]]></category>
		<guid isPermaLink="false">https://www.baeldung.com/sql/mysql-file-import-cmd-line</guid>
					<description><![CDATA[<img src="https://www.baeldung.com/wp-content/uploads/sites/7/2024/11/SQL-Featured-Image-05-1024x536.jpg" class="webfeedsFeaturedVisual wp-post-image" alt="" style="max-width:100% !important;height:auto !important;float: left; margin-right: 5px;" fetchpriority="high" />Explore commonly used command-line approaches to import an SQL file in MySQL.<div style="clear:both;padding-top:0.2em;"><a title="Like on Facebook" href="https://feeds.feedblitz.com/_/28/925427168/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/fblike20.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Pin it!" href="https://feeds.feedblitz.com/_/29/925427168/baeldung/sql,https%3a%2f%2fwww.baeldung.com%2fwp-content%2fuploads%2fsites%2f7%2f2024%2f11%2fSQL-Featured-Image-05-1024x536.jpg"><img height="20" src="https://assets.feedblitz.com/i/pinterest20.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Post to X.com" href="https://feeds.feedblitz.com/_/24/925427168/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/x.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Subscribe by email" href="https://feeds.feedblitz.com/_/19/925427168/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/email20.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Subscribe by RSS" href="https://feeds.feedblitz.com/_/20/925427168/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/rss20.png" style="border:0;margin:0;padding:0;"></a>&nbsp;<h3 style="clear:left;padding-top:10px">Related Stories</h3><ul><li><a rel="NOFOLLOW" href="https://www.baeldung.com/sql/mysql-configure-time-zone-settings">How to Configure Time Zone Settings in MySQL?</a></li><li><a rel="NOFOLLOW" href="https://www.baeldung.com/sql/apache-doris-tutorial">Introduction to Apache Doris</a></li><li><a rel="NOFOLLOW" href="https://www.baeldung.com/sql/cratedb-introduction">Introduction to CrateDB</a></li></ul>&#160;</div>]]>
</description>
										<content:encoded><![CDATA[<img src="https://www.baeldung.com/wp-content/uploads/sites/7/2024/11/SQL-Featured-Image-05-1024x536.jpg" class="webfeedsFeaturedVisual wp-post-image" alt="" style="float: left; margin-right: 5px;" decoding="async" srcset="https://www.baeldung.com/wp-content/uploads/sites/7/2024/11/SQL-Featured-Image-05-1024x536.jpg 1024w, https://www.baeldung.com/wp-content/uploads/sites/7/2024/11/SQL-Featured-Image-05-300x157.jpg 300w, https://www.baeldung.com/wp-content/uploads/sites/7/2024/11/SQL-Featured-Image-05-768x402.jpg 768w, https://www.baeldung.com/wp-content/uploads/sites/7/2024/11/SQL-Featured-Image-05-100x52.jpg 100w, https://www.baeldung.com/wp-content/uploads/sites/7/2024/11/SQL-Featured-Image-05-600x314.jpg 600w, https://www.baeldung.com/wp-content/uploads/sites/7/2024/11/SQL-Featured-Image-05.jpg 1200w" sizes="(max-width: 580px) 100vw, 580px" /><h2 id="bd-overview" data-id="overview">1. Overview</h2>
<div class="bd-anchor" id="overview"></div>
<p>Importing an SQL file is a basic operation for any MySQL user to restore a database from a backup, transfer data, share a database schema or configure a new environment. Although Graphical User Interface (GUI) applications such as <a href="https://feeds.feedblitz.com/~/t/0/0/baeldung/sql/~https://www.baeldung.com/linux/phpmyadmin-get-version-command-line">phpMyAdmin</a> are available, command line usage provides more control, efficiency, and reliability, especially for big files or scripted operations.</p>
<p>In this tutorial, we&#8217;ll discuss commonly used command-line approaches to import a <em>.sql</em> file.</p>
<h2 id="bd-using-shell-redirection" data-id="using-shell-redirection">2. Using Shell Redirection</h2>
<div class="bd-anchor" id="using-shell-redirection"></div>
<p>The most straightforward method is employing the <a href="https://feeds.feedblitz.com/~/t/0/0/baeldung/sql/~https://www.baeldung.com/linux/pipes-redirection#writing">redirection operator</a> of the shell (&lt;). This method redirects the contents of the SQL file directly to the <em>mysql</em> client program from the command line. Below is a one-line command to import the SQL file:</p>
<pre><code class="language-bash">$ mysql -u [username] -p [database_name] &lt; /path/to/file.sql</code></pre>
<p>The above command prompts to enter the password for the specified MySQL user. <strong>It&#8217;s crucial to have the target database already created before running this command, or else, the import fails.</strong></p>
<p>The primary advantage of this method is its simplicity. It’s a quick, single-line command that is easy to use in scripts. For small to medium-sized files, it&#8217;s highly efficient. But, if we&#8217;re importing a large file over a network, this method can sometimes be slower due to network latency, as it streams each query to the server one by one rather than as a single block.</p>
<h2 id="bd-using-the-source-command" data-id="using-the-source-command">3. Using the <em>source</em> Command</h2>
<div class="bd-anchor" id="using-the-source-command"></div>
<p>The second method is to log in to the MySQL command-line client first and then use the <a href="https://feeds.feedblitz.com/~/t/0/0/baeldung/sql/~https://www.baeldung.com/linux/source-command"><em>source</em></a> command. It has the advantage of offering an interactive session, with more control prior to starting the import:</p>
<pre><code class="language-bash">$ mysql -u [username] -p [database_name]</code></pre>
<p>When we&#8217;re logged in, we&#8217;ll get the <em>mysql&gt;</em> prompt. Using this prompt, we can execute the source command using the path to the SQL file:</p>
<pre><code class="language-bash">mysql&gt; source /path/to/file.sql;</code></pre>
<p>Again, we should check that the database [<em>database_name</em>] already exists before we start the process. The <em>source</em> command offers an immediate feedback, which generally displays the output of each command being run from the SQL file. This can be very reassuring to see during a large import.</p>
<p>MySQL, by default, executes with <a href="https://feeds.feedblitz.com/~/t/0/0/baeldung/sql/~https://dev.mysql.com/doc/refman/8.4/en/glossary.html#glos_autocommit"><em>autocommit</em></a> turned on. That is, every individual SQL statement, like an <em>INSERT</em> or an <em>UPDATE</em>, is executed as its own transaction and is automatically committed to the database right away. For a big SQL file containing thousands of statements, this leads to an enormous number of individual transactions, each of which takes a log flush to disk. This constant disk I/O is one of the major performance bottlenecks.</p>
<p>The below command snippet first selects the appropriate database and then imports the SQL file by treating it as a single transaction:</p>
<pre><code class="language-bash">mysql&gt; use db_name;
mysql&gt; SET autocommit=0 ; source file.sql ; COMMIT ;</code></pre>
<p>In the above command, we first disable the <em>autocommit. </em>By doing so, we ensure that all these statements are buffered and not written to disk immediately. All the updates from the SQL file are committed to the database in a single, bulk operation with the <em>COMMIT</em> statement. It needs only one log flush to disk, not one for each individual statement, which is where the huge performance improvement comes from.</p>
<p><strong>One of the big drawbacks to turning off <em>autocommit</em> is that the import is now an &#8220;all-or-nothing&#8221; process. If one of the statements in the SQL file fails, the whole transaction will be rolled back.</strong></p>
<h2 id="bd-conclusion" data-id="conclusion">4. Conclusion</h2>
<div class="bd-anchor" id="conclusion"></div>
<p>In this article, we compared various means of importing an SQL file from the command line in MySQL. For imports of small to medium-sized files, the redirection method is a great option for its simplicity. For large files, imports from a less stable network, or when we need more interactive feedback and control, the <em>source</em> command is the more secure and powerful choice.</p><Img align="left" border="0" height="1" width="1" alt="" style="border:0;float:left;margin:0;padding:0;width:1px!important;height:1px!important;" hspace="0" src="https://feeds.feedblitz.com/~/i/925427168/0/baeldung/sql">
<div style="clear:both;padding-top:0.2em;"><a title="Like on Facebook" href="https://feeds.feedblitz.com/_/28/925427168/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/fblike20.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Pin it!" href="https://feeds.feedblitz.com/_/29/925427168/baeldung/sql,https%3a%2f%2fwww.baeldung.com%2fwp-content%2fuploads%2fsites%2f7%2f2024%2f11%2fSQL-Featured-Image-05-1024x536.jpg"><img height="20" src="https://assets.feedblitz.com/i/pinterest20.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Post to X.com" href="https://feeds.feedblitz.com/_/24/925427168/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/x.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Subscribe by email" href="https://feeds.feedblitz.com/_/19/925427168/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/email20.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Subscribe by RSS" href="https://feeds.feedblitz.com/_/20/925427168/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/rss20.png" style="border:0;margin:0;padding:0;"></a>&nbsp;<h3 style="clear:left;padding-top:10px">Related Stories</h3><ul><li><a rel="NOFOLLOW" href="https://www.baeldung.com/sql/mysql-configure-time-zone-settings">How to Configure Time Zone Settings in MySQL?</a></li><li><a rel="NOFOLLOW" href="https://www.baeldung.com/sql/apache-doris-tutorial">Introduction to Apache Doris</a></li><li><a rel="NOFOLLOW" href="https://www.baeldung.com/sql/cratedb-introduction">Introduction to CrateDB</a></li></ul>&#160;</div>]]>
</content:encoded>
					
		
		
		<webfeeds:featuredImage>https://www.baeldung.com/wp-content/uploads/sites/7/2024/11/SQL-Featured-Image-05-150x150.jpg</webfeeds:featuredImage></item>
<item>
<feedburner:origLink>https://www.baeldung.com/sql/cratedb-introduction</feedburner:origLink>
		<title>Introduction to CrateDB</title>
		<link>https://feeds.feedblitz.com/~/924561767/0/baeldung/sql~Introduction-to-CrateDB</link>
		
		<dc:creator><![CDATA[Bhaskar Ghosh]]></dc:creator>
		<pubDate>Tue, 09 Sep 2025 05:40:40 +0000</pubDate>
				<category><![CDATA[Databases]]></category>
		<guid isPermaLink="false">https://www.baeldung.com/sql/?p=91519</guid>
					<description><![CDATA[<img src="https://www.baeldung.com/wp-content/uploads/sites/7/2024/11/SQL-Featured-Image-06-1024x536.jpg" class="webfeedsFeaturedVisual wp-post-image" alt="" style="max-width:100% !important;height:auto !important;float: left; margin-right: 5px;" />Discover CrateDB, an open-source, distributed SQL database designed for storing and running high-speed analytics on large volumes of data.<div style="clear:both;padding-top:0.2em;"><a title="Like on Facebook" href="https://feeds.feedblitz.com/_/28/924561767/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/fblike20.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Pin it!" href="https://feeds.feedblitz.com/_/29/924561767/baeldung/sql,https%3a%2f%2fwww.baeldung.com%2fwp-content%2fuploads%2fsites%2f7%2f2024%2f11%2fSQL-Featured-Image-06-1024x536.jpg"><img height="20" src="https://assets.feedblitz.com/i/pinterest20.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Post to X.com" href="https://feeds.feedblitz.com/_/24/924561767/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/x.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Subscribe by email" href="https://feeds.feedblitz.com/_/19/924561767/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/email20.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Subscribe by RSS" href="https://feeds.feedblitz.com/_/20/924561767/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/rss20.png" style="border:0;margin:0;padding:0;"></a>&nbsp;<h3 style="clear:left;padding-top:10px">Related Stories</h3><ul><li><a rel="NOFOLLOW" href="https://www.baeldung.com/sql/mysql-file-import-cmd-line">Import an SQL File Using the Command Line in MySQL</a></li><li><a rel="NOFOLLOW" href="https://www.baeldung.com/sql/mysql-configure-time-zone-settings">How to Configure Time Zone Settings in MySQL?</a></li><li><a rel="NOFOLLOW" href="https://www.baeldung.com/sql/apache-doris-tutorial">Introduction to Apache Doris</a></li></ul>&#160;</div>]]>
</description>
										<content:encoded><![CDATA[<img src="https://www.baeldung.com/wp-content/uploads/sites/7/2024/11/SQL-Featured-Image-06-1024x536.jpg" class="webfeedsFeaturedVisual wp-post-image" alt="" style="float: left; margin-right: 5px;" decoding="async" loading="lazy" srcset="https://www.baeldung.com/wp-content/uploads/sites/7/2024/11/SQL-Featured-Image-06-1024x536.jpg 1024w, https://www.baeldung.com/wp-content/uploads/sites/7/2024/11/SQL-Featured-Image-06-300x157.jpg 300w, https://www.baeldung.com/wp-content/uploads/sites/7/2024/11/SQL-Featured-Image-06-768x402.jpg 768w, https://www.baeldung.com/wp-content/uploads/sites/7/2024/11/SQL-Featured-Image-06-100x52.jpg 100w, https://www.baeldung.com/wp-content/uploads/sites/7/2024/11/SQL-Featured-Image-06-600x314.jpg 600w, https://www.baeldung.com/wp-content/uploads/sites/7/2024/11/SQL-Featured-Image-06.jpg 1200w" sizes="auto, (max-width: 580px) 100vw, 580px" /><h2 id="bd-introduction" data-id="introduction">1. Introduction</h2>
<div class="bd-anchor" id="introduction"></div>
<p>In this article, we&#8217;ll talk about <a href="https://feeds.feedblitz.com/~/t/0/0/baeldung/sql/~https://github.com/crate/crate">CrateDB</a>. <strong><em>CrateDB</em> is an open-source, distributed SQL database designed for storing and running high-speed analytics on large volumes of data</strong>.</p>
<p><em>CrateDB</em> combines the benefits of a SQL database and the scalability and flexibility that <a href="https://feeds.feedblitz.com/~/t/0/0/baeldung/sql/~https://www.baeldung.com/cs/sql-vs-nosql">NoSQL</a> databases provide.</p>
<p>In the following sections, we&#8217;ll install and run CrateDB. We&#8217;ll also delve into the features that make <em>CrateDB</em> a viable and lucrative database option.</p>
<h2 id="bd-installing-cratedb" data-id="installing-cratedb">2. Installing CrateDB</h2>
<div class="bd-anchor" id="installing-cratedb"></div>
<p>We can install and run <em>CrateDB</em> locally. <strong>It supports different operating systems, including Linux-based distributions, Mac OS, Windows, and even Docker.</strong></p>
<p>Additionally, there is a cloud-based offering called <em>CrateDB</em> <em>Cloud</em>, a fully managed service that does not require any installation.</p>
<h3 id="bd-1-installation-in-linux" data-id="1-installation-in-linux">2.1. Installation in Linux</h3>
<div class="bd-anchor" id="1-installation-in-linux"></div>
<p>Let&#8217;s install <em>CrateDB</em> on Debian or Ubuntu machines:</p>
<pre><code class="language-shell"># Install prerequisites.
sudo apt update
sudo apt install --yes apt-transport-https apt-utils curl gnupg lsb-release
# Import the public GPG key for verifying the package signatures.
curl -sS https://cdn.crate.io/downloads/debian/DEB-GPG-KEY-crate | \
    sudo tee /etc/apt/trusted.gpg.d/cratedb.asc
# Add CrateDB repository to Apt
echo "deb https://cdn.crate.io/downloads/debian/stable/ default main" | \
    sudo tee /etc/apt/sources.list.d/crate-stable.list
## Install
sudo apt install crate</code></pre>
<p>Once the installation is complete, we need to restart the service:</p>
<pre><code class="language-shell">sudo systemctl start crate</code></pre>
<h3 id="bd-2-installation-in-windows" data-id="2-installation-in-windows">2.2. Installation in Windows</h3>
<div class="bd-anchor" id="2-installation-in-windows"></div>
<p>For Windows machines, we need to download the <a href="https://feeds.feedblitz.com/~/t/0/0/baeldung/sql/~https://cdn.crate.io/downloads/releases/cratedb/x64_windows/">release archive</a>. Then we extract the archive using a tool like <em>7-Zip. </em>Now, let&#8217;s open <em>PowerShell</em> and run:</p>
<pre><code class="language-shell">unzip -o crate-*.zip
cd crate-*
./bin/crate</code></pre>
<p>When the installation is complete, the web Admin UI of <em>CrateDB</em> will be accessible at <em>http://localhost:4200</em>.</p>
<h2 id="bd-running-cratedb" data-id="running-cratedb">3. Running CrateDB</h2>
<div class="bd-anchor" id="running-cratedb"></div>
<p>Now that CrateDB is installed, let&#8217;s get started with using it. <strong>CrateDB has two main components, the Admin UI and the CrateDB Shell CLI(Crash).</strong></p>
<h3 id="bd-1-admin-ui" data-id="1-admin-ui">3.1. Admin UI</h3>
<div class="bd-anchor" id="1-admin-ui"></div>
<p>The Admin UI is a great interactive way to use <em>CrateDB</em> and comes with several useful tabs and a status<em> bar.</em></p>
<p><strong>The Status bar shows information essential to the running <em>CrateDB</em> node, including the Cluster name, the version of the <em>CrateDB</em> that is running, and the total number of nodes in the cluster.</strong></p>
<p>This also contains additional health checks for Data and Cluster status.</p>
<p>On the left panel, there are several tabs of the following:</p>
<ul>
<li>Overview screen</li>
<li>SQL console</li>
<li>Table browser</li>
<li>Views browser</li>
<li>Shards browser</li>
<li>Cluster browser</li>
<li>Monitoring</li>
</ul>
<p>Let&#8217;s check how the Admin UI looks with zero configurations done:</p>
<img loading="lazy" decoding="async" class="alignnone wp-image-91531" src="https://www.baeldung.com/wp-content/uploads/sites/7/2025/09/cratedb-admin-ui-1024x650.png" alt="Crate DB Admin UI" width="1100" height="698" srcset="https://www.baeldung.com/wp-content/uploads/sites/7/2025/09/cratedb-admin-ui-1024x650.png 1024w, https://www.baeldung.com/wp-content/uploads/sites/7/2025/09/cratedb-admin-ui-300x190.png 300w, https://www.baeldung.com/wp-content/uploads/sites/7/2025/09/cratedb-admin-ui-768x488.png 768w, https://www.baeldung.com/wp-content/uploads/sites/7/2025/09/cratedb-admin-ui-1536x975.png 1536w, https://www.baeldung.com/wp-content/uploads/sites/7/2025/09/cratedb-admin-ui-2048x1300.png 2048w, https://www.baeldung.com/wp-content/uploads/sites/7/2025/09/cratedb-admin-ui-100x63.png 100w, https://www.baeldung.com/wp-content/uploads/sites/7/2025/09/cratedb-admin-ui-600x381.png 600w" sizes="auto, (max-width: 1100px) 100vw, 1100px" />
<p>&nbsp;</p>
<h3 id="bd-2-crashcrate-db-shell" data-id="2-crashcrate-db-shell">3.2. Crash(Crate DB Shell)</h3>
<div class="bd-anchor" id="2-crashcrate-db-shell"></div>
<p><strong>The Crate DB shell is an interactive CLI application that works with CrateDB, and we can use it like a SQL terminal and node manager.</strong></p>
<p>Crash needs to connect to the CrateDB cluster to work:</p>
<pre><code class="language-shell">crash --hosts node1.example.com \
                node2.example.com \
        -c "SELECT * FROM sys.nodes" \
        --format json \
    &gt; output.json</code></pre>
<p>Crash supports several built-in commands, and a comprehensive list of such is present in the <a href="https://feeds.feedblitz.com/~/t/0/0/baeldung/sql/~https://cratedb.com/docs/crate/crash/en/latest/commands.html">documentation</a> page.</p>
<h2 id="bd-dynamic-data-handling-and-sql-support" data-id="dynamic-data-handling-and-sql-support">4. Dynamic Data Handling and SQL Support</h2>
<div class="bd-anchor" id="dynamic-data-handling-and-sql-support"></div>
<p>In this section, let&#8217;s talk about how CrateDB handles data internally.</p>
<h3 id="bd-1-data-in-cratedb" data-id="1-data-in-cratedb">4.1. Data in CrateDB</h3>
<div class="bd-anchor" id="1-data-in-cratedb"></div>
<p><strong>CrateDB is columnar</strong>. It therefore supports dynamic schemas and data structures that change on the fly without downtimes. This allows for storing and querying structured, semi-structured data, and unstructured data, such as raw JSONs, very easily.</p>
<p><strong>While traditional object-relational databases allow us to store and process JSON data only opaquely, CrateDB handles objects as first-level citizens.</strong></p>
<p>With such dynamic objects, when no strict schema is defined, CrateDB indexes all attributes by default, therefore allowing for efficient querying.</p>
<p><strong>CrateDB uses Apache <a href="https://feeds.feedblitz.com/~/t/0/0/baeldung/sql/~https://www.baeldung.com/lucene">Lucene</a> as its underlying storage layer</strong>. Therefore, it inherits its concepts about storage entities and units similar to <a href="https://feeds.feedblitz.com/~/t/0/0/baeldung/sql/~https://www.baeldung.com/elasticsearch-java"><em>Elasticsearch</em></a>.</p>
<p>Let&#8217;s consider the following example. We create a table for storing weather information with the following:</p>
<pre><code class="language-sql">CREATE TABLE weather_reading ( "timestamp" TIMESTAMP, "readings" OBJECT(DYNAMIC), "fields" OBJECT(DYNAMIC) );</code></pre>
<p>Let&#8217;s perform a DML query on the table:</p>
<pre><code class="language-sql">INSERT INTO weather_reading ( timestamp, readings, fields ) VALUES ( '2025-07-16T00:00:00', { "site_id" = 007 }, { "temperature" = 21.92, "humidity" = 100 } );</code></pre>
<p>Now, we can leverage the power of CrateDB to efficiently query the dynamic data:</p>
<pre><code class="language-sql">SELECT
  *
FROM
  reading
WHERE
  readings['site_id'] = 
  '007';</code></pre>
<h3 id="bd-2-sql-support" data-id="2-sql-support">4.2. SQL Support</h3>
<div class="bd-anchor" id="2-sql-support"></div>
<p><strong>There is native support for standard SQL baked into CrateDB. This includes joins, subqueries, indexing, and aggregations</strong>. This makes it very easy to integrate with existing SQL-based clients. <em>CrateDB</em> uses the PostgreSQL wire protocol and is therefore compatible with many PostgreSQL tools and clients.</p>
<p>An automatic advantage that comes out of this is that integration with systems using traditional database access interfaces like ODBC or <a href="https://feeds.feedblitz.com/~/t/0/0/baeldung/sql/~https://www.baeldung.com/java-jdbc">JDBC</a> is much simpler.</p>
<h3 id="bd-3-search-in-cratedb" data-id="3-search-in-cratedb">4.3. Search in CrateDB</h3>
<div class="bd-anchor" id="3-search-in-cratedb"></div>
<p><strong><em>CrateDB </em>offers native <em>BM25</em> term search and vector search, all while using SQL.</strong></p>
<p>This enables powerful single-query hybrid search over massive volumes of data.</p>
<p>Additionally,<strong> there is full-text search functionality with an <em>inverted index</em> and <em>Okapi BM25</em> search ranking at scale.</strong></p>
<p><em>CrateDB </em>also natively supports Geo-search and semantic search on Vector embeddings through <strong><a href="https://feeds.feedblitz.com/~/t/0/0/baeldung/sql/~https://www.baeldung.com/spring-ai-pgvector-semantic-search">HNSQ</a> data retrieval.</strong></p>
<h2 id="bd-distributed-architecture" data-id="distributed-architecture">5. Distributed Architecture</h2>
<div class="bd-anchor" id="distributed-architecture"></div>
<p><em>CrateDB</em> is natively distributed. <strong>It&#8217;s well-suited for large-scale distributed systems and employs a <em>shared-nothing</em> architecture.</strong> Therefore, data is automatically sharded across all available nodes, which makes it highly available and fault-tolerant.</p>
<p><strong>With support for horizontal scaling out of the box, new nodes can be easily added and removed.</strong></p>
<p><strong>Additionally, a distributed query execution engine powers CrateDB that supports running ad-hoc SQL queries on billions of records in milliseconds.</strong> This makes CrateDB ideal for real-time aggregations and operational analytics.</p>
<h2 id="bd-performance-and-scalability" data-id="performance-and-scalability">6. Performance and Scalability</h2>
<div class="bd-anchor" id="performance-and-scalability"></div>
<p>CrateDB provides scalability through partitioning, sharding, and replication.</p>
<p><strong>CrateDB automatically splits tables into shards, which are self-contained chunks that hold a portion of the data.</strong> These <a href="https://feeds.feedblitz.com/~/t/0/0/baeldung/sql/~https://www.baeldung.com/cs/sharding">shards</a> are then distributed across nodes in the cluster, each backed by a dedicated Lucene index.</p>
<p>It should be noted that choosing the right number of shards depends on our data volume, query patterns, and hardware setup.</p>
<p><strong>We can further organise data using partitioning, which splits tables based on defined columns.</strong> Each partition is essentially a collection of shards, making queries faster by narrowing the data scope.</p>
<p>To ensure fault tolerance and improve performance,<strong><em> CrateDB</em> lets us replicate table shards across nodes.</strong> Replication not only provides redundancy but also boosts read performance by enabling more parallel query execution.</p>
<h2 id="bd-conclusion" data-id="conclusion">7. Conclusion</h2>
<div class="bd-anchor" id="conclusion"></div>
<p>In this article, we discussed CrateDB and its powerful features and dynamic data handling capabilities, which make it a great alternative to traditional databases. It combines the benefits of SQL and NoSQL databases. We also discussed the distributed nature of CrateDB, making it suitable for efficiently handling large volumes of data with ease.</p>
<p>Finally, we saw the advanced search capabilities across multiple domains that come out of the box with CrateDB. CrateDB also provides excellent performance and scaling benchmarks.</p><Img align="left" border="0" height="1" width="1" alt="" style="border:0;float:left;margin:0;padding:0;width:1px!important;height:1px!important;" hspace="0" src="https://feeds.feedblitz.com/~/i/924561767/0/baeldung/sql">
<div style="clear:both;padding-top:0.2em;"><a title="Like on Facebook" href="https://feeds.feedblitz.com/_/28/924561767/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/fblike20.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Pin it!" href="https://feeds.feedblitz.com/_/29/924561767/baeldung/sql,https%3a%2f%2fwww.baeldung.com%2fwp-content%2fuploads%2fsites%2f7%2f2024%2f11%2fSQL-Featured-Image-06-1024x536.jpg"><img height="20" src="https://assets.feedblitz.com/i/pinterest20.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Post to X.com" href="https://feeds.feedblitz.com/_/24/924561767/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/x.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Subscribe by email" href="https://feeds.feedblitz.com/_/19/924561767/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/email20.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Subscribe by RSS" href="https://feeds.feedblitz.com/_/20/924561767/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/rss20.png" style="border:0;margin:0;padding:0;"></a>&nbsp;<h3 style="clear:left;padding-top:10px">Related Stories</h3><ul><li><a rel="NOFOLLOW" href="https://www.baeldung.com/sql/mysql-file-import-cmd-line">Import an SQL File Using the Command Line in MySQL</a></li><li><a rel="NOFOLLOW" href="https://www.baeldung.com/sql/mysql-configure-time-zone-settings">How to Configure Time Zone Settings in MySQL?</a></li><li><a rel="NOFOLLOW" href="https://www.baeldung.com/sql/apache-doris-tutorial">Introduction to Apache Doris</a></li></ul>&#160;</div>]]>
</content:encoded>
					
		
		
		<webfeeds:featuredImage>https://www.baeldung.com/wp-content/uploads/sites/7/2024/11/SQL-Featured-Image-06-150x150.jpg</webfeeds:featuredImage></item>
<item>
<feedburner:origLink>https://www.baeldung.com/sql/database-size</feedburner:origLink>
		<title>How to Retrieve the Database Size?</title>
		<link>https://feeds.feedblitz.com/~/924561770/0/baeldung/sql~How-to-Retrieve-the-Database-Size</link>
		
		<dc:creator><![CDATA[Sukanya V]]></dc:creator>
		<pubDate>Tue, 09 Sep 2025 05:35:18 +0000</pubDate>
				<category><![CDATA[SQL Queries]]></category>
		<category><![CDATA[SQL Views]]></category>
		<category><![CDATA[Information Schema]]></category>
		<guid isPermaLink="false">https://www.baeldung.com/sql/database-size</guid>
					<description><![CDATA[<img src="https://www.baeldung.com/wp-content/uploads/sites/7/2024/03/SQL-Featured-Image-01-1024x536.jpg" class="webfeedsFeaturedVisual wp-post-image" alt="" style="max-width:100% !important;height:auto !important;float: left; margin-right: 5px;" loading="lazy" />Learn how to check the size of databases via SQL for different database management systems.<div style="clear:both;padding-top:0.2em;"><a title="Like on Facebook" href="https://feeds.feedblitz.com/_/28/924561770/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/fblike20.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Pin it!" href="https://feeds.feedblitz.com/_/29/924561770/baeldung/sql,https%3a%2f%2fwww.baeldung.com%2fwp-content%2fuploads%2fsites%2f7%2f2024%2f03%2fSQL-Featured-Image-01-1024x536.jpg"><img height="20" src="https://assets.feedblitz.com/i/pinterest20.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Post to X.com" href="https://feeds.feedblitz.com/_/24/924561770/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/x.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Subscribe by email" href="https://feeds.feedblitz.com/_/19/924561770/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/email20.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Subscribe by RSS" href="https://feeds.feedblitz.com/_/20/924561770/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/rss20.png" style="border:0;margin:0;padding:0;"></a>&nbsp;<h3 style="clear:left;padding-top:10px">Related Stories</h3><ul><li><a rel="NOFOLLOW" href="https://www.baeldung.com/sql/select-except-columns">How to Exclude a Column Using SELECT EXCEPT in SQL</a></li><li><a rel="NOFOLLOW" href="https://www.baeldung.com/sql/sargability">What Is Sargability in SQL?</a></li><li><a rel="NOFOLLOW" href="https://www.baeldung.com/sql/subquery-update-rows">Updating Rows With a Subquery Referencing the Same Table in SQL</a></li></ul>&#160;</div>]]>
</description>
										<content:encoded><![CDATA[<img src="https://www.baeldung.com/wp-content/uploads/sites/7/2024/03/SQL-Featured-Image-01-1024x536.jpg" class="webfeedsFeaturedVisual wp-post-image" alt="" style="float: left; margin-right: 5px;" decoding="async" loading="lazy" srcset="https://www.baeldung.com/wp-content/uploads/sites/7/2024/03/SQL-Featured-Image-01-1024x536.jpg 1024w, https://www.baeldung.com/wp-content/uploads/sites/7/2024/03/SQL-Featured-Image-01-300x157.jpg 300w, https://www.baeldung.com/wp-content/uploads/sites/7/2024/03/SQL-Featured-Image-01-768x402.jpg 768w, https://www.baeldung.com/wp-content/uploads/sites/7/2024/03/SQL-Featured-Image-01-100x52.jpg 100w, https://www.baeldung.com/wp-content/uploads/sites/7/2024/03/SQL-Featured-Image-01.jpg 1200w" sizes="auto, (max-width: 580px) 100vw, 580px" /><h2 id="bd-introduction" data-id="introduction">1. Introduction</h2>
<div class="bd-anchor" id="introduction"></div>
<p>Unlike <a href="https://feeds.feedblitz.com/~/t/0/0/baeldung/sql/~https://www.baeldung.com/sql/table-size-get">table size checks</a>, monitoring the size of a database is an essential task for administrators and developers to ensure efficient storage management and optimal performance.</p>
<p>In this tutorial, we&#8217;ll explore how to use the built-in tools and system views of SQL Server and PostgreSQL, which enable us <strong>to quickly get a snapshot of the size of a single database or all databases in an instance</strong>.</p>
<h2 id="bd-how-to-check-database-size-in-postgresql" data-id="how-to-check-database-size-in-postgresql">2. How to Check Database Size in PostgreSQL?</h2>
<div class="bd-anchor" id="how-to-check-database-size-in-postgresql"></div>
<p>PostgreSQL provides built-in functions that make retrieving the database size fairly trivial.</p>
<p>Here, the query retrieves the size of the specific PostgreSQL database named <em>university</em>, showing it as <em>294 MB</em>:</p>
<pre><code class="language-sql"># SELECT pg_database.datname AS "Database", size_pretty(pg_database_size(pg_database.datname)) AS "Size" FROM pg_database WHERE datname = 'university';
   Database    |  Size   
---------------+---------
 university    | 294 MB
(1 row)</code></pre>
<p>Also, <strong>the <em>pg_database_size</em> function returns the size in bytes, whilst <em>pg_size_pretty</em> makes it human-readable (e.g., in MB, GB)</strong>.</p>
<p>Furthermore, we can list the sizes of all databases on the server, ordered from largest to smallest via <a href="https://feeds.feedblitz.com/~/t/0/0/baeldung/sql/~https://www.baeldung.com/sql/order-by-several-columns#basic-ordering">ORDER BY</a>:</p>
<pre><code class="language-sql"># SELECT datname AS "Database", pg_size_pretty(pg_database_size(datname)) AS "Size" FROM pg_database ORDER BY pg_database_size(datname) DESC;
   Database    |  Size   
---------------+---------
 gateway       | 543 MB
 university    | 294 MB
 apiserver     | 288 MB
 ...
 ...
 ...
 data_archival | 8436 kB
(11 rows)</code></pre>
<p>From the output, we can see that <em>gateway</em> is the largest database at <em>543 MB</em>, followed by <em>university</em> and <em>apiserver</em>. On the other hand, the smallest database is <em>data_archival</em> with <em>8436 kB</em> in size.</p>
<h2 id="bd-how-to-check-database-size-in-sql-server" data-id="how-to-check-database-size-in-sql-server">3. How to Check Database Size in SQL Server?</h2>
<div class="bd-anchor" id="how-to-check-database-size-in-sql-server"></div>
<p>Similarly, SQL Server provides built-in functions to check database sizes.</p>
<p>To begin with, <strong>we can use the <em>sp_spaceused</em> procedure, which returns the total size and unallocated space of the current database</strong>:</p>
<pre><code class="language-sql"># EXEC sp_spaceused;
 database_name   |  database_size  | unallocated space
-----------------+-----------------+-------------------
  university     |    294 MB       |    121 MB
</code></pre>
<p>Alternatively, <strong>the <em>sys.master_files</em> can show the <em>university</em> database size and report its total size in MB</strong>:</p>
<pre><code class="language-sql"># SELECT DB_NAME(database_id) AS [Database], CAST(SUM(size) * 8 / 1024 AS VARCHAR(20)) + ' MB' AS [Size] FROM sys.master_files WHERE DB_NAME(database_id) = 'university' GROUP BY database_id;
   Database    |  Size   
---------------+---------
 university    | 294 MB
</code></pre>
<p>Next, to <strong>see the sizes of all databases in the SQL Server instance, we can join <em>sys.databases</em> with <em>sys.master_files</em></strong>:</p>
<pre><code class="language-sql"># SELECT d.name AS [Database], CAST(SUM(mf.size) * 8 / 1024 AS VARCHAR(20)) + ' MB' AS [Size] FROM sys.databases d JOIN sys.master_files mf ON d.database_id = mf.database_id GROUP BY d.name ORDER BY SUM(mf.size) DESC;
   Database    |  Size
---------------+---------
 gateway       | 543 MB
 university    | 294 MB
 apiserver     | 288 MB
 ...
 ...
 ...
 data_archival | 8436 kB
</code></pre>
<p>Typically, built-in functions like <em>sp_spaceused</em> provide the easiest way to get the current database size.</p>
<p>Additionally, for more detailed insights, we can query <em>sys.master_files</em> and check the sizes of a specific database or all databases.</p>
<h2 id="bd-how-to-check-database-size-in-mysql" data-id="how-to-check-database-size-in-mysql">4. How to Check Database Size in MySQL?</h2>
<div class="bd-anchor" id="how-to-check-database-size-in-mysql"></div>
<p>MySQL doesn&#8217;t provide any built-in function like PostgreSQL or SQL Server to check database size, but it offers <strong>a straightforward way through the <em><a href="https://feeds.feedblitz.com/~/t/0/0/baeldung/sql/~https://www.baeldung.com/sql/script-generate-db-indexes">information_schema.tables</a></em> system view</strong>.</p>
<p>With that in mind, <strong>we can calculate the size of a specific database (e.g., <em>university</em>) by summing up the data and index lengths for all tables under that <a href="https://feeds.feedblitz.com/~/t/0/0/baeldung/sql/~https://www.baeldung.com/sql/check-table-existence-particular-schema">schema</a></strong>:</p>
<pre><code class="language-sql">&gt; SELECT table_schema AS "Database", FLOOR(SUM(data_length + index_length) / 1024 / 1024, 2) AS "Size (MB)" FROM information_schema.tables WHERE table_schema = 'university' GROUP BY table_schema;
+------------+------------+
| Database   | Size (MB)  |
+------------+------------+
| university | 294        |
+------------+------------+</code></pre>
<p>Here, the query returns the total size of the university database as <em>294 MB</em>.</p>
<p>Furthermore, to view the sizes of all databases on the server and sort them from largest to smallest, we can leverage a fairly simple query:</p>
<pre><code class="language-sql">&gt; SELECT table_schema AS "Database", FLOOR(SUM(data_length + index_length) / 1024 / 1024, 2) AS "Size (MB)"
FROM information_schema.tables GROUP BY table_schema ORDER BY SUM(data_length + index_length) DESC;
+----------------+------------+
| Database       | Size (MB)  |
+----------------+------------+
| gateway        | 543        |
| university     | 294        |
| applicationdbs | 121        |
| data_archival  | 8          |
+----------------+------------+</code></pre>
<p>Thus, the output shows the total size of each database by summing <em>data_length</em> (table data) and <em>index_length</em> (indexes) from all tables in the schema. As such, it <strong>reflects the actual on-disk storage in megabytes, excluding logs or temporary files</strong>.</p>
<h2 id="bd-conclusion" data-id="conclusion">5. Conclusion</h2>
<div class="bd-anchor" id="conclusion"></div>
<p>In this article, we got into database size checks.</p>
<p>In summary, monitoring database sizes is essential for efficient storage management and optimal performance. <strong>SQL Server and PostgreSQL provide built-in functions to quickly check the size of single or multiple databases, while MySQL offers system views like <em>information_schema</em> that enable similar insights through custom <a href="https://feeds.feedblitz.com/~/t/0/0/baeldung/sql/~https://www.baeldung.com/sql/sql-statements-queries">queries</a></strong>.</p>
<p>These tools can be leveraged to plan storage, optimize performance, and avoid unexpected space issues.</p><Img align="left" border="0" height="1" width="1" alt="" style="border:0;float:left;margin:0;padding:0;width:1px!important;height:1px!important;" hspace="0" src="https://feeds.feedblitz.com/~/i/924561770/0/baeldung/sql">
<div style="clear:both;padding-top:0.2em;"><a title="Like on Facebook" href="https://feeds.feedblitz.com/_/28/924561770/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/fblike20.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Pin it!" href="https://feeds.feedblitz.com/_/29/924561770/baeldung/sql,https%3a%2f%2fwww.baeldung.com%2fwp-content%2fuploads%2fsites%2f7%2f2024%2f03%2fSQL-Featured-Image-01-1024x536.jpg"><img height="20" src="https://assets.feedblitz.com/i/pinterest20.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Post to X.com" href="https://feeds.feedblitz.com/_/24/924561770/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/x.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Subscribe by email" href="https://feeds.feedblitz.com/_/19/924561770/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/email20.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Subscribe by RSS" href="https://feeds.feedblitz.com/_/20/924561770/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/rss20.png" style="border:0;margin:0;padding:0;"></a>&nbsp;<h3 style="clear:left;padding-top:10px">Related Stories</h3><ul><li><a rel="NOFOLLOW" href="https://www.baeldung.com/sql/select-except-columns">How to Exclude a Column Using SELECT EXCEPT in SQL</a></li><li><a rel="NOFOLLOW" href="https://www.baeldung.com/sql/sargability">What Is Sargability in SQL?</a></li><li><a rel="NOFOLLOW" href="https://www.baeldung.com/sql/subquery-update-rows">Updating Rows With a Subquery Referencing the Same Table in SQL</a></li></ul>&#160;</div>]]>
</content:encoded>
					
		
		
		<webfeeds:featuredImage>https://www.baeldung.com/wp-content/uploads/sites/7/2024/03/SQL-Featured-Image-01-150x150.jpg</webfeeds:featuredImage></item>
<item>
<feedburner:origLink>https://www.baeldung.com/sql/azure-view-roles-permissions</feedburner:origLink>
		<title>Viewing Roles and Permissions Granted to Users of Azure SQL Server Instance</title>
		<link>https://feeds.feedblitz.com/~/924492851/0/baeldung/sql~Viewing-Roles-and-Permissions-Granted-to-Users-of-Azure-SQL-Server-Instance</link>
		
		<dc:creator><![CDATA[Sandip Roy]]></dc:creator>
		<pubDate>Sun, 07 Sep 2025 18:17:08 +0000</pubDate>
				<category><![CDATA[Database Access]]></category>
		<guid isPermaLink="false">https://www.baeldung.com/sql/azure-view-roles-permissions</guid>
					<description><![CDATA[<img src="https://www.baeldung.com/wp-content/uploads/sites/7/2024/11/SQL-Featured-Image-08-1024x536.jpg" class="webfeedsFeaturedVisual wp-post-image" alt="" style="max-width:100% !important;height:auto !important;float: left; margin-right: 5px;" loading="lazy" />Learn to view roles and permissions in Azure SQL Server.<div style="clear:both;padding-top:0.2em;"><a title="Like on Facebook" href="https://feeds.feedblitz.com/_/28/924492851/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/fblike20.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Pin it!" href="https://feeds.feedblitz.com/_/29/924492851/baeldung/sql,https%3a%2f%2fwww.baeldung.com%2fwp-content%2fuploads%2fsites%2f7%2f2024%2f11%2fSQL-Featured-Image-08-1024x536.jpg"><img height="20" src="https://assets.feedblitz.com/i/pinterest20.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Post to X.com" href="https://feeds.feedblitz.com/_/24/924492851/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/x.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Subscribe by email" href="https://feeds.feedblitz.com/_/19/924492851/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/email20.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Subscribe by RSS" href="https://feeds.feedblitz.com/_/20/924492851/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/rss20.png" style="border:0;margin:0;padding:0;"></a>&nbsp;<h3 style="clear:left;padding-top:10px">Related Stories</h3><ul><li><a rel="NOFOLLOW" href="https://www.baeldung.com/sql/blocking-queries-monitor-fix">How to Check Blocking Queries</a></li><li><a rel="NOFOLLOW" href="https://www.baeldung.com/sql/mysql-host-not-allowed-error-troubleshoot">Fixing MySQL &#x2018;Host Not Allowed&#x2019; Error: A Simple Guide</a></li><li><a rel="NOFOLLOW" href="https://www.baeldung.com/sql/postgresql-user-password">Change a PostgreSQL User Password</a></li></ul>&#160;</div>]]>
</description>
										<content:encoded><![CDATA[<img src="https://www.baeldung.com/wp-content/uploads/sites/7/2024/11/SQL-Featured-Image-08-1024x536.jpg" class="webfeedsFeaturedVisual wp-post-image" alt="" style="float: left; margin-right: 5px;" decoding="async" loading="lazy" srcset="https://www.baeldung.com/wp-content/uploads/sites/7/2024/11/SQL-Featured-Image-08-1024x536.jpg 1024w, https://www.baeldung.com/wp-content/uploads/sites/7/2024/11/SQL-Featured-Image-08-300x157.jpg 300w, https://www.baeldung.com/wp-content/uploads/sites/7/2024/11/SQL-Featured-Image-08-768x402.jpg 768w, https://www.baeldung.com/wp-content/uploads/sites/7/2024/11/SQL-Featured-Image-08-100x52.jpg 100w, https://www.baeldung.com/wp-content/uploads/sites/7/2024/11/SQL-Featured-Image-08-600x314.jpg 600w, https://www.baeldung.com/wp-content/uploads/sites/7/2024/11/SQL-Featured-Image-08.jpg 1200w" sizes="auto, (max-width: 580px) 100vw, 580px" /><h2 id="bd-introduction" data-id="introduction"><strong>1. Introduction</strong></h2>
<div class="bd-anchor" id="introduction"></div>
<p><a href="https://feeds.feedblitz.com/~/t/0/0/baeldung/sql/~https://www.baeldung.com/sql/user-all-permissions">Roles and permissions</a> are essential to securing Microsoft Azure <a href="https://feeds.feedblitz.com/~/t/0/0/baeldung/sql/~https://www.baeldung.com/sql/update-via-select">SQL Server</a> databases. Providing users with the appropriate level of access is crucial for compliance and security as businesses grow.</p>
<p><strong>To query and examine the server-level, database-level, and custom roles that Azure SQL Database offers, we can use the Azure Portal, the <a href="https://feeds.feedblitz.com/~/t/0/0/baeldung/sql/~https://www.baeldung.com/spring-boot-azuread-authenticate-users">Azure Active Directory</a> integration, or custom <a href="https://feeds.feedblitz.com/~/t/0/0/baeldung/sql/~https://www.baeldung.com/sql/determine-database-version">T-SQL</a> statements.</strong></p>
<p>In this tutorial, we&#8217;ll present the different types of roles, how to view user permissions, and the best practices for auditing access in Azure SQL Server.</p>
<h2 id="bd-understanding-the-roles-in-azure-sql-server" data-id="understanding-the-roles-in-azure-sql-server">2. Understanding the Roles in Azure SQL Server</h2>
<div class="bd-anchor" id="understanding-the-roles-in-azure-sql-server"></div>
<p>Roles are predefined or user-defined security groupings. <strong>We can assign users to roles rather than giving them permissions on a case-by-case basis.</strong></p>
<p>We differentiate between server-level and database-level roles:</p>
<table class="table-styled" style="width: 91.1134%;height: 282px">
<thead>
<tr style="height: 24px">
<th style="width: 19.1155%;height: 24px;text-align: center">Roles</th>
<th style="width: 30.8106%;height: 24px">Command</th>
<th style="width: 110.963%;height: 24px">Description</th>
</tr>
</thead>
<tbody>
<tr style="height: 51px">
<td style="width: 19.1155%;height: 114px;text-align: center" rowspan="4">Server</td>
<td style="width: 30.8106%;text-align: left;height: 13px">sysadmin</td>
<td style="width: 110.963%;height: 13px;text-align: left">full control over the SQL Server instance.</td>
</tr>
<tr style="height: 24px">
<td style="width: 30.8106%;text-align: left;height: 18px">serveradmin</td>
<td style="width: 110.963%;height: 18px;text-align: left">manage server-wide configurations</td>
</tr>
<tr style="height: 46px">
<td style="width: 30.8106%;text-align: left;height: 15px">securityadmin</td>
<td style="width: 110.963%;height: 15px;text-align: left">manage logins and permissions</td>
</tr>
<tr style="height: 50px">
<td style="width: 30.8106%;text-align: left;height: 68px">setupadmin, processadmin, diskadmin, dbcreator, bulkadmin</td>
<td style="width: 110.963%;height: 68px;text-align: left">specialized roles</td>
</tr>
<tr style="height: 24px">
<td style="width: 19.1155%;height: 144px;text-align: center;background-color: white" rowspan="6">Database</td>
<td style="width: 30.8106%;text-align: left;height: 24px">db_owner</td>
<td style="width: 110.963%;text-align: left;height: 24px">full database control</td>
</tr>
<tr style="height: 24px">
<td style="width: 30.8106%;text-align: left;height: 24px">db_datareader / db_datawriter</td>
<td style="width: 110.963%;text-align: left;height: 24px">read or write data in all user tables</td>
</tr>
<tr style="height: 24px">
<td style="width: 30.8106%;text-align: left;height: 24px">db_ddladmin</td>
<td style="width: 110.963%;text-align: left;height: 24px">execute DDL commands (e.g., create/alter tables)</td>
</tr>
<tr style="height: 24px">
<td style="width: 30.8106%;text-align: left;height: 24px">db_securityadmin</td>
<td style="width: 110.963%;text-align: left;height: 24px">manage database-level permissions</td>
</tr>
<tr style="height: 24px">
<td style="width: 30.8106%;text-align: left;height: 24px">db_backupoperator</td>
<td style="width: 110.963%;text-align: left;height: 24px">manage database backups</td>
</tr>
<tr style="height: 24px">
<td style="width: 30.8106%;text-align: left;height: 24px">public</td>
<td style="width: 110.963%;text-align: left;height: 24px">default role, everyone belongs to this role</td>
</tr>
</tbody>
</table>
<p>Additionally, organizations can establish custom roles to comply with the least privilege principle. With user-defined custom roles, administrators can customize permissions to meet particular job functions or operational requirements.</p>
<p>This ensures that users only have access to the resources they need for their tasks, reducing the possibility of unintentional or malicious data exposure.</p>
<h2 id="bd-methods-for-viewing-roles-using-a-query" data-id="methods-for-viewing-roles-using-a-query">3. Methods for Viewing Roles Using a Query</h2>
<div class="bd-anchor" id="methods-for-viewing-roles-using-a-query"></div>
<p>Azure SQL supports querying system views to retrieve roles and permissions.</p>
<h3 id="bd-1-view-database-roles-assigned-to-users" data-id="1-view-database-roles-assigned-to-users">3.1. View Database Roles Assigned to Users</h3>
<div class="bd-anchor" id="1-view-database-roles-assigned-to-users"></div>
<p>Here&#8217;s an SQL query that retrieves a list of database roles and their members from the current SQL Server database:</p>
<pre><code class="language-">SELECT dp.name AS DatabaseRole,
mp.name AS MemberName,
mp.type_desc AS MemberType
FROM sys.database_role_members drm
JOIN sys.database_principals dp ON drm.role_principal_id = dp.principal_id
JOIN sys.database_principals mp ON drm.member_principal_id = mp.principal_id
ORDER BY dp.name;</code></pre>
<p>The <em>sys.database_role_members</em> view maps database roles to their members, showing which users belong to which roles. The <em>sys.database_role_principals</em> view contains information about all database-level security principals, including users, roles, and application roles.</p>
<p>Here&#8217;s what the output typically looks like:</p>
<table class="table-styled" style="width: 89.2234%;height: 88px">
<thead>
<tr style="height: 24px">
<th style="width: 31.0843%;height: 24px">DatabaseRole</th>
<th style="width: 32.7711%;height: 24px">MemberName</th>
<th style="width: 95.4217%;height: 24px">MemberType</th>
</tr>
</thead>
<tbody>
<tr style="height: 51px">
<td style="width: 31.0843%;height: 10px">db_datareader</td>
<td style="width: 32.7711%;text-align: left;height: 10px">app_user</td>
<td style="width: 95.4217%;height: 10px;text-align: left">SQL_USER</td>
</tr>
<tr style="height: 24px">
<td style="width: 31.0843%;height: 10px">db_datawriter</td>
<td style="width: 32.7711%;text-align: left;height: 10px">app_user</td>
<td style="width: 95.4217%;height: 10px;text-align: left">SQL_USER</td>
</tr>
<tr style="height: 46px">
<td style="width: 31.0843%;height: 10px">db_owner</td>
<td style="width: 32.7711%;text-align: left;height: 10px">admin_user</td>
<td style="width: 95.4217%;height: 10px;text-align: left">SQL_USER</td>
</tr>
<tr style="height: 50px">
<td style="width: 31.0843%;height: 10px">db_owner</td>
<td style="width: 32.7711%;text-align: left;height: 10px">dbo</td>
<td style="width: 95.4217%;height: 10px;text-align: left">DATABASE_ROLE</td>
</tr>
<tr style="height: 24px">
<td style="width: 31.0843%;height: 24px">db_ddladmin</td>
<td style="width: 32.7711%;text-align: left;height: 24px">dev_user</td>
<td style="width: 95.4217%;text-align: left;height: 24px">SQL_USER</td>
</tr>
</tbody>
</table>
<p>The actual output depends on our database&#8217;s current role assignments. We’ll see all users and roles that are members of other roles, sorted by the role name.</p>
<p>This query is a great way to get a clear snapshot of role memberships. It&#8217;s particularly useful when auditing permissions and managing access.</p>
<h3 id="bd-2-view-server-level-roles" data-id="2-view-server-level-roles">3.2. View Server-Level Roles</h3>
<div class="bd-anchor" id="2-view-server-level-roles"></div>
<p>Getting server-level role memberships in SQL Server is useful for auditing administrative privileges and understanding access control at the instance level.</p>
<p>Here&#8217;s an SQL query that retrieves a list of server roles and their members:</p>
<pre><code class="language-">SELECT spr.name AS ServerRole,
spm.name AS MemberName
FROM sys.server_role_members srm
JOIN sys.server_principals spr ON srm.role_principal_id = spr.principal_id
JOIN sys.server_principals spm ON srm.member_principal_id = spm.principal_id
ORDER BY spr.name;</code></pre>
<p>The <em>sys.server_role_members</em> view shows the relationships between server-level roles and their members. The <em>sys.server_principals</em> view lists all server-level security principals, such as logins and server roles, providing metadata about each.</p>
<p>Here&#8217;s what the output typically looks like:</p>
<table class="table-styled" style="width: 75.7257%;height: 74px">
<thead>
<tr style="height: 24px">
<th style="width: 31.0843%;height: 10px">ServerRole</th>
<th style="width: 17.6425%;height: 10px">MemberName</th>
</tr>
</thead>
<tbody>
<tr style="height: 51px">
<td style="width: 31.0843%;height: 10px">sysadmin</td>
<td style="width: 17.6425%;height: 10px;text-align: left">sa</td>
</tr>
<tr style="height: 24px">
<td style="width: 31.0843%;height: 10px">sysadmin</td>
<td style="width: 17.6425%;height: 10px;text-align: left">SandipAdmin</td>
</tr>
<tr style="height: 46px">
<td style="width: 31.0843%;height: 10px">securityadmin</td>
<td style="width: 17.6425%;height: 10px;text-align: left">AuditUser</td>
</tr>
<tr style="height: 50px">
<td style="width: 31.0843%;height: 10px">serveradminDBA_TeamLead</td>
<td style="width: 17.6425%;height: 10px;text-align: left">DBA_TeamLead</td>
</tr>
<tr style="height: 24px">
<td style="width: 31.0843%;height: 24px">setupadmin</td>
<td style="width: 17.6425%;height: 24px;text-align: left">InstallerLogin</td>
</tr>
</tbody>
</table>
<p>The actual output will reflect the logins configured on the SQL Server instance and their assigned server roles. <strong>These roles govern various capabilities, such as managing logins, configuring server settings, or executing high-level tasks.</strong></p>
<h3 id="bd-3-view-explicit-permissions-granted-to-a-user" data-id="3-view-explicit-permissions-granted-to-a-user">3.3. View Explicit Permissions Granted to a User</h3>
<div class="bd-anchor" id="3-view-explicit-permissions-granted-to-a-user"></div>
<p>In contrast to the query showing role memberships, <strong>we&#8217;ll now focus on explicit <a href="https://feeds.feedblitz.com/~/t/0/0/baeldung/sql/~https://www.baeldung.com/sql/user-all-permissions">permissions</a> granted directly to users or roles.</strong></p>
<p><strong>When auditing who has access to what, and under whose authority, a detailed view of explicit database-level permissions comes in handy:</strong></p>
<pre><code class="language-">SELECT dp1.name AS Grantee,
dp2.name AS Grantor,
perm.permission_name,
perm.state_desc,
obj.name AS ObjectName
FROM sys.database_permissions perm
JOIN sys.database_principals dp1 ON perm.grantee_principal_id = dp1.principal_id
JOIN sys.database_principals dp2 ON perm.grantor_principal_id = dp2.principal_id
LEFT JOIN sys.objects obj ON perm.major_id = obj.object_id
ORDER BY dp1.name, perm.permission_name;</code></pre>
<p>This query serves as an excellent tool to demonstrate granular access control within relational databases.</p>
<p>The following table provide details about the output columns in the query.</p>
<p>&nbsp;</p>
<table class="table-styled" style="width: 99.1098%;height: 74px">
<thead>
<tr style="height: 24px">
<th style="width: 2.72753%;height: 24px">Column</th>
<th style="width: 55.2118%;height: 24px">Description</th>
</tr>
</thead>
<tbody>
<tr style="height: 51px">
<td style="width: 2.72753%;height: 10px">Grantee</td>
<td style="width: 55.2118%;height: 10px;text-align: left">The principal (user/role) receiving the permission</td>
</tr>
<tr style="height: 24px">
<td style="width: 2.72753%;height: 10px">Grantor</td>
<td style="width: 55.2118%;height: 10px;text-align: left">The principal who granted the permission</td>
</tr>
<tr style="height: 46px">
<td style="width: 2.72753%;height: 10px">permission_name</td>
<td style="width: 55.2118%;height: 10px;text-align: left">The specific permission granted (SELECT, EXECUTE, INSERT)</td>
</tr>
<tr style="height: 50px">
<td style="width: 2.72753%;height: 10px">state_desc</td>
<td style="width: 55.2118%;height: 10px;text-align: left">The state of the permission (GRANT, DENY, REVOKE)</td>
</tr>
<tr style="height: 24px">
<td style="width: 2.72753%;height: 10px">ObjectName</td>
<td style="width: 55.2118%;height: 10px;text-align: left">The name of the object (table, view, procedure, etc.) the permission applies to</td>
</tr>
</tbody>
</table>
<p>Here&#8217;s how the output typically looks like:</p>
<table class="table-styled" style="width: 90.8436%;height: 65px">
<thead>
<tr style="height: 24px">
<th style="width: 12.7242%;height: 24px">Grantee</th>
<th style="width: 15.3413%;height: 24px">Grantor</th>
<th style="width: 19.5666%;height: 24px">permission_name</th>
<th style="width: 10.5295%;height: 24px">state_desc</th>
<th style="width: 10.5295%;height: 24px">ObjectName</th>
</tr>
</thead>
<tbody>
<tr style="height: 51px">
<td style="width: 12.7242%;height: 10px">app_user</td>
<td style="width: 15.3413%;text-align: left;height: 10px">dbo</td>
<td style="width: 19.5666%;text-align: left;height: 10px">SELECT</td>
<td style="width: 10.5295%;height: 10px;text-align: left">GRANT</td>
<td style="width: 10.5295%;text-align: left;height: 10px">Customers</td>
</tr>
<tr style="height: 24px">
<td style="width: 12.7242%;height: 11px">dev_user</td>
<td style="width: 15.3413%;text-align: left;height: 11px">dbo</td>
<td style="width: 19.5666%;text-align: left;height: 11px">EXECUTE</td>
<td style="width: 10.5295%;height: 11px;text-align: left">GRANT</td>
<td style="width: 10.5295%;text-align: left;height: 11px">usp_GetOrders</td>
</tr>
<tr style="height: 46px">
<td style="width: 12.7242%;height: 10px">audit_user</td>
<td style="width: 15.3413%;text-align: left;height: 10px">dbo</td>
<td style="width: 19.5666%;text-align: left;height: 10px">VIEW DEFINITION</td>
<td style="width: 10.5295%;height: 10px;text-align: left">GRANT</td>
<td style="width: 10.5295%;text-align: left;height: 10px">Orders</td>
</tr>
<tr style="height: 50px">
<td style="width: 12.7242%;height: 10px">guest</td>
<td style="width: 15.3413%;text-align: left;height: 10px">dbo</td>
<td style="width: 19.5666%;text-align: left;height: 10px">SELECT</td>
<td style="width: 10.5295%;height: 10px;text-align: left">DENY</td>
<td style="width: 10.5295%;text-align: left;height: 10px">SensitiveData</td>
</tr>
</tbody>
</table>
<p>Furthermore, this highlight security best practices in enterprise data environments, and clarify the distinctions between role based vs explicit permission assignments.</p>
<h2 id="bd-viewing-roles-using-the-azure-portal" data-id="viewing-roles-using-the-azure-portal">4. Viewing Roles Using the Azure Portal</h2>
<div class="bd-anchor" id="viewing-roles-using-the-azure-portal"></div>
<p>The <a href="https://feeds.feedblitz.com/~/t/0/0/baeldung/sql/~https://learn.microsoft.com/en-us/azure/azure-portal/azure-portal-overview">Azure Portal</a> provides a graphical interface for viewing and managing user roles:</p>
<p><img decoding="async" class="alignnone size-full wp-image-6800" src="https://www.baeldung.com/wp-content/uploads/sites/7/2025/09/rg-role-assignments.png" alt="View Role details." /> The steps to get there are:</p>
<ul>
<li>We&#8217;ll navigate to the Azure Portal and open the SQL databases section</li>
<li>Select the target database, then configure the server firewall and set the Active Directory admin for identity mapping</li>
<li>Within the database view, we&#8217;ll access the <a href="https://feeds.feedblitz.com/~/t/0/0/baeldung/sql/~https://learn.microsoft.com/en-us/azure/role-based-access-control/role-assignments-portal">Access control (IAM)</a> panel to review user roles and permissions.</li>
</ul>
<p>If the SQL Server is integrated with Azure AD, permissions can also be reviewed through the Azure Active Directory portal. Further, we&#8217;ll navigate to enterprise applications, then select users and groups to audit group-based assignments across multiple users.</p>
<p>This is especially useful when auditing group-based assignments across multiple users.</p>
<h2 id="bd-best-practices-for-managing-and-reviewing-permissions" data-id="best-practices-for-managing-and-reviewing-permissions">5. Best Practices for Managing and Reviewing Permissions</h2>
<div class="bd-anchor" id="best-practices-for-managing-and-reviewing-permissions"></div>
<p>To ensure secure and scalable access management, <strong>it&#8217;s essential to follow the principle of least privilege. This is done by assigning only the permissions that are strictly necessary.</strong></p>
<p>For routine audits, we need to use Azure Automation or SQL queries. As a result of these audits, we can detect excessive or out-of-date permissions, ensure adherence to internal policies, and identify potential security threats before they become a problem.</p>
<p><strong>We should also implement role-based access control through Azure AD groups for better scalability, and enable logging via Azure Monitor and SQL Auditing to effectively track access changes.</strong></p>
<h2 id="bd-conclusion" data-id="conclusion">6. Conclusion</h2>
<div class="bd-anchor" id="conclusion"></div>
<p><span style="margin: 0px;padding: 0px">In this article, we discussed about how Azure SQL Server roles and permissions ensures secure and legal database access. <strong>T-SQL queries, the Azure Portal, and Azure AD help administrators keep track of who has access and what they can do with it. </strong></span></p>
<p>The ability to manage roles and permissions in Azure SQL Server is essential for preserving data security, operational integrity, and regulatory compliance.</p>
<p>When onboarding new users, distributing access among teams, or getting ready for an audit, knowing who can do what and why is crucial.</p><Img align="left" border="0" height="1" width="1" alt="" style="border:0;float:left;margin:0;padding:0;width:1px!important;height:1px!important;" hspace="0" src="https://feeds.feedblitz.com/~/i/924492851/0/baeldung/sql">
<div style="clear:both;padding-top:0.2em;"><a title="Like on Facebook" href="https://feeds.feedblitz.com/_/28/924492851/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/fblike20.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Pin it!" href="https://feeds.feedblitz.com/_/29/924492851/baeldung/sql,https%3a%2f%2fwww.baeldung.com%2fwp-content%2fuploads%2fsites%2f7%2f2024%2f11%2fSQL-Featured-Image-08-1024x536.jpg"><img height="20" src="https://assets.feedblitz.com/i/pinterest20.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Post to X.com" href="https://feeds.feedblitz.com/_/24/924492851/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/x.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Subscribe by email" href="https://feeds.feedblitz.com/_/19/924492851/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/email20.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Subscribe by RSS" href="https://feeds.feedblitz.com/_/20/924492851/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/rss20.png" style="border:0;margin:0;padding:0;"></a>&nbsp;<h3 style="clear:left;padding-top:10px">Related Stories</h3><ul><li><a rel="NOFOLLOW" href="https://www.baeldung.com/sql/blocking-queries-monitor-fix">How to Check Blocking Queries</a></li><li><a rel="NOFOLLOW" href="https://www.baeldung.com/sql/mysql-host-not-allowed-error-troubleshoot">Fixing MySQL &#x2018;Host Not Allowed&#x2019; Error: A Simple Guide</a></li><li><a rel="NOFOLLOW" href="https://www.baeldung.com/sql/postgresql-user-password">Change a PostgreSQL User Password</a></li></ul>&#160;</div>]]>
</content:encoded>
					
		
		
		<webfeeds:featuredImage>https://www.baeldung.com/wp-content/uploads/sites/7/2024/11/SQL-Featured-Image-08-150x150.jpg</webfeeds:featuredImage></item>
<item>
<feedburner:origLink>https://www.baeldung.com/sql/select-except-columns</feedburner:origLink>
		<title>How to Exclude a Column Using SELECT EXCEPT in SQL</title>
		<link>https://feeds.feedblitz.com/~/924429209/0/baeldung/sql~How-to-Exclude-a-Column-Using-SELECT-EXCEPT-in-SQL</link>
		
		<dc:creator><![CDATA[Abdul Mateen]]></dc:creator>
		<pubDate>Sat, 06 Sep 2025 06:34:40 +0000</pubDate>
				<category><![CDATA[SQL Queries]]></category>
		<category><![CDATA[Information Schema]]></category>
		<category><![CDATA[SELECT]]></category>
		<category><![CDATA[System Catalog]]></category>
		<guid isPermaLink="false">https://www.baeldung.com/sql/select-except-columns</guid>
					<description><![CDATA[<img src="https://www.baeldung.com/wp-content/uploads/sites/7/2024/11/SQL-Featured-Image-07-1024x536.jpg" class="webfeedsFeaturedVisual wp-post-image" alt="" style="max-width:100% !important;height:auto !important;float: left; margin-right: 5px;" loading="lazy" />Learn how to exclude one or more columns when displaying whole tables.<div style="clear:both;padding-top:0.2em;"><a title="Like on Facebook" href="https://feeds.feedblitz.com/_/28/924429209/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/fblike20.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Pin it!" href="https://feeds.feedblitz.com/_/29/924429209/baeldung/sql,https%3a%2f%2fwww.baeldung.com%2fwp-content%2fuploads%2fsites%2f7%2f2024%2f11%2fSQL-Featured-Image-07-1024x536.jpg"><img height="20" src="https://assets.feedblitz.com/i/pinterest20.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Post to X.com" href="https://feeds.feedblitz.com/_/24/924429209/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/x.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Subscribe by email" href="https://feeds.feedblitz.com/_/19/924429209/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/email20.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Subscribe by RSS" href="https://feeds.feedblitz.com/_/20/924429209/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/rss20.png" style="border:0;margin:0;padding:0;"></a>&nbsp;<h3 style="clear:left;padding-top:10px">Related Stories</h3><ul><li><a rel="NOFOLLOW" href="https://www.baeldung.com/sql/table-row-count-efficient">Most Efficient Way to Get Table Row Count in SQL</a></li><li><a rel="NOFOLLOW" href="https://www.baeldung.com/sql/database-size">How to Retrieve the Database Size?</a></li><li><a rel="NOFOLLOW" href="https://www.baeldung.com/sql/sargability">What Is Sargability in SQL?</a></li></ul>&#160;</div>]]>
</description>
										<content:encoded><![CDATA[<img src="https://www.baeldung.com/wp-content/uploads/sites/7/2024/11/SQL-Featured-Image-07-1024x536.jpg" class="webfeedsFeaturedVisual wp-post-image" alt="" style="float: left; margin-right: 5px;" decoding="async" loading="lazy" srcset="https://www.baeldung.com/wp-content/uploads/sites/7/2024/11/SQL-Featured-Image-07-1024x536.jpg 1024w, https://www.baeldung.com/wp-content/uploads/sites/7/2024/11/SQL-Featured-Image-07-300x157.jpg 300w, https://www.baeldung.com/wp-content/uploads/sites/7/2024/11/SQL-Featured-Image-07-768x402.jpg 768w, https://www.baeldung.com/wp-content/uploads/sites/7/2024/11/SQL-Featured-Image-07-100x52.jpg 100w, https://www.baeldung.com/wp-content/uploads/sites/7/2024/11/SQL-Featured-Image-07-600x314.jpg 600w, https://www.baeldung.com/wp-content/uploads/sites/7/2024/11/SQL-Featured-Image-07.jpg 1200w" sizes="auto, (max-width: 580px) 100vw, 580px" /><h2 id="bd-overview" data-id="overview">1. Overview</h2>
<div class="bd-anchor" id="overview"></div>
<p>In SQL, we commonly use the <a href="https://feeds.feedblitz.com/~/t/0/0/baeldung/sql/~https://www.baeldung.com/sql/select-column-contains-specific-string">SELECT * statement</a> to retrieve all columns from the table. However, in certain scenarios, we sometimes want to display all columns except one or even a few. Unfortunately, <strong>standard SQL doesn&#8217;t support the direct  SELECT * EXCEPT syntax in most database management systems</strong>. Instead, the implementations vary depending on the database we&#8217;re using.</p>
<p>In this tutorial, we&#8217;ll explore various techniques for excluding specific columns in <a href="https://feeds.feedblitz.com/~/t/0/0/baeldung/sql/~https://www.baeldung.com/sql/sql-server-current-timestamp">SQL Server</a>, <a href="https://feeds.feedblitz.com/~/t/0/0/baeldung/sql/~https://www.baeldung.com/linux/postgresql-install-configure">PostgreSQL</a>, and <a href="https://feeds.feedblitz.com/~/t/0/0/baeldung/sql/~https://www.baeldung.com/sql/mysql-storage-engine-types">MySQL</a>.</p>
<p>To demonstrate, we&#8217;ll use the Baeldung <a href="https://feeds.feedblitz.com/~/t/0/0/baeldung/sql/~https://www.baeldung.com/sql/simple-schema"><em>University</em></a> database schema as the working example.</p>
<h2 id="bd-listing-specific-columns-in-sql" data-id="listing-specific-columns-in-sql">2. Listing Specific Columns in SQL</h2>
<div class="bd-anchor" id="listing-specific-columns-in-sql"></div>
<p>Generally, <strong>we can always explicitly list the required columns instead of using a SELECT * query</strong>. This approach works in every database management system and is ideal for small tables that rarely change their schema.</p>
<p>To start with, <strong>we can use the following syntax to display only the selected columns</strong>:</p>
<pre><code class="language-sql">SELECT column_1, column_2, column 3, column_4...
FROM table_name;
</code></pre>
<p>Above, we specify the required columns and <em>table_name</em>.</p>
<p>While this method is straightforward, it requires that we know and enumerate all required columns. Especially with big tables, this can be very tedious.</p>
<h2 id="bd-sql-server-syscolumns" data-id="sql-server-syscolumns">3. SQL Server <em>sys.columns</em></h2>
<div class="bd-anchor" id="sql-server-syscolumns"></div>
<p>In SQL Server, <strong>we can use the <a href="https://feeds.feedblitz.com/~/t/0/0/baeldung/sql/~https://www.baeldung.com/sql/find-column-data-type"><em>sys.columns</em></a> view system to dynamically build the query that excludes specific columns</strong>. In particular, this view contains metadata about each column, including its name, data type, and position.</p>
<p>To illustrate,<strong> let&#8217;s exclude the <em>gpa</em> column in the <em>Student</em> table</strong>. For this purpose, we can execute a specific query:</p>
<pre><code class="language-sql">DECLARE @sql NVARCHAR(MAX);
SELECT @sql =
    'SELECT ' + STRING_AGG(QUOTENAME(name), ', ')
    + ' FROM dbo.student'
FROM sys.columns
WHERE object_id = OBJECT_ID('dbo.student')
  AND name &lt;&gt; 'gpa';
EXEC sp_executesql @sql;</code></pre>
<p>The important part here, and the one we can build upon, is <em>AND name &lt;&gt; &#8216;gpa&#8217;</em>. <strong>Adding <em>AND</em></strong><strong> statements with respective names enables the exclusion of multiple columns</strong>.</p>
<p>Consequently, we see the respective output:</p>
<img loading="lazy" decoding="async" class="aligncenter wp-image-6760 size-full" src="https://www.baeldung.com/wp-content/uploads/sites/7/2025/09/SQL_Server_Column_Exclude.png" alt="SQL Server column exclusion result." width="1087" height="258" />
<p>In this output,<strong> all columns are listed except the <em>gpa</em></strong>.</p>
<h2 id="bd-postgresql-stringagg" data-id="postgresql-stringagg">4. PostgreSQL <em>string_agg</em></h2>
<div class="bd-anchor" id="postgresql-stringagg"></div>
<p>In PostgreSQL, <strong>we can exclude a column using the <a href="https://feeds.feedblitz.com/~/t/0/0/baeldung/sql/~https://www.baeldung.com/sql/find-table-column-names">INFORMATION_SCHEMA</a> view and concatenating the column list with </strong><em><strong>string_agg</strong></em>. This approach uses the system catalog view to build flexible queries without manually listing every column.</p>
<p>For instance, <strong>let&#8217;s exclude the <em>code</em> column from the <em>department</em> table</strong>:</p>
<pre><code class="language-sql">university=# DO $$
university$# DECLARE
university$#     sql_query text;
university$# BEGIN
university$#     SELECT 'SELECT ' ||
university$#            string_agg(quote_ident(column_name), ', ' ORDER BY ordinal_position) ||
university$#            ' FROM Department'
university$#     INTO sql_query
university$#     FROM information_schema.columns
university$#     WHERE table_schema = 'public'
university$#       AND table_name   = 'department'
university$#       AND column_name &lt;&gt; 'code';
university$#
university$#     RAISE NOTICE 'Generated SQL: %', sql_query;
university$#     EXECUTE sql_query;
university$# END $$;
NOTICE:  Generated SQL: SELECT id, name FROM department
DO</code></pre>
<p>In return, <strong>we see the generated query <em>SELECT id, name FROM department</em></strong>.</p>
<p>Now, <strong>let&#8217;s run the above-generated query to see the results</strong>:</p>
<pre><code class="language-sql">university=# SELECT id, name FROM department;
 id |              name
----+--------------------------------
  1 | Computer Science
  2 | Electronics and Communications
  3 | Mechanical Engineering
  4 | Civil Engineering
  5 | Mathematics
(5 rows)</code></pre>
<p>Thus, <strong>the output only </strong><span style="margin: 0px;padding: 0px"><strong>displays </strong><em><strong>the id</strong></em><strong> and <em>name</em> columns</strong></span>.</p>
<h2 id="bd-mysql-groupconcat" data-id="mysql-groupconcat">5. MySQL GROUP_CONCAT</h2>
<div class="bd-anchor" id="mysql-groupconcat"></div>
<p>In MySQL, <strong>we can achieve a functionality similar to that in PostgreSQL using the GROUP_CONCAT function, along with the INFORMATION_SCHEMA view</strong>. This approach enables the dynamic elimination of specific columns in the database.</p>
<p>For example, <strong>to eliminate the <em>textbook</em> column from the <em>course</em> table, we can use the <em>COLUMN_NAME</em> field</strong>:</p>
<pre><code class="language-sql">SET @sql = NULL;
SELECT GROUP_CONCAT(CONCAT('`', COLUMN_NAME, '`') ORDER BY ORDINAL_POSITION SEPARATOR ', ')
INTO @sql
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'university'
  AND TABLE_NAME = 'course'
  AND COLUMN_NAME &lt;&gt; 'textbook';
SET @sql = CONCAT('SELECT ', @sql, ' FROM course');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
</code></pre>
<p>Below, <strong>we can see all columns from the <em>course</em> table except <em>textbook</em></strong>:</p>
<img decoding="async" class="aligncenter size-full wp-image-6830" src="https://www.baeldung.com/wp-content/uploads/sites/7/2025/09/MySQL_Column_Exclude.png" alt="MySQL column exclusion result." />
<p>While the approach uses similar concepts, the syntax isn&#8217;t interchangeable with that of PostgreSQL.</p>
<h2 id="bd-conclusion" data-id="conclusion">6. Conclusion</h2>
<div class="bd-anchor" id="conclusion"></div>
<p>In this article, we learned various techniques for excluding a particular column in SQL Server, PostgreSQL, and MySQL.</p>
<p>First, we discussed explicitly listing the required columns as a universal and reliable approach. Then, we saw how to dynamically generate column lists using <em>sys.columns</em> in SQL Server, INFORMATION_SCHEMA with <em>string_agg</em> in PostgreSQL, and GROUP_CONCAT in MySQL to exclude unwanted columns.</p><Img align="left" border="0" height="1" width="1" alt="" style="border:0;float:left;margin:0;padding:0;width:1px!important;height:1px!important;" hspace="0" src="https://feeds.feedblitz.com/~/i/924429209/0/baeldung/sql">
<div style="clear:both;padding-top:0.2em;"><a title="Like on Facebook" href="https://feeds.feedblitz.com/_/28/924429209/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/fblike20.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Pin it!" href="https://feeds.feedblitz.com/_/29/924429209/baeldung/sql,https%3a%2f%2fwww.baeldung.com%2fwp-content%2fuploads%2fsites%2f7%2f2024%2f11%2fSQL-Featured-Image-07-1024x536.jpg"><img height="20" src="https://assets.feedblitz.com/i/pinterest20.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Post to X.com" href="https://feeds.feedblitz.com/_/24/924429209/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/x.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Subscribe by email" href="https://feeds.feedblitz.com/_/19/924429209/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/email20.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Subscribe by RSS" href="https://feeds.feedblitz.com/_/20/924429209/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/rss20.png" style="border:0;margin:0;padding:0;"></a>&nbsp;<h3 style="clear:left;padding-top:10px">Related Stories</h3><ul><li><a rel="NOFOLLOW" href="https://www.baeldung.com/sql/table-row-count-efficient">Most Efficient Way to Get Table Row Count in SQL</a></li><li><a rel="NOFOLLOW" href="https://www.baeldung.com/sql/database-size">How to Retrieve the Database Size?</a></li><li><a rel="NOFOLLOW" href="https://www.baeldung.com/sql/sargability">What Is Sargability in SQL?</a></li></ul>&#160;</div>]]>
</content:encoded>
					
		
		
		<webfeeds:featuredImage>https://www.baeldung.com/wp-content/uploads/sites/7/2024/11/SQL-Featured-Image-07-150x150.jpg</webfeeds:featuredImage></item>
<item>
<feedburner:origLink>https://www.baeldung.com/sql/blocking-queries-monitor-fix</feedburner:origLink>
		<title>How to Check Blocking Queries</title>
		<link>https://feeds.feedblitz.com/~/924429212/0/baeldung/sql~How-to-Check-Blocking-Queries</link>
		
		<dc:creator><![CDATA[Nikhil Bhargav]]></dc:creator>
		<pubDate>Sat, 06 Sep 2025 06:26:51 +0000</pubDate>
				<category><![CDATA[Database Access]]></category>
		<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[Transactions]]></category>
		<guid isPermaLink="false">https://www.baeldung.com/sql/how-to-check-blocking-queries</guid>
					<description><![CDATA[<img src="https://www.baeldung.com/wp-content/uploads/sites/7/2024/11/SQL-Featured-Image-07-1024x536.jpg" class="webfeedsFeaturedVisual wp-post-image" alt="" style="max-width:100% !important;height:auto !important;float: left; margin-right: 5px;" loading="lazy" />Learn to monitor blocked transactions in SQL Server 2022.<div style="clear:both;padding-top:0.2em;"><a title="Like on Facebook" href="https://feeds.feedblitz.com/_/28/924429212/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/fblike20.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Pin it!" href="https://feeds.feedblitz.com/_/29/924429212/baeldung/sql,https%3a%2f%2fwww.baeldung.com%2fwp-content%2fuploads%2fsites%2f7%2f2024%2f11%2fSQL-Featured-Image-07-1024x536.jpg"><img height="20" src="https://assets.feedblitz.com/i/pinterest20.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Post to X.com" href="https://feeds.feedblitz.com/_/24/924429212/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/x.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Subscribe by email" href="https://feeds.feedblitz.com/_/19/924429212/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/email20.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Subscribe by RSS" href="https://feeds.feedblitz.com/_/20/924429212/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/rss20.png" style="border:0;margin:0;padding:0;"></a>&nbsp;<h3 style="clear:left;padding-top:10px">Related Stories</h3><ul><li><a rel="NOFOLLOW" href="https://www.baeldung.com/sql/ms-sql-locks">Types of Locks in SQL Server</a></li><li><a rel="NOFOLLOW" href="https://www.baeldung.com/sql/azure-view-roles-permissions">Viewing Roles and Permissions Granted to Users of Azure SQL Server Instance</a></li><li><a rel="NOFOLLOW" href="https://www.baeldung.com/sql/mysql-host-not-allowed-error-troubleshoot">Fixing MySQL &#x2018;Host Not Allowed&#x2019; Error: A Simple Guide</a></li></ul>&#160;</div>]]>
</description>
										<content:encoded><![CDATA[<img src="https://www.baeldung.com/wp-content/uploads/sites/7/2024/11/SQL-Featured-Image-07-1024x536.jpg" class="webfeedsFeaturedVisual wp-post-image" alt="" style="float: left; margin-right: 5px;" decoding="async" loading="lazy" srcset="https://www.baeldung.com/wp-content/uploads/sites/7/2024/11/SQL-Featured-Image-07-1024x536.jpg 1024w, https://www.baeldung.com/wp-content/uploads/sites/7/2024/11/SQL-Featured-Image-07-300x157.jpg 300w, https://www.baeldung.com/wp-content/uploads/sites/7/2024/11/SQL-Featured-Image-07-768x402.jpg 768w, https://www.baeldung.com/wp-content/uploads/sites/7/2024/11/SQL-Featured-Image-07-100x52.jpg 100w, https://www.baeldung.com/wp-content/uploads/sites/7/2024/11/SQL-Featured-Image-07-600x314.jpg 600w, https://www.baeldung.com/wp-content/uploads/sites/7/2024/11/SQL-Featured-Image-07.jpg 1200w" sizes="auto, (max-width: 580px) 100vw, 580px" /><h2 id="bd-introduction" data-id="introduction">1. Introduction</h2>
<div class="bd-anchor" id="introduction"></div>
<p>In this tutorial, we&#8217;ll look at SQL blocking queries in-depth. We’ll use our <a href="https://feeds.feedblitz.com/~/t/0/0/baeldung/sql/~https://www.baeldung.com/sql/simple-schema">University schema</a> and SQL Server 2022 as our main SQL dialect.</p>
<p>SQL Server offers two ways to monitor blocking behavior:</p>
<ol>
<li>Using the SP_WHO2 stored procedure</li>
<li>Via an SQL query</li>
</ol>
<h2 id="bd-blocking-in-databases" data-id="blocking-in-databases">2. Blocking in Databases</h2>
<div class="bd-anchor" id="blocking-in-databases"></div>
<p>All SQL queries run under a session. <strong>We define a <em>blocking</em> session as holding a lock on a particular resource, which prevents other sessions from acquiring a conflicting lock type on that same resource</strong>.</p>
<p>Any blocked session must wait for the corresponding blocking session to complete its execution and release its lock on the resource.</p>
<p>Blocking queries can significantly impair database performance and business operations in many ways. For example, <strong>they can decrease throughput</strong> as queries take more than the normal time to complete. As a result, we see non-realtime user experience, application slowdowns, and poor business flow. Also, as database usage increases, a higher volume of concurrent transactions means <strong>longer execution times and increased disk I/O</strong>.</p>
<p>Thus, all these reasons motivate us to minimize blocking behavior in our database systems.</p>
<h2 id="bd-causes" data-id="causes">3. Causes</h2>
<div class="bd-anchor" id="causes"></div>
<p>Many things can contribute to blocking behavior.</p>
<p><strong>First, long-running queries cause a significant chunk of blocking of a database session</strong>. A long-running query holds its locks for the entire duration. Thus, it blocks other processes.</p>
<p>Second, we block a DB session when we cancel or kill a query. This is so because a process gets in a <a href="https://feeds.feedblitz.com/~/t/0/0/baeldung/sql/~https://www.baeldung.com/sql/mysql-transaction-management-statements">rollback</a> state when we cancel or kill a query (say, a client restart). In such a case, the database must undergo a rollback process to undo any data modifications. During this (potentially time-consuming) rollback, the query&#8217;s statements continue to hold <a href="https://feeds.feedblitz.com/~/t/0/0/baeldung/sql/~https://www.baeldung.com/sql/ms-sql-locks">locks</a>, which block other processes.</p>
<p>Another cause of blocking is when we set isolation levels for our transactions without thorough consideration. <strong>Any transaction isolation level other than Read Uncommitted also adds to blocking</strong>. For example, the database internally uses the default Read Committed level during read operations to prevent dirty reads. However, this leads to blocking if multiple transactions attempt to access the same data concurrently.</p>
<p>Higher isolation levels, such as Repeatable Read and Serializable, hold shared locks for the entire transaction duration. Thus, it increases their potential to cause blocking.</p>
<h2 id="bd-spwho2" data-id="spwho2">4. SP_WHO2</h2>
<div class="bd-anchor" id="spwho2"></div>
<p>Let&#8217;s check how SP_WHO2 helps detect blocking.</p>
<p data-pm-slice="1 1 [&quot;ordered_list&quot;,{&quot;spread&quot;:true,&quot;startingNumber&quot;:1,&quot;start&quot;:0,&quot;end&quot;:372},&quot;regular_list_item&quot;,{&quot;start&quot;:0,&quot;end&quot;:326}]">In the first session (<em>spid=56</em>), we run an <a href="https://feeds.feedblitz.com/~/t/0/0/baeldung/sql/~https://www.baeldung.com/sql/insert-update-if-row-exists">UPDATE</a> query on the <em>Course</em> table to set the credits of a particular course:</p>
<pre><code class="language-sql">BEGIN TRAN;
UPDATE Course
SET credits = 8
WHERE id = 'CS111';</code></pre>
<p>In our second session (<em>spid=58</em>), we run the same query with a different credit value. Since we didn&#8217;t commit or rollback the previous query, our second session blocks:</p>
<pre><code class="language-sql">BEGIN TRAN;
UPDATE Course
SET credits = 9
WHERE id = 'CS111';</code></pre>
<p>We now open a third session to execute this stored procedure to determine the source of blocking:</p>
<pre><code class="language-sql">EXEC sp_who2;</code></pre>
<p>And we can see that the second session is in the SUSPENDED state<em>:</em></p>
<pre><code class="language-shell">SPID  Status          BlkBy   Command         
----- -----------     ------- -----------------
56    sleeping        -        AWAITING COMMAND
58    SUSPENDED       56       UPDATE
</code></pre>
<p>The field <em>blkby</em> shows that the first session (<em>spid=56</em>) is its blocker.</p>
<h2 id="bd-dmv-query" data-id="dmv-query">5. DMV Query</h2>
<div class="bd-anchor" id="dmv-query"></div>
<p>Now we&#8217;ll explore how to solve the same problem using queries.</p>
<p><strong>SQL Server offers a framework called DMV, or dynamic management view</strong>. It provides granular information about the sessions, locks, and resources.</p>
<p>Let&#8217;s open a fourth session to run this query to know the reason and source of blocking of our second session:</p>
<pre><code class="language-sql">SELECT
    blocked.session_id,
    blocked.status,
    blocked.wait_type,
    blocking.session_id AS blocking_session_id,
    blocking.status AS blocking_status,
    blocked.command
FROM sys.dm_exec_requests AS blocked
INNER JOIN sys.dm_exec_sessions AS blocking ON blocked.blocking_session_id = blocking.session_id
LEFT JOIN sys.dm_exec_connections AS conn_blocked ON blocked.session_id = conn_blocked.session_id
LEFT JOIN sys.dm_exec_connections AS conn_blocking ON blocked.blocking_session_id = conn_blocking.session_id
OUTER APPLY sys.dm_exec_sql_text(conn_blocked.most_recent_sql_handle) AS blocked_sql
OUTER APPLY sys.dm_exec_sql_text(conn_blocking.most_recent_sql_handle) AS blocking_sql
WHERE blocked.blocking_session_id &lt;&gt; 0;</code></pre>
<p>The output shows that our second session (<em>spid=58</em>) is suspended by our first session (56), which holds a lock due to the update command:</p>
<pre><code class="language-shell">session_id  status       wait_type   blocking_session_id   blocking_status   command
----------  -----------  ----------- --------------------  ----------------  --------
58          suspended    LCK_M_X     56                    sleeping          UPDATE</code></pre>
<p>We can find the user who has blocked the session via attribute <em>blocking.login_name AS blocking_login.</em> Further, we can find the blocking command using the construct <em>blocking_sql.text AS blocking_query_text</em>.</p>
<h2 id="bd-blocking-termination" data-id="blocking-termination">6. Blocking Termination</h2>
<div class="bd-anchor" id="blocking-termination"></div>
<p>We can resolve the blocking behavior by either:</p>
<ol>
<li>Rolling back the blocking session</li>
<li>Committing the blocking session, or</li>
<li>Terminating the blocking session</li>
</ol>
<p>To terminate our blocking session (<em>spid=56</em>), we use the KILL command:</p>
<pre><code class="language-sql">KILL 56;</code></pre>
<p>The SQL Server immediately terminates the specified session and <span class="citation-20">initiates a </span><span class="citation-20">rollback</span><span class="citation-20 citation-end-20"> of any open transactions the killed session was running. As part of the rollback, all locks held by the session will be released, unblocking our second session.</span></p>
<h2 class="query-text-line ng-star-inserted" id="bd-comparison" data-id="comparison">7. Comparison</h2>
<div class="bd-anchor" id="comparison"></div>
<p>Let&#8217;s compare both solutions:</p>
<table class="table-styled" style="width: 83.297%;height: 381px">
<thead>
<tr>
<th style="width: 16.2723%">Method</th>
<th style="width: 22.608%">SP_WHO2</th>
<th style="width: 25.1116%">DMVs</th>
</tr>
</thead>
<tbody>
<tr>
<td style="width: 16.2723%">Ease of Use</td>
<td style="width: 22.608%">Very high</td>
<td style="width: 25.1116%">Moderate</td>
</tr>
<tr>
<td style="width: 16.2723%">Official Support</td>
<td style="width: 22.608%">Negligible</td>
<td style="width: 25.1116%">High</td>
</tr>
<tr>
<td style="width: 16.2723%">Flexibility</td>
<td style="width: 22.608%">Very low</td>
<td style="width: 25.1116%">Very high</td>
</tr>
<tr>
<td style="width: 16.2723%">Information Detail</td>
<td style="width: 22.608%">Low level</td>
<td style="width: 25.1116%">High level</td>
</tr>
<tr>
<td style="width: 16.2723%">Performance Impact</td>
<td style="width: 22.608%">Low</td>
<td style="width: 25.1116%">Higher</td>
</tr>
<tr>
<td style="width: 16.2723%">Use case</td>
<td style="width: 22.608%">Quick and ad-hoc checks for immediate blocking</td>
<td style="width: 25.1116%">In-depth analysis, proactive monitoring, and automated alerting for blocking and performance issues</td>
</tr>
</tbody>
</table>
<p>DMVs are more flexible than SP_WHO2 because of two main reasons.</p>
<p><strong>First, DMVs have customizable queries offering relational views</strong>. We can filter, join, and aggregate data in DMVs. On the other hand, SP_WHO2 offers a fixed output with making modifications very difficult.</p>
<p>Second, DMVs offer high level of detail such as such as blocking SQL query text, specific locks held (for example, LCK_M_S and LCK_M_X), lock duration, lock mode (S, X, U) and locked resource type (key, page, object). In contrast, SP_WHO2 offers minimal details (session id of blocker and blocker command).</p>
<h2 class="query-text-line ng-star-inserted" id="bd-best-practices" data-id="best-practices">8. Best Practices</h2>
<div class="bd-anchor" id="best-practices"></div>
<p>The most effective strategy for managing blocking in SQL Server is proactive prevention. Although identifying and addressing existing blocking is crucial, implementing measures to minimize the occurrence and duration of locks is much more impactful for maintaining a healthy, high-concurrency SQL Server environment.</p>
<h3 id="bd-1-transaction-management" data-id="1-transaction-management">8.1. Transaction Management</h3>
<div class="bd-anchor" id="1-transaction-management"></div>
<p>We should minimize the duration of each transaction by keeping them short and simple. We can do this by splitting every long transaction into smaller units. This approach significantly reduces the lock held duration there by decreasing the blocking window.</p>
<p><span class="button-container hide-from-message-actions ng-star-inserted"><strong>Another useful practice is to avoid taking user input within a transaction.</strong> User can delay and this often increases lock held duration </span>leading to blocking.<span class="button-container hide-from-message-actions ng-star-inserted">  </span></p>
<h3 id="bd-2-indexing-strategies" data-id="2-indexing-strategies">8.2. Indexing Strategies</h3>
<div class="bd-anchor" id="2-indexing-strategies"></div>
<p>Our SQL Server should have properly defined <a href="https://feeds.feedblitz.com/~/t/0/0/baeldung/sql/~https://www.baeldung.com/sql/databases-indexing">indexes</a>.</p>
<p>We should handle related indexes (clustering) and non-related indexes (singleton) indexes separately. This separation reduces logical reads, and minimizes the lock held duration.</p>
<p>All this leads to efficient data access by reducing the need for resource-intensive full table scans that acquire broader, more restrictive locks.</p>
<h3 id="bd-3-query-optimization" data-id="3-query-optimization">8.3. Query Optimization</h3>
<div class="bd-anchor" id="3-query-optimization"></div>
<p>We can use the construct <em>sys.dm_exec_query_plan</em> to identify performance bottlenecks and optimize inefficient queries. This reduces the execution time of resource-intensive queries.</p>
<p><strong>Second, we should avoid SELECT * when we don&#8217;t really need all columns of a table</strong>. This way, we reduce the amount of data read from disk and transferred over the network, thereby minimizing I/O and memory usage.</p>
<h3 id="bd-4-application-design" data-id="4-application-design">8.4. Application Design</h3>
<div class="bd-anchor" id="4-application-design"></div>
<p><strong>A good practice for making our application robust and deterministic is to implement retry logic to overcome transient errors, such as deadlocks or lock timeouts</strong>.</p>
<p>This allows the application to gracefully handle temporary blocking situations without crashing, improving overall system resilience.</p>
<h2 id="bd-conclusion" data-id="conclusion">9. Conclusion</h2>
<div class="bd-anchor" id="conclusion"></div>
<p>In this article, we studied blocking queries in depth by looking at the SP_WHO2 and SQL queries. We further showed that via queries, we can trace complex blocking chains, pinpoint head blockers, and uncover the precise root causes of concurrency issues. Then, we gave best practices to avoid blocking.</p>
<p>By adopting these best practices and maintaining a proactive stance, we can get minimal blocking and maximal concurrency of our database system. Thus, all this can offer a seamless user experience.</p><Img align="left" border="0" height="1" width="1" alt="" style="border:0;float:left;margin:0;padding:0;width:1px!important;height:1px!important;" hspace="0" src="https://feeds.feedblitz.com/~/i/924429212/0/baeldung/sql">
<div style="clear:both;padding-top:0.2em;"><a title="Like on Facebook" href="https://feeds.feedblitz.com/_/28/924429212/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/fblike20.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Pin it!" href="https://feeds.feedblitz.com/_/29/924429212/baeldung/sql,https%3a%2f%2fwww.baeldung.com%2fwp-content%2fuploads%2fsites%2f7%2f2024%2f11%2fSQL-Featured-Image-07-1024x536.jpg"><img height="20" src="https://assets.feedblitz.com/i/pinterest20.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Post to X.com" href="https://feeds.feedblitz.com/_/24/924429212/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/x.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Subscribe by email" href="https://feeds.feedblitz.com/_/19/924429212/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/email20.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Subscribe by RSS" href="https://feeds.feedblitz.com/_/20/924429212/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/rss20.png" style="border:0;margin:0;padding:0;"></a>&nbsp;<h3 style="clear:left;padding-top:10px">Related Stories</h3><ul><li><a rel="NOFOLLOW" href="https://www.baeldung.com/sql/ms-sql-locks">Types of Locks in SQL Server</a></li><li><a rel="NOFOLLOW" href="https://www.baeldung.com/sql/azure-view-roles-permissions">Viewing Roles and Permissions Granted to Users of Azure SQL Server Instance</a></li><li><a rel="NOFOLLOW" href="https://www.baeldung.com/sql/mysql-host-not-allowed-error-troubleshoot">Fixing MySQL &#x2018;Host Not Allowed&#x2019; Error: A Simple Guide</a></li></ul>&#160;</div>]]>
</content:encoded>
					
		
		
		<webfeeds:featuredImage>https://www.baeldung.com/wp-content/uploads/sites/7/2024/11/SQL-Featured-Image-07-150x150.jpg</webfeeds:featuredImage></item>
<item>
<feedburner:origLink>https://www.baeldung.com/sql/mysql-single-double-quotes-backticks</feedburner:origLink>
		<title>When to Use Single Quotes, Double Quotes, and Backticks in MySQL</title>
		<link>https://feeds.feedblitz.com/~/923992475/0/baeldung/sql~When-to-Use-Single-Quotes-Double-Quotes-and-Backticks-in-MySQL</link>
		
		<dc:creator><![CDATA[Enes Zvornicanin]]></dc:creator>
		<pubDate>Thu, 28 Aug 2025 23:33:20 +0000</pubDate>
				<category><![CDATA[SQL Basics]]></category>
		<category><![CDATA[MySQL]]></category>
		<category><![CDATA[Strings]]></category>
		<guid isPermaLink="false">https://www.baeldung.com/sql/?p=91496</guid>
					<description><![CDATA[<img src="https://www.baeldung.com/wp-content/uploads/sites/7/2024/11/SQL-Featured-Image-07-1024x536.jpg" class="webfeedsFeaturedVisual wp-post-image" alt="" style="max-width:100% !important;height:auto !important;float: left; margin-right: 5px;" loading="lazy" />Learn when to use single quotes, double quotes, and backticks in MySQL.<div style="clear:both;padding-top:0.2em;"><a title="Like on Facebook" href="https://feeds.feedblitz.com/_/28/923992475/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/fblike20.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Pin it!" href="https://feeds.feedblitz.com/_/29/923992475/baeldung/sql,https%3a%2f%2fwww.baeldung.com%2fwp-content%2fuploads%2fsites%2f7%2f2024%2f11%2fSQL-Featured-Image-07-1024x536.jpg"><img height="20" src="https://assets.feedblitz.com/i/pinterest20.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Post to X.com" href="https://feeds.feedblitz.com/_/24/923992475/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/x.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Subscribe by email" href="https://feeds.feedblitz.com/_/19/923992475/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/email20.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Subscribe by RSS" href="https://feeds.feedblitz.com/_/20/923992475/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/rss20.png" style="border:0;margin:0;padding:0;"></a>&nbsp;<h3 style="clear:left;padding-top:10px">Related Stories</h3><ul><li><a rel="NOFOLLOW" href="https://www.baeldung.com/sql/mysql-latitude-longitude-storage">What&#8217;s the Ideal Data Type to Use When Storing Latitude / Longitude in a MySQL Database?</a></li><li><a rel="NOFOLLOW" href="https://www.baeldung.com/sql/postgredql-convert-integer-string">Convert Integer to String in PostgreSQL</a></li><li><a rel="NOFOLLOW" href="https://www.baeldung.com/sql/mysql-file-import-cmd-line">Import an SQL File Using the Command Line in MySQL</a></li></ul>&#160;</div>]]>
</description>
										<content:encoded><![CDATA[<img src="https://www.baeldung.com/wp-content/uploads/sites/7/2024/11/SQL-Featured-Image-07-1024x536.jpg" class="webfeedsFeaturedVisual wp-post-image" alt="" style="float: left; margin-right: 5px;" decoding="async" loading="lazy" srcset="https://www.baeldung.com/wp-content/uploads/sites/7/2024/11/SQL-Featured-Image-07-1024x536.jpg 1024w, https://www.baeldung.com/wp-content/uploads/sites/7/2024/11/SQL-Featured-Image-07-300x157.jpg 300w, https://www.baeldung.com/wp-content/uploads/sites/7/2024/11/SQL-Featured-Image-07-768x402.jpg 768w, https://www.baeldung.com/wp-content/uploads/sites/7/2024/11/SQL-Featured-Image-07-100x52.jpg 100w, https://www.baeldung.com/wp-content/uploads/sites/7/2024/11/SQL-Featured-Image-07-600x314.jpg 600w, https://www.baeldung.com/wp-content/uploads/sites/7/2024/11/SQL-Featured-Image-07.jpg 1200w" sizes="auto, (max-width: 580px) 100vw, 580px" /><h2 id="bd-introduction" data-id="introduction">1. Introduction</h2>
<div class="bd-anchor" id="introduction"></div>
<p><strong>In this tutorial, we&#8217;ll explore the correct usage of single quotes, double quotes, and backticks in MySQL.</strong></p>
<p>Although appearing similar, these three types of quotation marks serve very different purposes in MySQL. Understanding the correct use of each is essential for writing clear, error-free <a href="https://feeds.feedblitz.com/~/t/0/0/baeldung/sql/~https://www.baeldung.com/sql/sql-statements-queries#2-sql-queries">SQL queries</a> and avoiding common pitfalls, especially when dealing with strings, identifiers, and reserved keywords.</p>
<h2 id="bd-single-quotes-in-mysql" data-id="single-quotes-in-mysql">2. Single Quotes in MySQL</h2>
<div class="bd-anchor" id="single-quotes-in-mysql"></div>
<p><strong>We primarily use single quotes (&#8216;&#8230;&#8217;) for string literals in MySQL.</strong> Whenever we need to specify a fixed string value, such as a name, date, or text data, we should use single quotes:</p>
<pre><code class="language-sql">SELECT * FROM users WHERE name = 'Lee Xin';</code></pre>
<p>MySQL interprets everything inside single quotes as a literal string. If our string contains a single quote character, then <a href="https://feeds.feedblitz.com/~/t/0/0/baeldung/sql/~https://www.baeldung.com/cs/sql-injection">we must escape it</a> with another single quote:</p>
<pre><code class="language-sql">SELECT 'It''s a sunny day';</code></pre>
<p>This escaping prevents syntax errors and ensures that the string is correctly processed. We can test this query with one and two quotes using <a href="https://feeds.feedblitz.com/~/t/0/0/baeldung/sql/~https://onecompiler.com/mysql">online MySQL compiler.</a> The results will look like this:</p>
<pre><code class="language-sql">&gt; SELECT 'It's a sunny day';
ERROR 1064 ...
&gt; SELECT 'It''s a sunny day';
+-----------+
+ It's a sunny day</code></pre>
<p>As we can see, it outputs an error when we use only a single quote inside single quotes that define our string.</p>
<h2 id="bd-double-quotes-in-mysql" data-id="double-quotes-in-mysql">3. Double Quotes in MySQL</h2>
<div class="bd-anchor" id="double-quotes-in-mysql"></div>
<p><strong>Double quotes (&#8220;&#8230;&#8221;) have a special role depending on the SQL mode.</strong></p>
<p>By default, in MySQL&#8217;s ANSI_QUOTES mode, double quotes are the same as backticks. It means they identify column or table names. In a non-ANSI_QUOTES mode, double quotes can sometimes act like single quotes for string literals, but relying on this behavior can cause compatibility issues across environments.</p>
<p>For example, lets assume we have the following query:</p>
<pre><code class="language-sql">SELECT "column" FROM table WHERE foo = "bar";</code></pre>
<p>Here we can have two outcomes:</p>
<ul>
<li>If ANSI_QUOTES is enabled, the query will select the values from column named <em>column</em> where column <em>foo</em> is equal to column <em>bar</em>.</li>
<li>Otherwise, the query will select the string literal &#8220;column&#8221; where column <em>foo</em> is equal to string &#8220;bar&#8221;.</li>
</ul>
<p><strong>The best practice is to avoid using double quotes so that our code becomes independent of <a href="https://feeds.feedblitz.com/~/t/0/0/baeldung/sql/~https://dev.mysql.com/doc/refman/8.4/en/sql-mode.html#sqlmode_ansi_quotes">SQL modes</a>.</strong></p>
<h2 id="bd-backticks-in-mysql" data-id="backticks-in-mysql">4. Backticks in MySQL</h2>
<div class="bd-anchor" id="backticks-in-mysql"></div>
<p><strong>We use backticks (`&#8230;`) for delimiting identifiers such as column names, table names, and database names that might otherwise cause problems</strong> because they are <a href="https://feeds.feedblitz.com/~/t/0/0/baeldung/sql/~https://www.baeldung.com/sql/column-names-use-reserved-words">reserved keywords</a>, contain spaces, or special characters:</p>
<pre><code class="language-sql">SELECT `order`, `user name` FROM `sales data`;</code></pre>
<p>Without backticks, &#8220;order&#8221; would be interpreted as a reserved keyword, and &#8220;user name&#8221; would be invalid due to the space. Backticks ensure that MySQL treats the enclosed text as an identifier exactly as written.</p>
<h2 id="bd-conclusion" data-id="conclusion">5. Conclusion</h2>
<div class="bd-anchor" id="conclusion"></div>
<p>In this article, we clarified when to use single quotes, double quotes, and backticks in MySQL.</p>
<p><strong>Single quotes are the standard for string literals</strong>. Double quotes are best avoided, as their meaning shifts depending on the SQL mode. <strong>Backticks remain the safest and most reliable choice for column, table, and database names</strong> that include reserved keywords, spaces, or special characters.</p><Img align="left" border="0" height="1" width="1" alt="" style="border:0;float:left;margin:0;padding:0;width:1px!important;height:1px!important;" hspace="0" src="https://feeds.feedblitz.com/~/i/923992475/0/baeldung/sql">
<div style="clear:both;padding-top:0.2em;"><a title="Like on Facebook" href="https://feeds.feedblitz.com/_/28/923992475/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/fblike20.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Pin it!" href="https://feeds.feedblitz.com/_/29/923992475/baeldung/sql,https%3a%2f%2fwww.baeldung.com%2fwp-content%2fuploads%2fsites%2f7%2f2024%2f11%2fSQL-Featured-Image-07-1024x536.jpg"><img height="20" src="https://assets.feedblitz.com/i/pinterest20.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Post to X.com" href="https://feeds.feedblitz.com/_/24/923992475/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/x.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Subscribe by email" href="https://feeds.feedblitz.com/_/19/923992475/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/email20.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Subscribe by RSS" href="https://feeds.feedblitz.com/_/20/923992475/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/rss20.png" style="border:0;margin:0;padding:0;"></a>&nbsp;<h3 style="clear:left;padding-top:10px">Related Stories</h3><ul><li><a rel="NOFOLLOW" href="https://www.baeldung.com/sql/mysql-latitude-longitude-storage">What&#8217;s the Ideal Data Type to Use When Storing Latitude / Longitude in a MySQL Database?</a></li><li><a rel="NOFOLLOW" href="https://www.baeldung.com/sql/postgredql-convert-integer-string">Convert Integer to String in PostgreSQL</a></li><li><a rel="NOFOLLOW" href="https://www.baeldung.com/sql/mysql-file-import-cmd-line">Import an SQL File Using the Command Line in MySQL</a></li></ul>&#160;</div>]]>
</content:encoded>
					
		
		
		<webfeeds:featuredImage>https://www.baeldung.com/wp-content/uploads/sites/7/2024/11/SQL-Featured-Image-07-150x150.jpg</webfeeds:featuredImage></item>
<item>
<feedburner:origLink>https://www.baeldung.com/sql/mysql-boolean</feedburner:origLink>
		<title>Which MySQL Data Type Is Best for Storing Boolean Values?</title>
		<link>https://feeds.feedblitz.com/~/923602925/0/baeldung/sql~Which-MySQL-Data-Type-Is-Best-for-Storing-Boolean-Values</link>
		
		<dc:creator><![CDATA[Zachary Bouhannana]]></dc:creator>
		<pubDate>Thu, 21 Aug 2025 16:59:27 +0000</pubDate>
				<category><![CDATA[Database Concepts]]></category>
		<category><![CDATA[Boolean]]></category>
		<category><![CDATA[MySQL]]></category>
		<guid isPermaLink="false">https://www.baeldung.com/sql/which-mysql-data-type-is-best-for-storing-boolean-values</guid>
					<description><![CDATA[<img src="https://www.baeldung.com/wp-content/uploads/sites/7/2024/03/SQL-Featured-Image-01-1024x536.jpg" class="webfeedsFeaturedVisual wp-post-image" alt="" style="max-width:100% !important;height:auto !important;float: left; margin-right: 5px;" loading="lazy" />Learn different ways to represent and handle Boolean values within MySQL databases.<div style="clear:both;padding-top:0.2em;"><a title="Like on Facebook" href="https://feeds.feedblitz.com/_/28/923602925/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/fblike20.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Pin it!" href="https://feeds.feedblitz.com/_/29/923602925/baeldung/sql,https%3a%2f%2fwww.baeldung.com%2fwp-content%2fuploads%2fsites%2f7%2f2024%2f03%2fSQL-Featured-Image-01-1024x536.jpg"><img height="20" src="https://assets.feedblitz.com/i/pinterest20.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Post to X.com" href="https://feeds.feedblitz.com/_/24/923602925/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/x.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Subscribe by email" href="https://feeds.feedblitz.com/_/19/923602925/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/email20.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Subscribe by RSS" href="https://feeds.feedblitz.com/_/20/923602925/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/rss20.png" style="border:0;margin:0;padding:0;"></a>&nbsp;<h3 style="clear:left;padding-top:10px">Related Stories</h3><ul><li><a rel="NOFOLLOW" href="https://www.baeldung.com/sql/mysql-file-import-cmd-line">Import an SQL File Using the Command Line in MySQL</a></li><li><a rel="NOFOLLOW" href="https://www.baeldung.com/sql/mysql-single-double-quotes-backticks">When to Use Single Quotes, Double Quotes, and Backticks in MySQL</a></li><li><a rel="NOFOLLOW" href="https://www.baeldung.com/sql/mysql-latitude-longitude-storage">What&#8217;s the Ideal Data Type to Use When Storing Latitude / Longitude in a MySQL Database?</a></li></ul>&#160;</div>]]>
</description>
										<content:encoded><![CDATA[<img src="https://www.baeldung.com/wp-content/uploads/sites/7/2024/03/SQL-Featured-Image-01-1024x536.jpg" class="webfeedsFeaturedVisual wp-post-image" alt="" style="float: left; margin-right: 5px;" decoding="async" loading="lazy" srcset="https://www.baeldung.com/wp-content/uploads/sites/7/2024/03/SQL-Featured-Image-01-1024x536.jpg 1024w, https://www.baeldung.com/wp-content/uploads/sites/7/2024/03/SQL-Featured-Image-01-300x157.jpg 300w, https://www.baeldung.com/wp-content/uploads/sites/7/2024/03/SQL-Featured-Image-01-768x402.jpg 768w, https://www.baeldung.com/wp-content/uploads/sites/7/2024/03/SQL-Featured-Image-01-100x52.jpg 100w, https://www.baeldung.com/wp-content/uploads/sites/7/2024/03/SQL-Featured-Image-01.jpg 1200w" sizes="auto, (max-width: 580px) 100vw, 580px" /><h2 id="bd-overview" data-id="overview">1. Overview</h2>
<div class="bd-anchor" id="overview"></div>
<p>Storing <a href="https://feeds.feedblitz.com/~/t/0/0/baeldung/sql/~https://www.baeldung.com/sql/columns-default-value#mysql">Boolean</a> values is a basic requirement in most database-driven applications. We often use them to track user preferences, feature toggles, or permissions in a table. So, learning how to reliably store binary logic in <a href="https://feeds.feedblitz.com/~/t/0/0/baeldung/sql/~https://dev.mysql.com/doc/refman/8.4/en/">MySQL</a> can be critical.</p>
<p>This might seem obvious, but MySQL doesn&#8217;t offer a true Boolean data type in the traditional sense. Instead<strong>, it uses workarounds that may be confusing and lead to unexpected behavior if misunderstood</strong>. Yet, choosing the right data type ensures efficiency and compatibility across applications and environments.</p>
<p>In this tutorial, we&#8217;ll explore how MySQL represents Boolean values, what data types we can use instead, and which option makes the most sense for storing true/false data.</p>
<h2 id="bd-mysql-boolean-type-support" data-id="mysql-boolean-type-support">2. MySQL Boolean Type Support</h2>
<div class="bd-anchor" id="mysql-boolean-type-support"></div>
<p>In short, yes &#8211; we can define columns as BOOLEAN or BOOL. However, <strong>unlike other <a href="https://feeds.feedblitz.com/~/t/0/0/baeldung/sql/~https://www.baeldung.com/cs/relational-database#10-popular-relational-database-management-systems-rdbms">database management systems</a> (DBMS), MySQL considers Boolean an alias for <em>TINYINT(1)</em></strong>.</p>
<p>This means, <strong>when we define a column as BOOLEAN, MySQL actually creates a <em>TINYINT(1)</em> column that can store values from <em>-128</em> to <em>127</em> (if signed) or from <em>0</em> to <em>255</em>  (if unsigned)</strong>. Under the hood, MySQL converts <em>FALSE</em> to <em>0</em> and <em>TRUE</em> to <em>1</em>.</p>
<p>Considering this, let&#8217;s create a sample users table and insert some data:</p>
<pre><code class="language-sql">CREATE TABLE Users (
  empId INTEGER PRIMARY KEY,
  name TEXT NOT NULL,
  dept TEXT NOT NULL,
  is_active BOOL not null
);
-- insert
INSERT INTO Users VALUES (1, 'Zack', 'Sales', TRUE);
INSERT INTO Users VALUES (2, 'Mark', 'Marketing', FALSE);</code></pre>
<p>Next, we query this table using SELECT and WHERE to retrieve the active users:</p>
<pre><code class="language-sql">SELECT * FROM USERS WHERE is_active is true;
Output:
+-------+------+-------+-----------+
| empId | name | dept  | is_active |
+-------+------+-------+-----------+
|     1 | Zack | Sales |         1 |
+-------+------+-------+-----------+
</code></pre>
<p>Thus, we can notice that MySQL indeed stores <em>1</em> instead of <em>TRUE</em>.</p>
<p>Of course, we can also do the opposite, and <strong>instead of using the Boolean values <em>TRUE</em> and <em>FALSE</em>, we can just type their respective numeric values <em>1</em> or <em>0</em></strong>:</p>
<pre><code class="language-sql">INSERT INTO Users VALUES (1, 'Zack', 'Sales', 1);
     -- OR
SELECT * FROM Users WHERE is_active = 1;</code></pre>
<p>This returns the same result. Both approaches work the same way, so the choice often comes down to code readability.</p>
<h2 id="bd-use-tinyint-directly" data-id="use-tinyint-directly">3. Use TINYINT Directly</h2>
<div class="bd-anchor" id="use-tinyint-directly"></div>
<p>Now that we understand how MySQL handles the BOOLEAN data type, we can simply use TINYINT(1) directly instead.</p>
<p>Let&#8217;s employ ALTER TABLE to update the <em>USERS</em> table to redefine the <em>is_active</em> column as TINYINT(1) instead of BOOL:</p>
<pre><code class="language-sql">ALTER TABLE Users
MODIFY COLUMN is_active TINYINT(1);</code></pre>
<p>Now, if we rerun the same tests from the previous example, we get identical results. <strong>This confirms that we can use BOOLEAN and TINYINT(1) interchangeably in MySQL</strong>.</p>
<p>Notably, MySQL can convert Boolean values to and from other <a href="https://feeds.feedblitz.com/~/t/0/0/baeldung/sql/~https://dev.mysql.com/doc/refman/8.4/en/integer-types.html">integer types</a> like INT, SMALLINT, or BIGINT in the same way. That said, TINYINT(1) remains the most space-efficient choice.</p>
<h2 id="bd-use-bit-with-0-or-1" data-id="use-bit-with-0-or-1">4. Use BIT With <em>0</em> or <em>1</em></h2>
<div class="bd-anchor" id="use-bit-with-0-or-1"></div>
<p>A Boolean represents two possible values (true or false), and MySQL offers a way to store this binary logic with <a href="https://feeds.feedblitz.com/~/t/0/0/baeldung/sql/~https://dev.mysql.com/doc/refman/8.0/en/bit-type.html">BIT</a>. Technically, <strong>BIT(1) can store a single binary value (0 or 1), making it a natural fit for representing Boolean values</strong>. However, it&#8217;s often less practical in real-world use cases.</p>
<p>Let&#8217;s start by updating the Users table to define the <em>is_active</em> column as BIT(1):</p>
<pre><code class="language-sql">ALTER TABLE Users
MODIFY COLUMN is_active BIT(1) NOT NULL;</code></pre>
<p>Next, we add some records:</p>
<pre><code class="language-sql">INSERT INTO USERS VALUES (1, 'Zack', 'Sales', b'1');
INSERT INTO USERS VALUES (2, 'Mike', 'HR', b'0');</code></pre>
<p>Here, the <em>b&#8217;value&#8217;</em> notation explicitly tells MySQL we&#8217;re inserting a binary literal with a value that contains only <em>0</em> and <em>1</em>.</p>
<p>However, there&#8217;s another catch with BIT: <strong>by default, MySQL may display BIT values as non-printable characters or binary blob</strong>:</p>
<pre><code class="language-sql">SELECT empId, name, dept, is_active FROM Users;
+-------+------+-------+-----------+
| empId | name | dept  | is_active |
+-------+------+-------+-----------+
|     1 | Zack | Sales |           |
|     2 | Mike | HR    |           |
+-------+------+-------+-----------+
</code></pre>
<p>So, if we want to retrieve BIT values as visible zeroes and ones, we need to explicitly convert them into a readable format:</p>
<pre><code class="language-sql">SELECT empId, name, dept, BIN(is_active) AS is_active_bin
FROM Users;
+-------+------+-------+---------------+
| empId | name | dept  | is_active_bin |
+-------+------+-------+---------------+
|     1 | Zack | Sales |             1 |
+-------+------+-------+---------------+</code></pre>
<p>In the above query, <strong>we use the <a href="https://feeds.feedblitz.com/~/t/0/0/baeldung/sql/~https://dev.mysql.com/doc/refman/8.4/en/string-functions.html#function_bin">BIN()</a> function to see the binary representation as a string</strong>.</p>
<p>Alternatively, another option is to use <a href="https://feeds.feedblitz.com/~/t/0/0/baeldung/sql/~https://dev.mysql.com/doc/refman/8.0/en/cast-functions.html#function_cast">CAST()</a>:</p>
<pre><code class="language-sql">SELECT empId, name, dept, CAST(is_active AS UNSIGNED) AS is_active_num FROM Users;</code></pre>
<p>The CAST function displays BIT(1) values as numeric <em>0</em> or <em>1</em>. It converts the binary data into unsigned integers.</p>
<p>In practice, BIT can be tricky and even inconsistent across platforms. For example, many developers report normal behavior on Windows but issues on Linux systems. Furthermore, <strong>BIT(1) still takes up a full byte, just like TINYINT(1)</strong>. Considering that, it&#8217;s simpler to just use TINYINT(1).</p>
<h2 id="bd-use-enum-with-custom-values" data-id="use-enum-with-custom-values">5. Use ENUM With Custom Values</h2>
<div class="bd-anchor" id="use-enum-with-custom-values"></div>
<p>What if we want to use custom Boolean-like values similar to what&#8217;s possible in other DBMSs? We can rely on ENUM for that. <strong>It enables us to define a specific set of values for a column, like <em>yes</em> and <em>no</em></strong>.</p>
<p>As usual, let&#8217;s update the Users table and change the type of the <em>is_active</em> column to <em>ENUM</em>:</p>
<pre><code class="language-sql">ALTER TABLE Users 
MODIFY COLUMN is_active ENUM('yes', 'no') NOT NULL;</code></pre>
<p>After this change, the <em>is_active</em> column accepts either <em>yes</em> or <em>no</em> values. Additionally, MySQL can also take these values as numeric indexes (<em>yes</em> as <em>1</em>, <em>no</em> as <em>2</em>).</p>
<p>Let&#8217;s insert two rows of data and query the table:</p>
<pre><code class="language-">INSERT INTO Users VALUES (1, 'Nick', 'Accounting', yes);
INSERT INTO Users VALUES (2, 'John', 'Marketing', 2);
SELECT * FROM Users
+-------+------+-----------+------------+
| empId | name | dept       | is_active
+-------+------+-----------+------------+
|     1 | Nick | Accounting | yes       |
|     2 | John | Marketing  | no        |
+-------+------+------------+-----------+</code>
Here, the first row uses the defined ENUM value directly (<em>yes</em>). The second row uses its numeric index (<em>2</em>), which MySQL automatically maps to the corresponding label (<em>no</em>). Basically, <strong>this shows that we can query ENUM values either by label or by index</strong>.</pre>
<h2 id="bd-conclusion" data-id="conclusion">6. Conclusion</h2>
<div class="bd-anchor" id="conclusion"></div>
<p>In this article, we explored how MySQL interprets Boolean values and the most common data types available to represent true and false logic. Specifically, we found that MySQL uses BOOL and TINYINT(1) interchangeably, learned how to work with the BIT type, and applied ENUM for custom true and false labels.</p>
<p>In conclusion, although we can use multiple data types to represent Boolean values, TINYINT(1) remains the most reliable, space-efficient choice.</p><Img align="left" border="0" height="1" width="1" alt="" style="border:0;float:left;margin:0;padding:0;width:1px!important;height:1px!important;" hspace="0" src="https://feeds.feedblitz.com/~/i/923602925/0/baeldung/sql">
<div style="clear:both;padding-top:0.2em;"><a title="Like on Facebook" href="https://feeds.feedblitz.com/_/28/923602925/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/fblike20.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Pin it!" href="https://feeds.feedblitz.com/_/29/923602925/baeldung/sql,https%3a%2f%2fwww.baeldung.com%2fwp-content%2fuploads%2fsites%2f7%2f2024%2f03%2fSQL-Featured-Image-01-1024x536.jpg"><img height="20" src="https://assets.feedblitz.com/i/pinterest20.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Post to X.com" href="https://feeds.feedblitz.com/_/24/923602925/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/x.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Subscribe by email" href="https://feeds.feedblitz.com/_/19/923602925/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/email20.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Subscribe by RSS" href="https://feeds.feedblitz.com/_/20/923602925/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/rss20.png" style="border:0;margin:0;padding:0;"></a>&nbsp;<h3 style="clear:left;padding-top:10px">Related Stories</h3><ul><li><a rel="NOFOLLOW" href="https://www.baeldung.com/sql/mysql-file-import-cmd-line">Import an SQL File Using the Command Line in MySQL</a></li><li><a rel="NOFOLLOW" href="https://www.baeldung.com/sql/mysql-single-double-quotes-backticks">When to Use Single Quotes, Double Quotes, and Backticks in MySQL</a></li><li><a rel="NOFOLLOW" href="https://www.baeldung.com/sql/mysql-latitude-longitude-storage">What&#8217;s the Ideal Data Type to Use When Storing Latitude / Longitude in a MySQL Database?</a></li></ul>&#160;</div>]]>
</content:encoded>
					
		
		
		<webfeeds:featuredImage>https://www.baeldung.com/wp-content/uploads/sites/7/2024/03/SQL-Featured-Image-01-150x150.jpg</webfeeds:featuredImage></item>
<item>
<feedburner:origLink>https://www.baeldung.com/sql/sargability</feedburner:origLink>
		<title>What Is Sargability in SQL?</title>
		<link>https://feeds.feedblitz.com/~/923435873/0/baeldung/sql~What-Is-Sargability-in-SQL</link>
		
		<dc:creator><![CDATA[Damilare Keshinro]]></dc:creator>
		<pubDate>Mon, 18 Aug 2025 14:43:34 +0000</pubDate>
				<category><![CDATA[SQL Queries]]></category>
		<category><![CDATA[Indexes]]></category>
		<guid isPermaLink="false">https://www.baeldung.com/sql/sargability</guid>
					<description><![CDATA[<img src="https://www.baeldung.com/wp-content/uploads/sites/7/2024/11/SQL-Featured-Image-05-1024x536.jpg" class="webfeedsFeaturedVisual wp-post-image" alt="" style="max-width:100% !important;height:auto !important;float: left; margin-right: 5px;" loading="lazy" />Learn what sargability is and why it matters.<div style="clear:both;padding-top:0.2em;"><a title="Like on Facebook" href="https://feeds.feedblitz.com/_/28/923435873/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/fblike20.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Pin it!" href="https://feeds.feedblitz.com/_/29/923435873/baeldung/sql,https%3a%2f%2fwww.baeldung.com%2fwp-content%2fuploads%2fsites%2f7%2f2024%2f11%2fSQL-Featured-Image-05-1024x536.jpg"><img height="20" src="https://assets.feedblitz.com/i/pinterest20.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Post to X.com" href="https://feeds.feedblitz.com/_/24/923435873/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/x.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Subscribe by email" href="https://feeds.feedblitz.com/_/19/923435873/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/email20.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Subscribe by RSS" href="https://feeds.feedblitz.com/_/20/923435873/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/rss20.png" style="border:0;margin:0;padding:0;"></a>&nbsp;<h3 style="clear:left;padding-top:10px">Related Stories</h3><ul><li><a rel="NOFOLLOW" href="https://www.baeldung.com/sql/database-size">How to Retrieve the Database Size?</a></li><li><a rel="NOFOLLOW" href="https://www.baeldung.com/sql/select-except-columns">How to Exclude a Column Using SELECT EXCEPT in SQL</a></li><li><a rel="NOFOLLOW" href="https://www.baeldung.com/sql/subquery-update-rows">Updating Rows With a Subquery Referencing the Same Table in SQL</a></li></ul>&#160;</div>]]>
</description>
										<content:encoded><![CDATA[<img src="https://www.baeldung.com/wp-content/uploads/sites/7/2024/11/SQL-Featured-Image-05-1024x536.jpg" class="webfeedsFeaturedVisual wp-post-image" alt="" style="float: left; margin-right: 5px;" decoding="async" loading="lazy" srcset="https://www.baeldung.com/wp-content/uploads/sites/7/2024/11/SQL-Featured-Image-05-1024x536.jpg 1024w, https://www.baeldung.com/wp-content/uploads/sites/7/2024/11/SQL-Featured-Image-05-300x157.jpg 300w, https://www.baeldung.com/wp-content/uploads/sites/7/2024/11/SQL-Featured-Image-05-768x402.jpg 768w, https://www.baeldung.com/wp-content/uploads/sites/7/2024/11/SQL-Featured-Image-05-100x52.jpg 100w, https://www.baeldung.com/wp-content/uploads/sites/7/2024/11/SQL-Featured-Image-05-600x314.jpg 600w, https://www.baeldung.com/wp-content/uploads/sites/7/2024/11/SQL-Featured-Image-05.jpg 1200w" sizes="auto, (max-width: 580px) 100vw, 580px" /><h2 id="bd-introduction" data-id="introduction">1. Introduction</h2>
<div class="bd-anchor" id="introduction"></div>
<p>Performance optimization is very crucial in SQL for database applications, especially when it involves large datasets. A key concept that impacts query speed is sargability (Search ARGument ABILITY).</p>
<p>Sargability refers to the ability of an SQL query to utilize database <a href="https://feeds.feedblitz.com/~/t/0/0/baeldung/sql/~https://www.baeldung.com/sql/databases-indexing">indexes</a> to speed up data retrieval operations. <strong>It is when the conditions within a <em>WHERE, HAVING, and ORDER BY </em>clause scan, but also JOINs and HAVING, are leveraged by the database engine to efficiently retrieve rows via indexing</strong>. When a query is sargable, the optimizer can determine whether to use index seeks (for small subsets of rows) or index scans for accessing larger data.</p>
<p>In this tutorial, we&#8217;ll explain sargability, what makes a query sargable, tools for identifying sargability, how it affects performance, and how to write sargable SQL queries. This tutorial uses the table from Baeldung’s <a href="https://feeds.feedblitz.com/~/t/0/0/baeldung/sql/~https://www.baeldung.com/sql/full-schema">simple <em>U</em><em>niversity </em>database schema</a>.</p>
<h2 id="bd-what-makes-an-sql-statement-sargable" data-id="what-makes-an-sql-statement-sargable">2. What Makes an SQL Statement Sargable?</h2>
<div class="bd-anchor" id="what-makes-an-sql-statement-sargable"></div>
<p>The core concept of sargability revolves around search arguments that can efficiently leverage database indexes to optimize query execution.</p>
<p>The difference between sargable and non-sargable queries is this: <strong>sargable queries enable the optimizer to determine when to use index seek and index scans</strong>. Non-sargable queries often force the database to perform full table scans, as they can&#8217;t utilize indexes due to their search conditions.</p>
<p>For a query to efficiently use an index, certain conditions must be met in the WHERE, JOIN, or ORDER BY clauses:</p>
<ul>
<li>Direct column comparisons using operators like =, &lt;, &gt;, &lt;=, &gt;=, or BETWEEN</li>
<li>No functions or calculations applied to the indexed column (e.g., avoid LOWER(column) or column + 10)</li>
<li>Consistent data types between the column and the comparison value to avoid implicit type conversion</li>
<li>Leading column usage in multi-column indexes (e.g., use the first column in the index)</li>
<li>Pattern matching with a trailing wildcard, such as LIKE &#8216;abc%&#8217;, rather than LIKE &#8216;%abc&#8217;</li>
<li>Use of IN with specific values (e.g., WHERE id IN (1, 2, 3)), depending on the database engine</li>
</ul>
<p>These conditions help the database perform index seeks rather than full scans, improving performance and reducing resource usage.</p>
<h2 id="bd-tools-to-identify-non-sargable-queries" data-id="tools-to-identify-non-sargable-queries">3. Tools to Identify Non-Sargable Queries</h2>
<div class="bd-anchor" id="tools-to-identify-non-sargable-queries"></div>
<p>Detecting a non-sargable query at the early stage helps to optimize performance. It allows database admins, analysts, or developers to refactor the queries rather than executing inefficient queries with cost and computational implications. The table below shows the tools for identifying sargability in different SQL versions:</p>
<table class="table-styled" style="border-collapse: collapse;width: 100%;height: 361px">
<thead>
<tr style="height: 24px">
<th style="width: 12.9927%;height: 24px">Tool</th>
<th style="width: 25.0166%;height: 24px">Sargability Indicator</th>
<th style="width: 36.6066%;height: 24px">Command</th>
<th style="width: 25.3841%;height: 24px"> Description</th>
</tr>
</thead>
<tbody>
<tr style="height: 144px">
<td style="width: 12.9927%;height: 144px">SQL Server</td>
<td style="width: 25.0166%;height: 144px">Index Seek vs Scan</td>
<td style="width: 36.6066%;height: 144px">SET SHOWPLAN_TEXT ON;</p>
<p>&nbsp;</p>
<p>SET STATISTICS IO ON;</td>
<td style="width: 25.3841%;height: 144px">Shows the execution plan</p>
<p>&nbsp;</p>
<p>Reveals read operation</td>
</tr>
<tr style="height: 25px">
<td style="width: 12.9927%;height: 25px">PostgreSQL</td>
<td style="width: 25.0166%;height: 25px">Index Scan vs Seq Scan</td>
<td style="width: 36.6066%;height: 25px">EXPLAIN ANALYZE &#8212; add query;</td>
<td style="width: 25.3841%;height: 25px">Checks index usage</td>
</tr>
<tr style="height: 168px">
<td style="width: 12.9927%;height: 168px">MYSQL</td>
<td style="width: 25.0166%;height: 168px">type: range vs ALL or NULL</td>
<td style="width: 36.6066%;height: 168px">EXPLAIN FORMAT=JSON &#8211;add query;</p>
<p>&nbsp;</p>
<p>EXPLAIN ANALYZE &#8212; add query;</p>
<p>&nbsp;</p>
<p>EXPLAIN &#8212; add query;</td>
<td style="width: 25.3841%;height: 168px">Returns query analysis in JSON format</p>
<p>&nbsp;</p>
<p>Shows the query&#8217;s cost and time usage</p>
<p>&nbsp;</p>
<p>Checks index usage and filters</td>
</tr>
</tbody>
</table>
<p>In addition, it is important to note these observations:</p>
<ul>
<li>Check execution plans for table scans instead of index seeks</li>
<li>Pay attention to warnings regarding &#8220;implicit conversions&#8221; or &#8220;cardinality estimate errors&#8221;</li>
<li>Monitor and compare query read times relative to the rows returned</li>
</ul>
<p>Examples in the next section use <i>the EXPLAIN</i> command to detect non-sargable queries.</p>
<h2 id="bd-examples-of-sargable-vs-non-sargable-queries" data-id="examples-of-sargable-vs-non-sargable-queries">4. Examples of Sargable vs. Non-Sargable Queries</h2>
<div class="bd-anchor" id="examples-of-sargable-vs-non-sargable-queries"></div>
<p>Understanding the difference between sargable and non-sargable queries becomes easier with practical examples. In this section, we aim to highlight the common query patterns that prevent index usage and understand the best way to rewrite them. Rather than focusing on the query result, we use <em>EXPLAIN</em> to analyze if a query is sargable or not.</p>
<h3 id="bd-1-function-on-a-column" data-id="1-function-on-a-column"><strong>4.1. Function on a Column</strong></h3>
<div class="bd-anchor" id="1-function-on-a-column"></div>
<p>Wrapping a column in a function like <em>CAST()</em>, <i>YEAR(), </i>or <em>CONVERT()</em> makes the query non-sargable, as it prevents the use of an index even if applicable to the specified column:</p>
<pre class="add-horizontal-scrollbar"><code class="language-sql">-- Non-Sargable
EXPLAIN SELECT * FROM Student 
WHERE YEAR(birth_date) = 2001;
+----+-------------+---------+------------+------+---------------+------+---------+------+------+----------+-------------+
| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+----+-------------+---------+------------+------+---------------+------+---------+------+------+----------+-------------+
| 1 | SIMPLE | Student | NULL | ALL | NULL | NULL | NULL | NULL | 25 | 100 | Using where |
+----+-------------+---------+------------+------+---------------+------+---------+------+------+----------+-------------+
</code></pre>
<p>Here, the <em>YEAR()</em> function is applied to <em>birth_date</em>, so the index on the birth_date column is ignored. Let&#8217;s look at a sargable alternative:</p>
<pre class="add-horizontal-scrollbar"><code class="language-sql">-- Sargable
EXPLAIN SELECT * FROM Student 
WHERE birth_date &gt;= '2001-01-01' AND birth_date &lt; '2002-01-01';
+----+-------------+---------+------------+-------+---------------+----------+---------+------+------+----------+-----------------------+
| id | select_type | table   | partitions | type  | possible_keys | key      | key_len | ref  | rows | filtered | Extra                 |
+----+-------------+---------+------------+-------+---------------+----------+---------+------+------+----------+-----------------------+
|  1 | SIMPLE      | Student | NULL       | range | year_idx      | year_idx | 4       | NULL |   10 |      100 | Using index condition |
+----+-------------+---------+------------+-------+---------------+----------+---------+------+------+----------+-----------------------+</code></pre>
<p>This query is sargable because it allows the optimizer to search the columns in the <em>WHERE</em> clause using index scans.</p>
<h3 id="bd-2-leading-wildcard-in-like" data-id="2-leading-wildcard-in-like"><strong>4.2. Leading Wildcard in LIKE</strong></h3>
<div class="bd-anchor" id="2-leading-wildcard-in-like"></div>
<p>Using a preceding &#8220;%&#8221; when performing a text search prevents the use of an index on the column to be searched:</p>
<pre class="add-horizontal-scrollbar"><code class="language-">-- non-sargable
EXPLAIN SELECT * FROM Student WHERE name LIKE '%Po';
+----+-------------+---------+------------+------+---------------+------+---------+------+------+--------------------+-------------+
| id | select_type | table   | partitions | type | possible_keys | key  | key_len | ref  | rows | filtered           | Extra       |
+----+-------------+---------+------------+------+---------------+------+---------+------+------+--------------------+-------------+
|  1 | SIMPLE      | student | NULL       | ALL  | NULL          | NULL | NULL    | NULL |   25 | 11.110000610351562 | Using where |
+----+-------------+---------+------------+------+---------------+------+---------+------+------+--------------------+-------------+</code></pre>
<p>The better approach to make the query sargable is to use the wildcard at the end of the search, just like this:</p>
<pre class="add-horizontal-scrollbar"><code class="language-sql">-- Sargable
EXPLAIN SELECT * FROM Student WHERE name LIKE 'Po%';
+----+-------------+---------+------------+-------+---------------+------------+---------+------+------+----------+-----------------------+
| id | select_type | table   | partitions | type  | possible_keys | key        | key_len | ref  | rows | filtered | Extra                 |
+----+-------------+---------+------------+-------+---------------+------------+---------+------+------+----------+-----------------------+
|  1 | SIMPLE      | student | NULL       | range | index_name    | index_name | 243     | NULL |    2 |      100 | Using index condition |</code></pre>
<p>The above table shows that the query will utilize the &#8220;index_name&#8221; index, reducing the search to two rows.</p>
<h3 id="bd-3-data-type-mismatch" data-id="3-data-type-mismatch"><strong>4.3. Data Type Mismatch</strong></h3>
<div class="bd-anchor" id="3-data-type-mismatch"></div>
<p>If the <em>id</em> in the column is numerical (INT), using a quote in the search can make the query non-sargable, because the engine first converts the data type from VARCHAR to INT before executing the query:</p>
<pre class="add-horizontal-scrollbar"><code class="language-sql">-- Non-Sargable (if id is INT)
SELECT * FROM customers WHERE id = '1001';
</code></pre>
<p>A better alternative is to run the search without the quote. It shows the significant difference between the two queries:</p>
<pre><code class="language-sql">-- Sargable
SELECT * FROM customers WHERE id = 1001;
</code></pre>
<p>The above query won&#8217;t need a data type conversion. Hence, it&#8217;s considered searchable.</p>
<h3 id="bd-4-or-conditions-across-different-columns" data-id="4-or-conditions-across-different-columns"><strong>4.4. OR Conditions Across Different Columns</strong></h3>
<div class="bd-anchor" id="4-or-conditions-across-different-columns"></div>
<p>The <em>OR</em> condition can be sargable if the columns in the conditions have appropriate indexes. However, the columns become non-sargable when neither of them has an index, the columns do not share a composite index, or the query combines indexed and non-indexed columns.</p>
<pre class="add-horizontal-scrollbar"><code class="language-sql">-- non-sargable 
EXPLAIN 
SELECT * FROM Student 
WHERE national_id = 123345566 OR name = 'John Liu';
+----+-------------+---------+------------+------+---------------+------+---------+------+------+--------------------+-------------+
| id | select_type | table   | partitions | type | possible_keys | key  | key_len | ref  | rows | filtered           | Extra       |
+----+-------------+---------+------------+------+---------------+------+---------+------+------+--------------------+-------------+
|  1 | SIMPLE      | Student | NULL       | ALL  | index_name    | NULL | NULL    | NULL |   25 | 13.600000381469727 | Using where |
+----+-------------+---------+------------+------+---------------+------+---------+------+------+--------------------+-------------+</code></pre>
<p>We can fix this by using a <em>UNION</em> statement, which ensures that each column is independently indexed:</p>
<pre class="add-horizontal-scrollbar"><code class="language-sql">-- Sargable
EXPLAIN 
SELECT * FROM Student WHERE national_id = 123345566
UNION 
SELECT * FROM Student WHERE name='John Liu';
+----+--------------+------------+------------+------+---------------+------------+---------+-------+------+----------+-----------------+
| id | select_type  | table      | partitions | type | possible_keys | key        | key_len | ref   | rows | filtered | Extra           |
+----+--------------+------------+------------+------+---------------+------------+---------+-------+------+----------+-----------------+
|  1 | PRIMARY      | Student    | NULL       | ALL  | NULL          | NULL       | NULL    | NULL  |   25 |       10 | Using where     |
|  2 | UNION        | student    | NULL       | ref  | index_name    | index_name | 243     | const |    1 |      100 | NULL            |
|  3 | UNION RESULT | &lt;union1,2&gt; | NULL       | ALL  | NULL          | NULL       | NULL    | NULL  | NULL |     NULL | Using temporary |
+----+--------------+------------+------------+------+---------------+------------+---------+-------+------+----------+-----------------+</code></pre>
<p>While the first part uses a full table scan due to the lack of an index on the <em>national_id</em> column, the second part uses an index and a &#8220;<em>ref</em>&#8220;. Since a part of the query benefits from using an index, it helps to retain sargability.</p>
<h3 id="bd-5-sargability-in-joins" data-id="5-sargability-in-joins"><strong>4.5. Sargability in JOINs</strong></h3>
<div class="bd-anchor" id="5-sargability-in-joins"></div>
<p><strong>What makes <em>JOINs</em> and subqueries sargable is if predicates or conditions can use indexes</strong>. Avoiding functions when trying to match case-sensitive composite columns makes a significant difference:</p>
<pre class="add-horizontal-scrollbar"><code class="language-sql">-- non-sargable JOIN
EXPLAIN SELECT c.name, e.semester, e.grade 
FROM Course c 
JOIN Exam e 
       ON LOWER(c.id) = LOWER(e.course_id) 
WHERE c.credits &gt; 4;
+----+-------------+-------+------------+------+---------------+------+---------+------+------+-------------------+--------------------------------------------+
| id | select_type | table | partitions | type | possible_keys | key  | key_len | ref  | rows | filtered          | Extra                                      |
+----+-------------+-------+------------+------+---------------+------+---------+------+------+-------------------+--------------------------------------------+
|  1 | SIMPLE      | c     | NULL       | ALL  | NULL          | NULL | NULL    | NULL |   81 | 33.32999801635742 | Using where                                |
|  1 | SIMPLE      | e     | NULL       | ALL  | NULL          | NULL | NULL    | NULL |  143 |               100 | Using where; Using join buffer (hash join) |
+----+-------------+-------+------------+------+---------------+------+---------+------+------+-------------------+--------------------------------------------+</code></pre>
<p>From the output, we can see why this is non-sargable. Many of the conditions listed in section 2 also apply to optimizing JOINs. It is important to ensure that filtering happens in the execution plan rather than after joining large datasets. Let&#8217;s now look at a sargable version.</p>
<pre class="add-horizontal-scrollbar"><code class="language-sql">-- Sargable
EXPLAIN SELECT c.name, e.semester, e.grade 
FROM Course c 
JOIN Exam e 
        ON c.id = e.course_id 
WHERE c.credits &gt; 4;
+----+-------------+-------+------------+------+---------------------+---------------------+---------+-----------------+------+-------------------+-------------+
| id | select_type | table | partitions | type | possible_keys       | key                 | key_len | ref             | rows | filtered          | Extra       |
+----+-------------+-------+------------+------+---------------------+---------------------+---------+-----------------+------+-------------------+-------------+
|  1 | SIMPLE      | c     | NULL       | ALL  | PRIMARY,id          | NULL                | NULL    | NULL            |   81 | 33.32999801635742 | Using where |
|  1 | SIMPLE      | e     | NULL       | ref  | exam_course_id_fkey | exam_course_id_fkey | 43      | university.c.id |    1 |               100 | NULL        |
+----+-------------+-------+------------+------+---------------------+---------------------+---------+-----------------+------+-------------------+-------------+</code></pre>
<p>Removing the functions and sticking to direct column comparison with the &#8220;&gt;&#8221; operator solves the optimization issue from the first query.</p>
<h2 id="bd-how-non-sargable-queries-affect-performance" data-id="how-non-sargable-queries-affect-performance">5. How Non-Sargable Queries Affect Performance</h2>
<div class="bd-anchor" id="how-non-sargable-queries-affect-performance"></div>
<p>Non-sargable queries force the database engine to ignore indexes and perform full table scans, thereby degrading performance. This results in higher CPU usage, increased disk I/O, and longer execution time as the dataset gets larger.</p>
<p>When indexes do not apply to queries, the engine examines every row to determine if it matches the computationally expensive condition. For non-sargable JOINs, or subqueries, the query optimizer may be forced to use inefficient join strategies or process larger results than necessary.</p>
<p>Additionally, non-sargable queries create scaling issues. A query that performs acceptably on small datasets (e.g., 10,000 rows) may become unusable on larger tables (e.g., 10 million rows) due to the non-linear growth in resource requirements.</p>
<h2 id="bd-difference-in-sargability-across-sql-engines" data-id="difference-in-sargability-across-sql-engines">6. Difference in Sargability Across SQL Engines</h2>
<div class="bd-anchor" id="difference-in-sargability-across-sql-engines"></div>
<p>The table below shows details on how different database engines interpret and optimize queries for sargability. It is important to make this distinction in cases when we&#8217;re tuning for specific environments:</p>
<table class="table-styled" style="border-collapse: collapse;width: 100%">
<tbody>
<tr>
<th style="width: 20%">Feature</th>
<th style="width: 20%">SQL Server</th>
<th style="width: 20%">PostgreSQL</th>
<th style="width: 20%">MySQL</th>
<th style="width: 20%">Oracle</th>
</tr>
<tr>
<td style="width: 20%">Function on Indexed Column</td>
<td style="width: 20%">Non-sargable unless using a computed column index</td>
<td style="width: 20%">Non-sargable, but can utilise function-based index</td>
<td style="width: 20%">Breaks sargability function-based indexes not native</td>
<td style="width: 20%">Supports function-based index</td>
</tr>
<tr>
<td style="width: 20%">Implicit Type Conversion</td>
<td style="width: 20%">Can silently break index usage</td>
<td style="width: 20%">Can be detected in the query plan</td>
<td style="width: 20%">Common cause of non-sargable queries</td>
<td style="width: 20%">may result in an index skip unless there are matching data types</td>
</tr>
<tr>
<td style="width: 20%">LIKE with leading Wildcard</td>
<td style="width: 20%">Non-sargable</td>
<td style="width: 20%">Non-sargable</td>
<td style="width: 20%">Non-sargable</td>
<td style="width: 20%">Non-sargable</td>
</tr>
<tr>
<td style="width: 20%">OR conditions on Multiple Columns</td>
<td style="width: 20%">Can be non-sargable unless it has a composite index</td>
<td style="width: 20%">May use sequential scan depending on context</td>
<td style="width: 20%">Non-sargable without <em>UNION</em> or composite index</td>
<td style="width: 20%">may use the function index depending on the query type</td>
</tr>
<tr>
<td style="width: 20%">Index on expression</td>
<td style="width: 20%">Supported</td>
<td style="width: 20%">Supported</td>
<td style="width: 20%">Supported for generated columns</td>
<td style="width: 20%">Supported</td>
</tr>
</tbody>
</table>
<h2 id="bd-conclusion" data-id="conclusion">7. Conclusion</h2>
<div class="bd-anchor" id="conclusion"></div>
<p>Sargability isn&#8217;t just about having indexes. It&#8217;s about ensuring that queries can use indexes more efficiently. However, this concept of SQL query optimization is often overlooked due to more focus on functionality rather than performance. Understanding this concept can improve the scalability of database systems.</p>
<p>In this article, we explored what sargability is and why it matters, common patterns that prevent sargability, sargable and non-sargable examples, and tools and techniques to identify non-sargable conditions.</p><Img align="left" border="0" height="1" width="1" alt="" style="border:0;float:left;margin:0;padding:0;width:1px!important;height:1px!important;" hspace="0" src="https://feeds.feedblitz.com/~/i/923435873/0/baeldung/sql">
<div style="clear:both;padding-top:0.2em;"><a title="Like on Facebook" href="https://feeds.feedblitz.com/_/28/923435873/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/fblike20.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Pin it!" href="https://feeds.feedblitz.com/_/29/923435873/baeldung/sql,https%3a%2f%2fwww.baeldung.com%2fwp-content%2fuploads%2fsites%2f7%2f2024%2f11%2fSQL-Featured-Image-05-1024x536.jpg"><img height="20" src="https://assets.feedblitz.com/i/pinterest20.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Post to X.com" href="https://feeds.feedblitz.com/_/24/923435873/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/x.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Subscribe by email" href="https://feeds.feedblitz.com/_/19/923435873/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/email20.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Subscribe by RSS" href="https://feeds.feedblitz.com/_/20/923435873/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/rss20.png" style="border:0;margin:0;padding:0;"></a>&nbsp;<h3 style="clear:left;padding-top:10px">Related Stories</h3><ul><li><a rel="NOFOLLOW" href="https://www.baeldung.com/sql/database-size">How to Retrieve the Database Size?</a></li><li><a rel="NOFOLLOW" href="https://www.baeldung.com/sql/select-except-columns">How to Exclude a Column Using SELECT EXCEPT in SQL</a></li><li><a rel="NOFOLLOW" href="https://www.baeldung.com/sql/subquery-update-rows">Updating Rows With a Subquery Referencing the Same Table in SQL</a></li></ul>&#160;</div>]]>
</content:encoded>
					
		
		
		<webfeeds:featuredImage>https://www.baeldung.com/wp-content/uploads/sites/7/2024/11/SQL-Featured-Image-05-150x150.jpg</webfeeds:featuredImage></item>
<item>
<feedburner:origLink>https://www.baeldung.com/sql/subquery-update-rows</feedburner:origLink>
		<title>Updating Rows With a Subquery Referencing the Same Table in SQL</title>
		<link>https://feeds.feedblitz.com/~/923263661/0/baeldung/sql~Updating-Rows-With-a-Subquery-Referencing-the-Same-Table-in-SQL</link>
		
		<dc:creator><![CDATA[Deepak Vohra]]></dc:creator>
		<pubDate>Fri, 15 Aug 2025 03:01:19 +0000</pubDate>
				<category><![CDATA[SQL Joins]]></category>
		<category><![CDATA[SQL Queries]]></category>
		<category><![CDATA[Subquery]]></category>
		<category><![CDATA[UPDATE]]></category>
		<category><![CDATA[UPDATE JOIN]]></category>
		<category><![CDATA[WHERE]]></category>
		<guid isPermaLink="false">https://www.baeldung.com/sql/subquery-update-rows</guid>
					<description><![CDATA[<img src="https://www.baeldung.com/wp-content/uploads/sites/7/2024/03/SQL-Featured-Image-01-1024x536.jpg" class="webfeedsFeaturedVisual wp-post-image" alt="" style="max-width:100% !important;height:auto !important;float: left; margin-right: 5px;" loading="lazy" />Learn how to update a table based on data from that table by using an SQL subquery.<div style="clear:both;padding-top:0.2em;"><a title="Like on Facebook" href="https://feeds.feedblitz.com/_/28/923263661/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/fblike20.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Pin it!" href="https://feeds.feedblitz.com/_/29/923263661/baeldung/sql,https%3a%2f%2fwww.baeldung.com%2fwp-content%2fuploads%2fsites%2f7%2f2024%2f03%2fSQL-Featured-Image-01-1024x536.jpg"><img height="20" src="https://assets.feedblitz.com/i/pinterest20.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Post to X.com" href="https://feeds.feedblitz.com/_/24/923263661/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/x.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Subscribe by email" href="https://feeds.feedblitz.com/_/19/923263661/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/email20.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Subscribe by RSS" href="https://feeds.feedblitz.com/_/20/923263661/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/rss20.png" style="border:0;margin:0;padding:0;"></a>&nbsp;<h3 style="clear:left;padding-top:10px">Related Stories</h3><ul><li><a rel="NOFOLLOW" href="https://www.baeldung.com/sql/update-via-select">How to UPDATE a Record Using a SELECT in SQL Server</a></li><li><a rel="NOFOLLOW" href="https://www.baeldung.com/sql/distinct-count-combination">Combining DISTINCT and COUNT In a SQL Query</a></li><li><a rel="NOFOLLOW" href="https://www.baeldung.com/sql/where-subselect-columns">How to Use Columns From a Subselect in WHERE Clause in SQL</a></li></ul>&#160;</div>]]>
</description>
										<content:encoded><![CDATA[<img src="https://www.baeldung.com/wp-content/uploads/sites/7/2024/03/SQL-Featured-Image-01-1024x536.jpg" class="webfeedsFeaturedVisual wp-post-image" alt="" style="float: left; margin-right: 5px;" decoding="async" loading="lazy" srcset="https://www.baeldung.com/wp-content/uploads/sites/7/2024/03/SQL-Featured-Image-01-1024x536.jpg 1024w, https://www.baeldung.com/wp-content/uploads/sites/7/2024/03/SQL-Featured-Image-01-300x157.jpg 300w, https://www.baeldung.com/wp-content/uploads/sites/7/2024/03/SQL-Featured-Image-01-768x402.jpg 768w, https://www.baeldung.com/wp-content/uploads/sites/7/2024/03/SQL-Featured-Image-01-100x52.jpg 100w, https://www.baeldung.com/wp-content/uploads/sites/7/2024/03/SQL-Featured-Image-01.jpg 1200w" sizes="auto, (max-width: 580px) 100vw, 580px" /><h2 id="bd-overview" data-id="overview">1. Overview</h2>
<div class="bd-anchor" id="overview"></div>
<p>Subqueries are SELECT statements nested inside other <a href="https://feeds.feedblitz.com/~/t/0/0/baeldung/sql/~https://www.baeldung.com/sql/sql-statements-queries">SQL statements</a>. Such nested queries execute first and return a result, which is then used by the outer query.</p>
<p>In this tutorial, <strong>we&#8217;ll demonstrate how to update rows using a <a href="https://feeds.feedblitz.com/~/t/0/0/baeldung/sql/~https://www.baeldung.com/sql/subquery-outer-table-reference">subquery</a> that references the same table in a MySQL relational database</strong>. Then, we&#8217;ll demonstrate that we can <a href="https://feeds.feedblitz.com/~/t/0/0/baeldung/sql/~https://www.baeldung.com/sql/update-multiple-rows-different-values-same-query">update rows</a> via an UPDATE &#8230; FROM statement referencing the same table in both the PostgreSQL and the SQL Server relational databases.</p>
<p>Notably, we&#8217;ll employ the <em>Program</em> table from the <a href="https://feeds.feedblitz.com/~/t/0/0/baeldung/sql/~https://www.baeldung.com/sql/full-schema">Baeldung <em>University</em> database</a>.</p>
<h2 id="bd-mysql-database" data-id="mysql-database">2. MySQL Database</h2>
<div class="bd-anchor" id="mysql-database"></div>
<p>Let&#8217;s suppose we want to update the <em>end_date</em> in the <em>Program</em> table to equal the <em>start_date + 3</em> weeks for all rows. To achieve this, we have two main options.</p>
<p>At the outset, <strong>we can&#8217;t use a simple UPDATE &#8230; FROM statement in MySQL to access the outer query table within a subquery</strong> in an UPDATE statement. In fact, when we try to do this, we encounter <em><a href="https://feeds.feedblitz.com/~/t/0/0/baeldung/sql/~https://www.baeldung.com/sql/mysql-fix-error-1093-hy000">ERROR 1093 (HY000)</a>: You can&#8217;t specify the target table &#8216;x&#8217; for update in the FROM clause</em>.</p>
<h3 id="bd-1-using-a-subquery-within-a-self-join" data-id="1-using-a-subquery-within-a-self-join">2.1. Using a Subquery Within a Self-Join</h3>
<div class="bd-anchor" id="1-using-a-subquery-within-a-self-join"></div>
<p>We can <strong>update rows using a subquery that references the same table through a <a href="https://feeds.feedblitz.com/~/t/0/0/baeldung/sql/~https://www.baeldung.com/sql/create-temp-tables-select">self-join</a></strong>. <strong>This method is especially useful if parts of the updated data come from within the same table</strong>, e.g., updating the <em>end_date</em> column based on the <em>start_date</em> column:</p>
<pre><code class="language-sql">UPDATE Program AS P1
JOIN (
    SELECT id, DATE_ADD(start_date, INTERVAL 3 WEEK) AS new_end_date
    FROM Program
) AS P2
ON P1.id = P2.id
SET P1.end_date = P2.new_end_date;</code></pre>
<p>In this case, the statement above joins the <em>Program</em> table with a temporary table (<em>P2</em>) that contains the calculated <em>new_end_date</em> for every row. The UPDATE then sets the <em>end_date</em> of each row in <em>P1</em> to the corresponding value from <em>P2</em>.</p>
<p>Thus, we update all 24 rows in the table. Let&#8217;s verify this with a SELECT query on the table:</p>
<pre><code class="language-sql">SELECT start_date,end_date from Program;
+------------+------------+
| start_date | end_date   |
+------------+------------+
| 2012-01-01 | 2012-01-22 |
| 2012-01-01 | 2012-01-22 |
| 2011-01-01 | 2011-01-22 |
| 2011-01-01 | 2011-01-22 |
| 2010-01-01 | 2010-01-22 |
| 2010-01-01 | 2010-01-22 |
| 2018-07-01 | 2018-07-22 |
| 2018-07-01 | 2018-07-22 |
| 2011-01-11 | 2011-02-01 |
| 2011-01-11 | 2011-02-01 |
| 2010-07-11 | 2010-08-01 |
| 2010-07-11 | 2010-08-01 |
| 2010-07-01 | 2010-07-22 |
| 2010-07-01 | 2010-07-22 |
| 2010-07-01 | 2010-07-22 |
| 2010-07-01 | 2010-07-22 |
| 2010-01-11 | 2010-02-01 |
| 2010-01-11 | 2010-02-01 |
| 2011-07-01 | 2011-07-22 |
| 2011-07-01 | 2011-07-22 |
| 2011-01-11 | 2011-02-01 |
| 2011-01-11 | 2011-02-01 |
| 2010-07-11 | 2010-08-01 |
| 2010-07-11 | 2010-08-01 |
+------------+------------+</code></pre>
<p>As expected, all values are updated properly.</p>
<h3 id="bd-2-using-a-subquery-within-a-derived-table" data-id="2-using-a-subquery-within-a-derived-table">2.2. Using a Subquery Within a Derived Table</h3>
<div class="bd-anchor" id="2-using-a-subquery-within-a-derived-table"></div>
<p>As another option, we can <strong>use a derived table</strong> for updating with data within the same table. In particular, the derived table <em>Temp_table</em> acts as an intermediate result set that the outer UPDATE query depends upon. Therefore, the UPDATE is performed only after the result set from the derived table is materialized:</p>
<pre><code class="language-sql">UPDATE Program
SET end_date = (
    SELECT new_end_date FROM (
        SELECT DATE_ADD(start_date, INTERVAL 3 WEEK) AS new_end_date
        FROM Program AS Temp
        WHERE Temp.id = Program.id
    ) AS Temp_table
);</code></pre>
<p>In this example, the subquery calculates the <em>end_date</em> for each row individually by joining the <em>Temp_table</em> to the <em>Program</em> table on the <em>id</em> column.</p>
<h2 id="bd-postgresql-database" data-id="postgresql-database">3. PostgreSQL Database</h2>
<div class="bd-anchor" id="postgresql-database"></div>
<p><strong>The PostgreSQL UPDATE syntax is more flexible and doesn&#8217;t require a nested subquery</strong> to avoid a self-referencing error. Again, we have two options for the example task of updating the <em>end_date</em> column in the <em>Program</em> table to equal the <em>start_date + 3</em> weeks for all rows.</p>
<h3 id="bd-1-using-a-self-join" data-id="1-using-a-self-join">3.1. Using a Self-Join</h3>
<div class="bd-anchor" id="1-using-a-self-join"></div>
<p>Even in the case of PostgreSQL, we can <strong>update all 24 rows using a self-join, but this time we don&#8217;t need a SELECT subquery</strong>:</p>
<pre><code class="language-sql">UPDATE Program AS P1
SET end_date = P2.start_date + INTERVAL '3 weeks'
FROM Program AS P2
WHERE P1.id = p2.id;</code></pre>
<p>In fact, this is perhaps the most common method for performing such an update in PostgreSQL. Specifically, it joins the <em>Program</em> table (aliased as <em>P1</em>) with itself (aliased as <em>P2</em>) on the <em>id</em> field and sets the <em>P1</em> <em>end_date</em> to the calculated value from <em>P2</em>.</p>
<p><strong>Let&#8217;s verify all 24 rows are updated</strong>:</p>
<pre><code class="language-sql">postgres=&gt; SELECT start_date, end_date from Program;
 2012-01-01 | 2012-01-22
 2011-01-01 | 2011-01-22
 2011-01-01 | 2011-01-22
 2018-07-01 | 2018-07-22
 2018-07-01 | 2018-07-22
 2010-01-11 | 2010-02-01
 2010-01-11 | 2010-02-01
 2011-07-01 | 2011-07-22
 2011-07-01 | 2011-07-22
 2010-07-01 | 2010-07-22
 2010-07-01 | 2010-07-22
 2010-07-01 | 2010-07-22
 2010-07-01 | 2010-07-22
 2011-01-11 | 2011-02-01
 2011-01-11 | 2011-02-01
 2010-07-11 | 2010-08-01
 2010-07-11 | 2010-08-01
 2011-01-11 | 2011-02-01
 2011-01-11 | 2011-02-01
 2010-07-11 | 2010-08-01
 2010-07-11 | 2010-08-01
(24 rows)</code></pre>
<p>Similar to the previous example, the self-join works in practice.</p>
<h3 id="bd-2-using-a-subquery-within-an-update--set-statement" data-id="2-using-a-subquery-within-an-update--set-statement">3.2. Using a Subquery Within an UPDATE &#8230; SET Statement</h3>
<div class="bd-anchor" id="2-using-a-subquery-within-an-update--set-statement"></div>
<p>We can <strong>use a subquery within the SET clause of the UPDATE statement</strong>:</p>
<pre><code class="language-sql">UPDATE Program
SET end_date = (
    SELECT start_date + INTERVAL '3 weeks'
    FROM Program AS Temp
    WHERE Temp.id = Program.id
);</code></pre>
<p>This query updates each row by correlating it with a subquery on the same table. Furthermore, the subquery fetches the <em>start_date</em> for the corresponding <em>id</em> and adds three weeks. Again, we can verify that the <em>end_date</em> is set to <em>start_date</em> + 3 weeks using a simple, unnested SELECT query.</p>
<h2 id="bd-sql-server-database" data-id="sql-server-database">4. SQL Server Database</h2>
<div class="bd-anchor" id="sql-server-database"></div>
<p><strong>The SQL Server UPDATE&#8230;JOIN syntax is very powerful, enabling us to join tables directly within the UPDATE statement</strong>. In this case, we use the DATEADD function for date calculations. So, let&#8217;s discuss two options to update the <em>end_date</em> in the <em>Program</em> table.</p>
<h3 id="bd-1-using-a-self-join-1" data-id="1-using-a-self-join-1">4.1. Using a Self-Join</h3>
<div class="bd-anchor" id="1-using-a-self-join-1"></div>
<p>Similar to PostgreSQL, we can <strong>use a self-join without a nested subquery</strong>:</p>
<pre><code class="language-sql">UPDATE P1
SET P1.end_date = DATEADD(week, 3, P2.start_date)
FROM Program AS P1
JOIN Program AS P2
ON P1.id = P2.id;</code></pre>
<p>This statement updates <em>P1</em> using a JOIN to <em>P2</em> on the <em>id</em> column. Specifically, the FROM clause defines the tables being used and their aliases, and the SET clause performs the update using the joined data.</p>
<h3 id="bd-2-using-a-subquery-within-an-update--set-statement-1" data-id="2-using-a-subquery-within-an-update--set-statement-1">4.2. Using a Subquery Within an UPDATE &#8230; SET Statement</h3>
<div class="bd-anchor" id="2-using-a-subquery-within-an-update--set-statement-1"></div>
<p>Lastly, as an alternative, we can <strong>use a subquery</strong> within an UPDATE &#8230; SET statement:</p>
<pre><code class="language-sql">UPDATE Program
SET end_date = (
    SELECT DATEADD(week, 3, start_date)
    FROM Program AS Temp
    WHERE Temp.id = Program.id
);</code></pre>
<p>Similar to PostgreSQL, SQL Server can employ a correlated subquery to update each row based on its own data without a complex nested structure.</p>
<h2 id="bd-conclusion" data-id="conclusion">5. Conclusion</h2>
<div class="bd-anchor" id="conclusion"></div>
<p>In this article, we learned about updating rows in a table using a subquery on the same table.</p>
<p>MySQL doesn&#8217;t support a straightforward UPDATE &#8230; FROM statement; therefore, we usually need a nested subquery using a self-join or a derived table. However, PostgreSQL and SQL Server can both use an UPDATE &#8230; FROM syntax to update rows using data obtained from the same table; therefore, we don&#8217;t always need a subquery.</p><Img align="left" border="0" height="1" width="1" alt="" style="border:0;float:left;margin:0;padding:0;width:1px!important;height:1px!important;" hspace="0" src="https://feeds.feedblitz.com/~/i/923263661/0/baeldung/sql">
<div style="clear:both;padding-top:0.2em;"><a title="Like on Facebook" href="https://feeds.feedblitz.com/_/28/923263661/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/fblike20.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Pin it!" href="https://feeds.feedblitz.com/_/29/923263661/baeldung/sql,https%3a%2f%2fwww.baeldung.com%2fwp-content%2fuploads%2fsites%2f7%2f2024%2f03%2fSQL-Featured-Image-01-1024x536.jpg"><img height="20" src="https://assets.feedblitz.com/i/pinterest20.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Post to X.com" href="https://feeds.feedblitz.com/_/24/923263661/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/x.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Subscribe by email" href="https://feeds.feedblitz.com/_/19/923263661/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/email20.png" style="border:0;margin:0;padding:0;"></a>&#160;<a title="Subscribe by RSS" href="https://feeds.feedblitz.com/_/20/923263661/baeldung/sql"><img height="20" src="https://assets.feedblitz.com/i/rss20.png" style="border:0;margin:0;padding:0;"></a>&nbsp;<h3 style="clear:left;padding-top:10px">Related Stories</h3><ul><li><a rel="NOFOLLOW" href="https://www.baeldung.com/sql/update-via-select">How to UPDATE a Record Using a SELECT in SQL Server</a></li><li><a rel="NOFOLLOW" href="https://www.baeldung.com/sql/distinct-count-combination">Combining DISTINCT and COUNT In a SQL Query</a></li><li><a rel="NOFOLLOW" href="https://www.baeldung.com/sql/where-subselect-columns">How to Use Columns From a Subselect in WHERE Clause in SQL</a></li></ul>&#160;</div>]]>
</content:encoded>
					
		
		
		<webfeeds:featuredImage>https://www.baeldung.com/wp-content/uploads/sites/7/2024/03/SQL-Featured-Image-01-150x150.jpg</webfeeds:featuredImage></item>
</channel></rss>

