<?xml version="1.0" encoding="UTF-8"?><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:media="http://search.yahoo.com/mrss/" >

<channel>
	<title>SQL Server Guides</title>
	<atom:link href="https://sqlserverguides.com/feed/" rel="self" type="application/rss+xml" />
	<link>https://sqlserverguides.com</link>
	<description>Tutorials on SQL Server</description>
	<lastBuildDate>Wed, 18 Nov 2026 12:01:22 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=7.1.5</generator>

<image>
	<url>https://sqlserverguides.com/wp-content/uploads/2023/10/sqlserverguides-150x150.png</url>
	<title>SQL Server Guides</title>
	<link>https://sqlserverguides.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>SQL Server LAG and LEAD Functions</title>
		<link>https://sqlserverguides.com/sql-server-lag-and-lead-functions/</link>
		
		<dc:creator><![CDATA[Bijay Kumar Sahoo]]></dc:creator>
		<pubDate>Wed, 18 Nov 2026 11:59:52 +0000</pubDate>
				<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[SQL Server LAG and LEAD Functions]]></category>
		<guid isPermaLink="false">https://sqlserverguides.com/?p=24144</guid>

					<description><![CDATA[A sales dashboard shows the wrong month-over-month change even though its totals look correct. The reporting query compares one customer’s revenue with another customer’s previous row. Meanwhile, a separate batch process uses a loop to calculate gaps between orders. SQL Server LAG and LEAD Functions solve adjacent-row comparisons without requiring a self-join for every calculation. ... <a title="SQL Server LAG and LEAD Functions" class="read-more" href="https://sqlserverguides.com/sql-server-lag-and-lead-functions/" aria-label="Read more about SQL Server LAG and LEAD Functions">Read more</a>]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">A sales dashboard shows the wrong month-over-month change even though its totals look correct. The reporting query compares one customer’s revenue with another customer’s previous row. Meanwhile, a separate batch process uses a loop to calculate gaps between orders.</p>



<p class="wp-block-paragraph"><strong>SQL Server LAG and LEAD Functions</strong> solve adjacent-row comparisons without requiring a self-join for every calculation. <code>LAG</code> retrieves a value from an earlier row, while <code>LEAD</code> retrieves one from a later row within a defined ordering.</p>



<p class="wp-block-paragraph">You’ll learn how to build reliable comparisons, calculate changes and time gaps, handle missing values, and tune these queries for production reporting.</p>



<h2 class="wp-block-heading">Understand SQL Server LAG and LEAD Functions</h2>



<p class="wp-block-paragraph"><code>LAG</code> and <code>LEAD</code> are window functions. A window function calculates a result across related rows while keeping the individual rows in the output.</p>



<p class="wp-block-paragraph">Unlike <code>GROUP BY</code>, which combines rows into summary groups, these functions let an order remain visible beside its previous or next order value.</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th class="has-text-align-left" data-align="left">Function</th><th class="has-text-align-left" data-align="left">Direction</th><th class="has-text-align-left" data-align="left">Typical use</th></tr></thead><tbody><tr><td><code>LAG</code></td><td>Earlier in the specified order</td><td>Compare current revenue with previous revenue</td></tr><tr><td><code>LEAD</code></td><td>Later in the specified order</td><td>Find the next order date</td></tr><tr><td>Both</td><td>Within an optional partition</td><td>Keep customer or tenant sequences separate</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">“Earlier” and “later” refer to the window ordering, not necessarily chronological time. With descending dates, <code>LAG</code> can retrieve a chronologically newer value.</p>



<p class="wp-block-paragraph">Both functions have been available since SQL Server 2012 and are supported in Azure SQL Database and Azure SQL Managed Instance. Their basic syntax does not require a special Azure service tier.</p>



<pre class="wp-block-preformatted"><code>SELECT<br>    SalesMonth,<br>    Revenue,<br>    LAG(Revenue, 1, NULL) OVER (<br>        ORDER BY SalesMonth<br>    ) AS PreviousRevenue,<br>    LEAD(Revenue, 1, NULL) OVER (<br>        ORDER BY SalesMonth<br>    ) AS NextRevenue<br>FROM (<br>    VALUES<br>        (CONVERT(date, '20260101'), CAST(1000 AS decimal(12,2))),<br>        (CONVERT(date, '20260201'), CAST(1200 AS decimal(12,2))),<br>        (CONVERT(date, '20260301'), CAST(900 AS decimal(12,2)))<br>) AS Sales(SalesMonth, Revenue)<br>ORDER BY SalesMonth;</code></pre>



<p class="wp-block-paragraph">The derived table supplies three monthly records. February shows previous revenue of <code>1000.00</code> and next revenue of <code>900.00</code>. See the screenshot below for reference.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img fetchpriority="high" decoding="async" width="1024" height="620" src="https://sqlserverguides.com/wp-content/uploads/2026/11/SQL-Server-LAG-and-LEAD-Functions-1024x620.jpg" alt="SQL Server LAG and LEAD Functions" class="wp-image-24145" srcset="https://sqlserverguides.com/wp-content/uploads/2026/11/SQL-Server-LAG-and-LEAD-Functions-1024x620.jpg 1024w, https://sqlserverguides.com/wp-content/uploads/2026/11/SQL-Server-LAG-and-LEAD-Functions-300x182.jpg 300w, https://sqlserverguides.com/wp-content/uploads/2026/11/SQL-Server-LAG-and-LEAD-Functions-768x465.jpg 768w, https://sqlserverguides.com/wp-content/uploads/2026/11/SQL-Server-LAG-and-LEAD-Functions.jpg 1255w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p class="wp-block-paragraph">For broader context, review these <a rel="noopener" target="_blank" href="https://sqlserverguides.com/window-functions-in-sql-server/">SQL Server window function examples</a>.</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">Pro Tip: I start with three hand-checked rows before expanding a window query. That makes an incorrect direction or partition obvious.</p>
</blockquote>



<h3 class="wp-block-heading">Read the Syntax Before Building the Report</h3>



<p class="wp-block-paragraph">The basic expression is:</p>



<pre class="wp-block-preformatted"><code>LAG(ValueExpression, Offset, DefaultValue)<br>    OVER (<br>        PARTITION BY GroupingColumn<br>        ORDER BY SequencingColumn<br>    )</code></pre>



<p class="wp-block-paragraph">Use <code>LEAD</code> with the same structure when looking forward.</p>



<p class="wp-block-paragraph">Each component has a specific role:</p>



<ul class="wp-block-list">
<li><code>ValueExpression</code> identifies the value to retrieve.</li>



<li><code>Offset</code> specifies how many rows to move; its default is <code>1</code>.</li>



<li><code>DefaultValue</code> applies when the requested row is outside the partition.</li>



<li><code>PARTITION BY</code> separates independent sequences.</li>



<li><code>ORDER BY</code> defines the sequence within each partition.</li>
</ul>



<p class="wp-block-paragraph">The default must be compatible with the value’s data type. For example, use a decimal-compatible default for revenue, not a label such as <code>'No previous sale'</code>. The window <code>ORDER BY</code> is required.</p>



<p class="wp-block-paragraph">An offset counts rows, not days or months. <code>LAG(Revenue, 12)</code> means twelve rows earlier; it means twelve months earlier only when the data contains exactly one row for every month.</p>



<p class="wp-block-paragraph">The window ordering also does not guarantee the final display order. Add an outer <code>ORDER BY</code> for predictable report output.</p>



<p class="wp-block-paragraph">See this <a rel="noopener" target="_blank" href="https://sqlserverguides.com/sql-over-clause/">OVER clause guide</a> for how partitioning and ordering work together.</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">Pro Tip: I document the row grain before choosing an offset. “One row per customer per calendar month” is a useful contract; “monthly data” leaves too much room for mistakes.</p>
</blockquote>



<h3 class="wp-block-heading">Prepare a Reusable Customer Revenue Dataset</h3>



<p class="wp-block-paragraph">The following examples use a local temporary table. Its <code>#</code> prefix makes it session-local, and SQL Server stores it in <code>tempdb</code>, the system database used for temporary work.</p>



<p class="wp-block-paragraph">Run the setup once in a development connection:</p>



<pre class="wp-block-preformatted"><code>CREATE TABLE <em>CustomerRevenue</em><br>(<br>    CustomerId int NOT NULL,<br>    SalesMonth date NOT NULL,<br>    Revenue decimal(12,2) NULL,<br>    PRIMARY KEY CLUSTERED (CustomerId, SalesMonth)<br>);<br><br>INSERT INTO <em>CustomerRevenue</em><br>    (CustomerId, SalesMonth, Revenue)<br>VALUES<br>    (101, '20260101', 1000.00),<br>    (101, '20260201', 1200.00),<br>    (101, '20260301', NULL),<br>    (101, '20260401', 1500.00),<br>    (102, '20260101', 800.00),<br>    (102, '20260201', 1000.00),<br>    (102, '20260301', 900.00);</code></pre>



<p class="wp-block-paragraph">The primary key prevents duplicate customer-month combinations. Its clustered index organizes the rowstore table by customer and month, matching the sequence used below.</p>



<p class="wp-block-paragraph"><code>decimal(12,2)</code> stores exact decimal amounts, avoiding approximate floating-point arithmetic for this revenue example. NULL revenue deliberately represents an unknown value, not zero sales.</p>



<p class="wp-block-paragraph">This design establishes a clear grain: one row per customer per month. If the source contains individual orders, aggregate them to that grain before calculating monthly comparisons.</p>



<p class="wp-block-paragraph">For setup variations, see this guide to <a rel="noopener" target="_blank" href="https://sqlserverguides.com/temp-table-in-sql-server/">creating temporary tables in SQL Server</a>.</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">Pro Tip: I enforce the intended reporting grain with a key whenever possible. Duplicate periods can produce believable but incorrect comparisons.</p>
</blockquote>



<h3 class="wp-block-heading">Use SQL Server LAG and LEAD Functions by Customer</h3>



<p class="wp-block-paragraph">Without partitioning, the last row for customer 101 could become the previous row for customer 102. That is a calculation error, even when the query executes successfully.</p>



<pre class="wp-block-preformatted"><code>SELECT<br>    CustomerId,<br>    SalesMonth,<br>    Revenue,<br>    LAG(Revenue) OVER (<br>        PARTITION BY CustomerId<br>        ORDER BY SalesMonth<br>    ) AS PreviousRevenue,<br>    LEAD(Revenue) OVER (<br>        PARTITION BY CustomerId<br>        ORDER BY SalesMonth<br>    ) AS NextRevenue<br>FROM <em>CustomerRevenue</em><br>ORDER BY CustomerId, SalesMonth;</code></pre>



<p class="wp-block-paragraph">After executing the above query, I got the expected output as shown in the screenshot below.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img decoding="async" width="702" height="633" src="https://sqlserverguides.com/wp-content/uploads/2026/11/LAG-and-LEAD-Functions-SQL.jpg" alt="LAG and LEAD Functions SQL" class="wp-image-24148" srcset="https://sqlserverguides.com/wp-content/uploads/2026/11/LAG-and-LEAD-Functions-SQL.jpg 702w, https://sqlserverguides.com/wp-content/uploads/2026/11/LAG-and-LEAD-Functions-SQL-300x271.jpg 300w" sizes="(max-width: 702px) 100vw, 702px" /></figure>
</div>


<p class="wp-block-paragraph"><code>PARTITION BY CustomerId</code> restarts the comparison for each customer. The first row in each partition has no previous row; the last has no next row.</p>



<p class="wp-block-paragraph">Customer 101’s February row returns:</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th class="has-text-align-left" data-align="left">Revenue</th><th class="has-text-align-left" data-align="left">PreviousRevenue</th><th class="has-text-align-left" data-align="left">NextRevenue</th></tr></thead><tbody><tr><td>1200.00</td><td>1000.00</td><td>NULL</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">Here, the next row exists, but its revenue is NULL. That differs from the final row, where no next row exists.</p>



<p class="wp-block-paragraph">For event-level data, dates alone may not provide a unique sequence. Use a meaningful tie-breaker such as <code>ORDER BY EventTime, EventId</code>. A unique identifier makes ordering repeatable, but the application must still define what simultaneous events mean.</p>



<p class="wp-block-paragraph">Window partitioning is logical query grouping, not physical table partitioning and not a security boundary. Learn more in this <a rel="noopener" target="_blank" href="https://sqlserverguides.com/sql-partition-by/">PARTITION BY tutorial</a>.</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">Pro Tip: I test two customers together before approving a report. A single-customer test cannot expose a missing partition.</p>
</blockquote>



<h3 class="wp-block-heading">Calculate Revenue Changes and Filter Correctly</h3>



<p class="wp-block-paragraph">A common requirement is the amount and percentage change from the previous period.</p>



<p class="wp-block-paragraph">Use a common table expression, or CTE, to name the intermediate query result:</p>



<pre class="wp-block-preformatted"><code>WITH RevenueHistory AS<br>(<br>    SELECT<br>        CustomerId,<br>        SalesMonth,<br>        Revenue,<br>        LAG(Revenue) OVER (<br>            PARTITION BY CustomerId<br>            ORDER BY SalesMonth<br>        ) AS PreviousRevenue<br>    FROM <em>CustomerRevenue</em><br>)<br>SELECT<br>    CustomerId,<br>    SalesMonth,<br>    Revenue,<br>    PreviousRevenue,<br>    Revenue - PreviousRevenue AS RevenueChange,<br>    CAST(<br>        100.0 * (Revenue - PreviousRevenue)<br>        / NULLIF(PreviousRevenue, 0)<br>        AS decimal(12,2)<br>    ) AS PercentageChange<br>FROM RevenueHistory<br>WHERE SalesMonth >= '20260201'<br>ORDER BY CustomerId, SalesMonth;</code></pre>



<p class="wp-block-paragraph">For customer 101 in February, the increase is <code>200.00</code>, or <code>20.00%</code>. See the screenshot below for reference.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img decoding="async" width="772" height="799" src="https://sqlserverguides.com/wp-content/uploads/2026/11/LAG-and-LEAD-Functions-in-SQL.jpg" alt="LAG and LEAD Functions in SQL" class="wp-image-24149" srcset="https://sqlserverguides.com/wp-content/uploads/2026/11/LAG-and-LEAD-Functions-in-SQL.jpg 772w, https://sqlserverguides.com/wp-content/uploads/2026/11/LAG-and-LEAD-Functions-in-SQL-290x300.jpg 290w, https://sqlserverguides.com/wp-content/uploads/2026/11/LAG-and-LEAD-Functions-in-SQL-767x794.jpg 767w" sizes="(max-width: 772px) 100vw, 772px" /></figure>
</div>


<p class="wp-block-paragraph"><code>NULLIF(PreviousRevenue, 0)</code> converts a zero denominator to NULL, preventing division by zero. This reports an undefined percentage as NULL rather than inventing a percentage.</p>



<p class="wp-block-paragraph">The filter belongs outside the CTE because January is needed to calculate February’s previous value. Filtering January out before <code>LAG</code> runs removes that comparison row.</p>



<p class="wp-block-paragraph">A CTE does not automatically materialize or cache results. Its purpose here is calculation structure. Review this <a rel="noopener" target="_blank" href="https://sqlserverguides.com/sql-server-cte-vs-temp-table/">CTE versus temporary table comparison</a> when intermediate results need reuse.</p>



<p class="wp-block-paragraph">For missing calendar periods, first join to a calendar table or otherwise generate the required periods. <code>LAG</code> cannot create a missing month.</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">Pro Tip: I check the first displayed reporting period against the preceding source period. Incorrect filter placement often shows up only at that boundary.</p>
</blockquote>



<h3 class="wp-block-heading">Handle Defaults and IGNORE NULLS Deliberately</h3>



<p class="wp-block-paragraph">The third argument is a boundary default, not a replacement for every NULL value.</p>



<pre class="wp-block-preformatted"><code>SELECT<br>    CustomerId,<br>    SalesMonth,<br>    Revenue,<br>    LAG(Revenue, 1, 0.00) OVER (<br>        PARTITION BY CustomerId<br>        ORDER BY SalesMonth<br>    ) AS PreviousRevenue<br>FROM <em>CustomerRevenue</em><br>WHERE CustomerId = 101<br>ORDER BY SalesMonth;</code></pre>



<p class="wp-block-paragraph">January returns <code>0.00</code> because no previous row exists. April still returns NULL because March exists and contains NULL revenue.<a rel="noopener" target="_blank" href="https://learn.microsoft.com/en-us/sql/t-sql/functions/lag-transact-sql?view=sql-server-ver17"></a></p>



<p class="wp-block-paragraph">Replacing both cases with zero can distort growth rates. Preserve unknown values unless the business explicitly defines them as zero.</p>



<h3 class="wp-block-heading">Skip missing observations when appropriate</h3>



<p class="wp-block-paragraph">SQL Server 2022 and supported Azure SQL platforms provide <code>IGNORE NULLS</code>. Run the following only on a supporting version:</p>



<pre class="wp-block-preformatted"><code>SELECT<br>    CustomerId,<br>    SalesMonth,<br>    Revenue,<br>    LAG(Revenue) IGNORE NULLS OVER (<br>        PARTITION BY CustomerId<br>        ORDER BY SalesMonth<br>    ) AS PreviousKnownRevenue<br>FROM <em>CustomerRevenue</em><br>WHERE CustomerId = 101<br>ORDER BY SalesMonth;</code></pre>



<p class="wp-block-paragraph">April returns February’s <code>1200.00</code>, skipping March’s NULL. This is the previous known observation, not the previous calendar month.</p>



<p class="wp-block-paragraph">Without the option, the default behavior respects NULLs. SQL Server 2022 CU4 included a fix involving <code>IGNORE NULLS</code> with <code>LAG</code> and <code>LEAD</code>; use an appropriately patched, supported build and regression-test the behavior.</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">Pro Tip: I name this output <code>PreviousKnownRevenue</code>, not <code>PreviousMonthRevenue</code>. The name should reveal that the query can skip periods.</p>
</blockquote>



<h3 class="wp-block-heading">Use LEAD to Measure Time Between Events</h3>



<p class="wp-block-paragraph"><code>LEAD</code> also helps analyze order gaps, equipment readings, and workflow transitions.</p>



<pre class="wp-block-preformatted"><code>WITH OrderEvents AS<br>(<br>    SELECT *<br>    FROM (<br>        VALUES<br>            (101, 1, CONVERT(datetime2(0), '2026-01-10T09:00:00')),<br>            (101, 2, CONVERT(datetime2(0), '2026-01-10T11:30:00')),<br>            (101, 3, CONVERT(datetime2(0), '2026-01-11T08:00:00'))<br>    ) AS Sample(CustomerId, OrderId, OrderTime)<br>),<br>OrderedEvents AS<br>(<br>    SELECT<br>        CustomerId,<br>        OrderId,<br>        OrderTime,<br>        LEAD(OrderTime) OVER (<br>            PARTITION BY CustomerId<br>            ORDER BY OrderTime, OrderId<br>        ) AS NextOrderTime<br>    FROM OrderEvents<br>)<br>SELECT<br>    CustomerId,<br>    OrderId,<br>    OrderTime,<br>    NextOrderTime,<br>    DATEDIFF_BIG(SECOND, OrderTime, NextOrderTime)<br>        AS SecondsUntilNextOrder<br>FROM OrderedEvents<br>ORDER BY CustomerId, OrderTime, OrderId;</code></pre>



<p class="wp-block-paragraph">The first gap is <code>9000</code> seconds. The final row returns NULL because no next order exists.</p>



<p class="wp-block-paragraph"><code>DATEDIFF_BIG</code> counts date-part boundaries and returns <code>bigint</code>. The whole-second sample avoids implying fractional-second precision. For finer timing, choose the required date part and timestamp precision deliberately.</p>



<p class="wp-block-paragraph">Store event times consistently, commonly in UTC, and handle local display conversion separately. For status histories, an interval between events measures time in a status only if the history captures every relevant transition.</p>



<p class="wp-block-paragraph">See this <a rel="noopener" target="_blank" href="https://sqlserverguides.com/datediff-function-in-sql-server/">DATEDIFF function guide</a> for date-difference fundamentals.</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">Pro Tip: I retain the event timestamps beside calculated durations during testing. That makes timezone mistakes and unexpected sequencing much easier to diagnose.</p>
</blockquote>



<h3 class="wp-block-heading">Frequently Asked Questions</h3>



<h4 class="wp-block-heading">What is the difference between LAG and LEAD in SQL Server?</h4>



<p class="wp-block-paragraph"><code>LAG</code> retrieves a value from an earlier row in the window order. <code>LEAD</code> retrieves a value from a later row, and both operate within the specified partition.</p>



<h4 class="wp-block-heading">Can I use LAG without ORDER BY?</h4>



<p class="wp-block-paragraph">No. Its window requires <code>ORDER BY</code> to define the sequence. Use an additional unique ordering column when dates or timestamps can tie.</p>



<h4 class="wp-block-heading">Does LAG return the previous month?</h4>



<p class="wp-block-paragraph">Not automatically. It returns an earlier row, so missing months change the meaning. Generate a complete monthly sequence when the requirement is a calendar-period comparison.</p>



<h4 class="wp-block-heading">Can I filter directly on a LAG result in WHERE?</h4>



<p class="wp-block-paragraph">Not in the same query level where the window result is calculated. Compute it in a CTE or derived table, then apply the filter outside.</p>



<h4 class="wp-block-heading">Does the default value replace NULL revenue?</h4>



<p class="wp-block-paragraph">No. It applies when the requested offset is outside the partition. Use explicit NULL-handling logic or supported <code>IGNORE NULLS</code> behavior when the business requirement calls for it.<a rel="noopener" target="_blank" href="https://learn.microsoft.com/en-us/sql/t-sql/functions/lag-transact-sql?view=sql-server-ver17"></a></p>



<p class="wp-block-paragraph">You May Also Like</p>



<ul class="wp-block-list">
<li><a href="https://sqlserverguides.com/row_number-function-in-sql-server/" target="_blank" rel="noopener">Use ROW_NUMBER to sequence SQL Server results</a></li>



<li><a href="https://sqlserverguides.com/sql-last-value/" target="_blank" rel="noopener">Understand SQL Server LAST_VALUE</a></li>



<li><a href="https://sqlserverguides.com/sql-rank-vs-dense-rank/" target="_blank" rel="noopener">Compare RANK and DENSE_RANK</a></li>



<li><a href="https://sqlserverguides.com/sql-query-optimization-tips/" target="_blank" rel="noopener">Improve SQL Server query performance</a></li>



<li><a href="https://sqlserverguides.com/sql-server-permissions/" target="_blank" rel="noopener">Review SQL Server database permissions</a></li>
</ul>



<p class="wp-block-paragraph"><code>LAG</code> and <code>LEAD</code> let you compare neighboring rows, calculate changes, and measure event gaps without writing repetitive lookup logic. Reliable results depend on correct row grain, ordering, partition boundaries, and tested NULL handling—not just valid syntax. I hope you found this article helpful.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>SQL Server CHARINDEX vs PATINDEX</title>
		<link>https://sqlserverguides.com/sql-server-charindex-vs-patindex/</link>
		
		<dc:creator><![CDATA[Bijay Kumar Sahoo]]></dc:creator>
		<pubDate>Mon, 16 Nov 2026 10:41:37 +0000</pubDate>
				<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[SQL Server CHARINDEX vs PATINDEX]]></category>
		<guid isPermaLink="false">https://sqlserverguides.com/?p=24137</guid>

					<description><![CDATA[The main difference in SQL Server CHARINDEX vs PATINDEX is straightforward: CHARINDEX finds a literal substring, while PATINDEX finds a wildcard pattern. Both return a starting position, but only CHARINDEX accepts a starting search location. You’ll learn how to choose the right function, extract values safely, handle NULLs and collations, and keep string searches from ... <a title="SQL Server CHARINDEX vs PATINDEX" class="read-more" href="https://sqlserverguides.com/sql-server-charindex-vs-patindex/" aria-label="Read more about SQL Server CHARINDEX vs PATINDEX">Read more</a>]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">The main difference in <strong>SQL Server CHARINDEX vs PATINDEX</strong> is straightforward: <code>CHARINDEX</code> finds a literal substring, while <code>PATINDEX</code> finds a wildcard pattern. Both return a starting position, but only <code>CHARINDEX</code> accepts a starting search location.</p>



<p class="wp-block-paragraph">You’ll learn how to choose the right function, extract values safely, handle NULLs and collations, and keep string searches from becoming a production bottleneck.</p>



<h2 class="wp-block-heading">SQL Server CHARINDEX vs PATINDEX: Key Differences</h2>



<p class="wp-block-paragraph">Use <code>CHARINDEX</code> when you know the text or delimiter you need. Use <code>PATINDEX</code> when you need to locate a character class or a flexible pattern.</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th class="has-text-align-left" data-align="left">Feature</th><th class="has-text-align-left" data-align="left">CHARINDEX</th><th class="has-text-align-left" data-align="left">PATINDEX</th></tr></thead><tbody><tr><td>Search type</td><td>Literal substring</td><td>Wildcard pattern</td></tr><tr><td>Example</td><td>Find <code>@</code> in an address</td><td>Find the first digit</td></tr><tr><td>Optional starting position</td><td>Yes</td><td>No</td></tr><tr><td>Position numbering</td><td>Starts at 1</td><td>Starts at 1</td></tr><tr><td>No match</td><td>Returns 0</td><td>Returns 0</td></tr><tr><td>Case sensitivity</td><td>Controlled by collation</td><td>Controlled by collation</td></tr><tr><td>Search argument limit</td><td>8,000 characters</td><td>8,000 characters</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">The 8,000-character limit applies to the search text or pattern, not automatically to the entire searched value. Both functions support searching large string values, with return types depending on the searched data type.</p>



<p class="wp-block-paragraph">These functions are available in SQL Server, Azure SQL Database, and Azure SQL Managed Instance. Neither requires moving an existing database to a different hosting model.</p>



<p class="wp-block-paragraph">A position is useful when another expression needs to extract or inspect text. If the requirement is simply “does this value start with this prefix,” <code>LIKE</code> may express the requirement more clearly.</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">Pro Tip: I choose the function by writing the requirement in plain English first. “Find this exact text” points to CHARINDEX; “find a character matching this rule” points to PATINDEX.</p>
</blockquote>



<h3 class="wp-block-heading">Find Literal Text With CHARINDEX</h3>



<p class="wp-block-paragraph">The syntax places the search text first and the value being searched second:</p>



<pre class="wp-block-preformatted"><code>SELECT CHARINDEX('INV-', 'Payment received for INV-2048')<br>    AS InvoicePosition;</code></pre>



<p class="wp-block-paragraph">The result is <code>22</code>. <code>CHARINDEX</code> locates the first character of <code>INV-</code>, counting from 1. Checkout the screenshot below for your reference.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="188" src="https://sqlserverguides.com/wp-content/uploads/2026/11/SQL-Server-CHARINDEX-vs-PATINDEX-1024x188.jpg" alt="SQL Server CHARINDEX vs PATINDEX" class="wp-image-24138" srcset="https://sqlserverguides.com/wp-content/uploads/2026/11/SQL-Server-CHARINDEX-vs-PATINDEX-1024x188.jpg 1024w, https://sqlserverguides.com/wp-content/uploads/2026/11/SQL-Server-CHARINDEX-vs-PATINDEX-300x55.jpg 300w, https://sqlserverguides.com/wp-content/uploads/2026/11/SQL-Server-CHARINDEX-vs-PATINDEX-768x141.jpg 768w, https://sqlserverguides.com/wp-content/uploads/2026/11/SQL-Server-CHARINDEX-vs-PATINDEX.jpg 1116w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p class="wp-block-paragraph">Reversing the arguments is a common mistake. Searching for the entire payment message inside <code>INV-</code> returns no match.</p>



<h3 class="wp-block-heading">Search from a specific position</h3>



<p class="wp-block-paragraph">The optional third argument helps locate repeated delimiters:</p>



<pre class="wp-block-preformatted"><code>DECLARE @OrderReference varchar(50) = 'US-WEST-2048';<br><br>DECLARE @FirstDash int =<br>    CHARINDEX('-', @OrderReference);<br><br>DECLARE @SecondDash int =<br>    CASE<br>        WHEN @FirstDash > 0<br>        THEN CHARINDEX('-', @OrderReference, @FirstDash + 1)<br>        ELSE 0<br>    END;<br><br>SELECT<br>    @FirstDash AS FirstDashPosition,<br>    @SecondDash AS SecondDashPosition;</code></pre>



<p class="wp-block-paragraph">The results are <code>3</code> and <code>8</code>. The second search begins after the first dash, but its result remains a position within the original string. I got the expected output as shown in the screenshot below.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="600" src="https://sqlserverguides.com/wp-content/uploads/2026/11/sql-charindex-vs-patindex-1024x600.jpg" alt="sql charindex vs patindex" class="wp-image-24139" srcset="https://sqlserverguides.com/wp-content/uploads/2026/11/sql-charindex-vs-patindex-1024x600.jpg 1024w, https://sqlserverguides.com/wp-content/uploads/2026/11/sql-charindex-vs-patindex-300x176.jpg 300w, https://sqlserverguides.com/wp-content/uploads/2026/11/sql-charindex-vs-patindex-768x450.jpg 768w, https://sqlserverguides.com/wp-content/uploads/2026/11/sql-charindex-vs-patindex.jpg 1181w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p class="wp-block-paragraph">The guard matters: if the first dash is missing, blindly adding 1 to its result starts another search at position 1. That can hide malformed input.</p>



<p class="wp-block-paragraph">A missing, zero, or negative starting location makes <code>CHARINDEX</code> search from the beginning. It does not search backward.<a rel="noopener" target="_blank" href="https://learn.microsoft.com/en-us/sql/t-sql/functions/charindex-transact-sql?view=sql-server-ver17"></a></p>



<h4 class="wp-block-heading">Wildcards remain literal</h4>



<pre class="wp-block-preformatted"><code>SELECT<br>    CHARINDEX('_', 'SKU_A100') AS UnderscorePosition,<br>    CHARINDEX('%', 'Discount 10%') AS PercentPosition;</code></pre>



<p class="wp-block-paragraph">The results are <code>4</code> and <code>12</code>. No wildcard escaping is needed because <code>CHARINDEX</code> treats these characters literally. I got the expected output as shown in the screenshot below.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="225" src="https://sqlserverguides.com/wp-content/uploads/2026/11/sql-server-charindex-vs-patindex-performance-1024x225.jpg" alt="sql server charindex vs patindex performance" class="wp-image-24140" srcset="https://sqlserverguides.com/wp-content/uploads/2026/11/sql-server-charindex-vs-patindex-performance-1024x225.jpg 1024w, https://sqlserverguides.com/wp-content/uploads/2026/11/sql-server-charindex-vs-patindex-performance-300x66.jpg 300w, https://sqlserverguides.com/wp-content/uploads/2026/11/sql-server-charindex-vs-patindex-performance-765x168.jpg 765w, https://sqlserverguides.com/wp-content/uploads/2026/11/sql-server-charindex-vs-patindex-performance.jpg 1079w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p class="wp-block-paragraph">For additional delimiter examples, see this <a rel="noopener" target="_blank" href="https://sqlserverguides.com/charindex-function-in-sql-server/">CHARINDEX function guide</a>.</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">Pro Tip: I use CHARINDEX for fixed separators such as <code>@</code>, <code>|</code>, and <code>-</code>. Literal searching makes the code easier to review and avoids accidental wildcard behavior.</p>
</blockquote>



<h3 class="wp-block-heading">Find Patterns With PATINDEX</h3>



<p class="wp-block-paragraph"><code>PATINDEX</code> uses wildcard syntax similar to <code>LIKE</code>, but returns a position instead of a true-or-false match condition. It is not a regular-expression engine.<a rel="noopener" target="_blank" href="https://learn.microsoft.com/en-us/sql/t-sql/functions/patindex-transact-sql?view=sql-server-ver17"></a></p>



<p class="wp-block-paragraph">Common pattern elements include:</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th class="has-text-align-left" data-align="left">Pattern</th><th class="has-text-align-left" data-align="left">Meaning</th></tr></thead><tbody><tr><td><code>%</code></td><td>Zero or more characters</td></tr><tr><td><code>_</code></td><td>Exactly one character</td></tr><tr><td><code>[0-9]</code></td><td>One character in the specified range</td></tr><tr><td><code>[ABC]</code></td><td>One character from the listed set</td></tr><tr><td><code>[^0-9]</code></td><td>One character outside the specified range</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">For an anywhere-in-the-string search, surround the meaningful pattern with <code>%</code>:</p>



<pre class="wp-block-preformatted"><code>SELECT<br>    PATINDEX('%[0-9]%', 'Order AB123 shipped')<br>        AS FirstDigitPosition,<br>    PATINDEX('%[^0-9]%', '123A45')<br>        AS FirstNonDigitPosition;</code></pre>



<p class="wp-block-paragraph">The results are <code>9</code> and <code>4</code>. The second expression is useful when a supplier sends supposedly numeric identifiers containing letters.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="945" height="315" src="https://sqlserverguides.com/wp-content/uploads/2026/11/charindex-vs-patindex-in-sql-server.jpg" alt="charindex vs patindex in sql server" class="wp-image-24141" srcset="https://sqlserverguides.com/wp-content/uploads/2026/11/charindex-vs-patindex-in-sql-server.jpg 945w, https://sqlserverguides.com/wp-content/uploads/2026/11/charindex-vs-patindex-in-sql-server-768x256.jpg 768w, https://sqlserverguides.com/wp-content/uploads/2026/11/charindex-vs-patindex-in-sql-server-300x100.jpg 300w" sizes="auto, (max-width: 945px) 100vw, 945px" /></figure>
</div>


<p class="wp-block-paragraph">Ranges and comparisons can depend on collation. For strict machine-readable rules, define the intended character set and test it under an appropriate collation.</p>



<h3 class="wp-block-heading">Locate a flexible substring</h3>



<pre class="wp-block-preformatted"><code>SELECT PATINDEX('%en_ure%', 'Please ensure the door is locked!')<br>    AS PatternPosition;</code></pre>



<p class="wp-block-paragraph">The result is <code>8</code>. The underscore matches one character between <code>en</code> and <code>ure</code>.</p>



<p class="wp-block-paragraph">Patterns do not always need surrounding percent signs. For example, <code>PATINDEX('INV%', 'INV-2048')</code> returns <code>1</code>, while the same pattern does not match <code>Paid INV-2048</code>, because it requires the value to begin with <code>INV</code>.</p>



<p class="wp-block-paragraph">Learn more about these operators in the <a rel="noopener" target="_blank" href="https://sqlserverguides.com/sql-wildcard-characters/">SQL wildcard character guide</a>.</p>



<h3 class="wp-block-heading">Search for literal wildcard characters</h3>



<pre class="wp-block-preformatted"><code>SELECT<br>    PATINDEX('%[_]%', 'SKU_A100') AS UnderscorePosition,<br>    PATINDEX('%[%]%', 'Discount 10%') AS PercentPosition,<br>    PATINDEX('%[[]%', 'Item[Blue]') AS BracketPosition;</code></pre>



<p class="wp-block-paragraph">Bracket expressions make <code>_</code>, <code>%</code>, and <code>[</code> literal in these examples. Without that treatment, the first two characters would retain their wildcard meanings.</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">Pro Tip: I test wildcard patterns against both expected matches and near misses. A pattern that finds the right row can still be wrong if it also accepts dozens of invalid values.</p>
</blockquote>



<h3 class="wp-block-heading">SQL Server CHARINDEX vs PATINDEX for Data Validation</h3>



<p class="wp-block-paragraph">Consider an order-processing API receiving account codes from several vendors. The business rule permits only uppercase ASCII letters, digits, and hyphens.</p>



<p class="wp-block-paragraph">A set-based query checks all sample rows together rather than using a row-by-row loop:</p>



<pre class="wp-block-preformatted"><code>DECLARE @IncomingAccounts TABLE<br>(<br>    AccountId int,<br>    AccountCode varchar(30) NULL<br>);<br><br>INSERT INTO @IncomingAccounts (AccountId, AccountCode)<br>VALUES<br>    (1, 'AC-2048'),<br>    (2, 'AC_2048'),<br>    (3, ''),<br>    (4, NULL),<br>    (5, 'ac-2048');<br><br>SELECT<br>    AccountId,<br>    AccountCode,<br>    CASE<br>        WHEN AccountCode IS NULL THEN 'Missing'<br>        WHEN DATALENGTH(AccountCode) = 0 THEN 'Empty'<br>        WHEN PATINDEX(<br>            '%[^A-Z0-9-]%',<br>            COALESCE(AccountCode, '')<br>                COLLATE Latin1_General_100_BIN2<br>        ) > 0 THEN 'Invalid characters'<br>        ELSE 'Valid'<br>    END AS ValidationStatus<br>FROM @IncomingAccounts;</code></pre>



<p class="wp-block-paragraph">The first code is valid. The underscore and lowercase letters are invalid; empty and missing values receive separate statuses.</p>



<p class="wp-block-paragraph"><code>COLLATE</code> applies comparison rules to an expression. The binary collation makes the intended ASCII ranges explicit rather than relying on a database’s linguistic sorting behavior.</p>



<p class="wp-block-paragraph"><code>COALESCE</code> supplies a non-NULL search expression to <code>PATINDEX</code>. The separate NULL branch still preserves the difference between “missing” and “contains no invalid characters.”</p>



<p class="wp-block-paragraph">This example checks allowed characters, not the complete account-code format. It still accepts values such as <code>---</code>. Add separate rules for structure, length, or required prefixes.</p>



<p class="wp-block-paragraph">For permanent enforcement, consider a <code>CHECK</code> constraint—a rule evaluated when data changes. Pair it with <code>NOT NULL</code> where values are mandatory, and test existing records before deployment. See these <a rel="noopener" target="_blank" href="https://sqlserverguides.com/sql-constraints/">SQL constraint fundamentals</a>.</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">Pro Tip: I return separate validation reasons instead of one “bad data” flag. Support teams can fix a missing value much faster when it is not mixed with character-format errors.</p>
</blockquote>



<h3 class="wp-block-heading">Extract Values Without Invalid-Length Errors</h3>



<p class="wp-block-paragraph">String searching often feeds <code>LEFT</code> or <code>SUBSTRING</code>. The danger appears when no delimiter exists.</p>



<p class="wp-block-paragraph">An expression such as <code>LEFT(EmailAddress, CHARINDEX('@', EmailAddress) - 1)</code> can produce a negative length when <code>CHARINDEX</code> returns zero.</p>



<p class="wp-block-paragraph">Use a guarded expression:</p>



<pre class="wp-block-preformatted"><code>DECLARE @EmailAddress nvarchar(200) = N'alex@example.test';<br><br>DECLARE @AtPosition int =<br>    CHARINDEX(N'@', @EmailAddress);<br><br>SELECT<br>    CASE<br>        WHEN @AtPosition > 1<br>        THEN LEFT(<br>            @EmailAddress,<br>            CASE<br>                WHEN @AtPosition > 1 THEN @AtPosition - 1<br>                ELSE 0<br>            END<br>        )<br>        ELSE NULL<br>    END AS LocalPart;</code></pre>



<p class="wp-block-paragraph">The result is <code>alex</code>. The inner length expression remains nonnegative, while the outer condition returns NULL for missing delimiters or an empty local part.</p>



<p class="wp-block-paragraph">This is extraction, not complete email validation. It does not establish that the domain exists or that the address meets every email-format rule.</p>



<h3 class="wp-block-heading">Simulate a starting location for PATINDEX</h3>



<p class="wp-block-paragraph"><code>PATINDEX</code> has no third parameter. Search a substring, then translate the result back into the original position:</p>



<pre class="wp-block-preformatted"><code>DECLARE @AuditText nvarchar(200) = N'ID=12; CODE=AB7';<br>DECLARE @StartPosition int = 8;<br><br>DECLARE @RelativePosition int =<br>    PATINDEX(<br>        N'%[0-9]%',<br>        SUBSTRING(@AuditText, @StartPosition, 200)<br>    );<br><br>SELECT<br>    CASE<br>        WHEN @RelativePosition > 0<br>        THEN @StartPosition + @RelativePosition - 1<br>        ELSE 0<br>    END AS OriginalPosition;</code></pre>



<p class="wp-block-paragraph">The result is <code>14</code>, the location of <code>7</code> in the original text. The conditional preserves zero when no match exists.</p>



<p class="wp-block-paragraph">For extraction options, review the <a rel="noopener" target="_blank" href="https://sqlserverguides.com/substring-function-in-sql-server/">SUBSTRING function tutorial</a>. If the real requirement is splitting many delimited values, consider a dedicated splitting approach instead of nesting repeated searches.</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">Pro Tip: I test extraction with no delimiter, a leading delimiter, repeated delimiters, and NULL. Happy-path examples rarely expose the invalid-length failures that interrupt imports.</p>
</blockquote>



<h3 class="wp-block-heading">Handle NULLs, Collations, and Unicode Deliberately</h3>



<p class="wp-block-paragraph"><code>CHARINDEX</code> returns NULL when either input is NULL. Current Microsoft documentation distinguishes <code>PATINDEX</code>: a NULL pattern returns NULL, while a NULL searched expression is documented as an error. Older documentation describes different NULL behavior, so avoid depending on implicit handling across versions.</p>



<p class="wp-block-paragraph">For portable defensive code, pass an explicitly normalized expression:</p>



<pre class="wp-block-preformatted"><code>DECLARE @CustomerNote nvarchar(200) = NULL;<br><br>SELECT PATINDEX(<br>    N'%[0-9]%',<br>    COALESCE(@CustomerNote, N'')<br>) AS DigitPosition;</code></pre>



<p class="wp-block-paragraph">This returns <code>0</code>. Use this only when treating missing text as empty fits the business rule; otherwise, preserve a separate missing-value status.</p>



<p class="wp-block-paragraph">Case sensitivity is also explicit, not a built-in difference between the functions:</p>



<pre class="wp-block-preformatted"><code>SELECT<br>    CHARINDEX(<br>        'sql',<br>        'SQL Server' COLLATE Latin1_General_100_CI_AS<br>    ) AS CaseInsensitivePosition,<br>    CHARINDEX(<br>        'sql',<br>        'SQL Server' COLLATE Latin1_General_100_CS_AS<br>    ) AS CaseSensitivePosition;</code></pre>



<p class="wp-block-paragraph">The results are <code>1</code> and <code>0</code>. <code>CI</code> means case-insensitive; <code>CS</code> means case-sensitive. Both functions follow the applicable collation.</p>



<p class="wp-block-paragraph">Use Unicode literals such as <code>N'客户'</code> when searching <code>nvarchar</code> data. Under supplementary-character-aware collations, both functions count UTF-16 surrogate pairs as one character. Positions are not byte offsets, so do not combine them blindly with byte measurements.</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">Pro Tip: I include collation and NULL cases in automated tests. Otherwise, moving the same code into a differently configured database can change results without changing the query text.</p>
</blockquote>



<h3 class="wp-block-heading">Performance, Cost, and Safe Production Testing</h3>



<p class="wp-block-paragraph">Neither function is universally faster. The amount of text examined, row count, filters, data types, and execution plan usually matter more than choosing one function name.</p>



<p class="wp-block-paragraph">A condition such as <code>CHARINDEX('refund', OrderNote) &gt; 0</code> generally cannot seek directly into an ordinary index on <code>OrderNote</code>. A seek navigates to a selective index range; an anywhere-substring search commonly needs a scan.</p>



<p class="wp-block-paragraph">Replacing it with <code>PATINDEX('%refund%', OrderNote) &gt; 0</code> does not solve that access-path problem.</p>



<p class="wp-block-paragraph">For SQL Server performance tuning:</p>



<ul class="wp-block-list">
<li>Restrict searches by indexed business attributes such as tenant, order date, or processing status.</li>



<li>Use <code>LIKE 'INV-%'</code> for prefix searches when appropriate; suitable indexes and data types can enable a range seek.</li>



<li>Store frequently queried reference numbers in dedicated columns instead of repeatedly parsing notes.</li>



<li>Evaluate full-text search for word-based document searches, not as a drop-in replacement for arbitrary substring matching.</li>
</ul>



<p class="wp-block-paragraph">Inspect actual execution plans and logical reads, which measure data pages accessed through the buffer cache. Query Store retains query plans and runtime history for before-and-after comparison. These <a rel="noopener" target="_blank" href="https://sqlserverguides.com/sql-query-optimization-tips/">SQL query optimization tips</a> provide a broader tuning workflow.</p>



<p class="wp-block-paragraph">On Azure SQL Database, repeated scans can consume purchased CPU and I/O capacity. Tune the search and schema before increasing compute.</p>



<p class="wp-block-paragraph">Run profiling with a non-administrator account and only required <code>SELECT</code> permissions. Keep application and administrator identities separate. Prefer Microsoft Entra authentication and managed identities where supported; protect unavoidable credentials in Azure Key Vault rather than source code or shared files.</p>



<p class="wp-block-paragraph">Require encrypted connections with certificate validation. Verify the current session’s encryption through approved connection diagnostics or the permitted connection DMV, rather than assuming encryption from a successful login.</p>



<p class="wp-block-paragraph">Parameterize application input instead of building dynamic SQL. Parameterization prevents input from becoming SQL syntax, but it does not remove wildcard meaning from a <code>PATINDEX</code> pattern.</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">Pro Tip: I benchmark on production-sized test data before approving a search change. Ten sample rows cannot reveal the scan costs that appear on a busy order-history table.</p>
</blockquote>



<h3 class="wp-block-heading">Frequently Asked Questions</h3>



<h4 class="wp-block-heading">Is PATINDEX a regular-expression function?</h4>



<p class="wp-block-paragraph">No. It supports SQL wildcard patterns such as <code>%</code>, <code>_</code>, and bracket expressions, not regular-expression quantifiers or capture groups. Use it for simple positional pattern matching.<a rel="noopener" target="_blank" href="https://learn.microsoft.com/en-us/sql/t-sql/functions/patindex-transact-sql?view=sql-server-ver17"></a></p>



<h4 class="wp-block-heading">Can CHARINDEX find the second occurrence?</h4>



<p class="wp-block-paragraph">Yes. Find the first occurrence, then start another search after it. Guard the first result so a missing match does not accidentally restart the search.</p>



<h4 class="wp-block-heading">Why does PATINDEX return zero?</h4>



<p class="wp-block-paragraph">Zero means the supplied pattern did not match. Check surrounding <code>%</code> characters, collation, literal wildcard escaping, and whether the data contains the characters you expect.</p>



<h4 class="wp-block-heading">Which is faster, CHARINDEX or PATINDEX?</h4>



<p class="wp-block-paragraph">There is no universal winner. Choose correct semantics first, then measure the actual execution plan and workload; scanning millions of rows can outweigh any small scalar-function difference.</p>



<h4 class="wp-block-heading">Can I use these functions in Azure SQL Database?</h4>



<p class="wp-block-paragraph">Yes. Both are supported in Azure SQL Database and Azure SQL Managed Instance. Still test collation, NULL handling, and performance in the target database rather than assuming every environment is configured identically.</p>



<p class="wp-block-paragraph">You May Also Like</p>



<ul class="wp-block-list">
<li><a href="https://sqlserverguides.com/patindex-function-in-sql-server/" target="_blank" rel="noopener">Explore PATINDEX examples in SQL Server</a></li>



<li><a href="https://sqlserverguides.com/sql-server-split-string-into-rows/" target="_blank" rel="noopener">Split a SQL Server string into rows</a></li>



<li><a href="https://sqlserverguides.com/sql-null/" target="_blank" rel="noopener">Understand SQL NULL values</a></li>



<li><a href="https://sqlserverguides.com/sql-indexes-best-practices/" target="_blank" rel="noopener">Apply SQL Server indexing best practices</a></li>



<li><a href="https://sqlserverguides.com/sql-server-permissions/" target="_blank" rel="noopener">Review SQL Server database permissions</a></li>
</ul>



<p class="wp-block-paragraph"><code>CHARINDEX</code> locates literal substrings and supports a starting location, while <code>PATINDEX</code> locates wildcard patterns. Choose the correct matching rules, guard extraction boundaries, and measure search costs before deploying against large tables. I hope you found this article helpful.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>SQL Server LEN vs DATALENGTH</title>
		<link>https://sqlserverguides.com/sql-server-len-vs-datalength/</link>
		
		<dc:creator><![CDATA[Bijay Kumar Sahoo]]></dc:creator>
		<pubDate>Mon, 16 Nov 2026 07:10:57 +0000</pubDate>
				<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[SQL Server LEN vs DATALENGTH]]></category>
		<guid isPermaLink="false">https://sqlserverguides.com/?p=24130</guid>

					<description><![CDATA[SQL Server LEN vs DATALENGTH comes down to what you measure. LEN counts characters but excludes trailing spaces. DATALENGTH counts the bytes representing an expression, including trailing spaces in string values. Unicode encoding and fixed-length data types make that distinction especially important. You’ll learn how to choose the right function, validate incoming data, investigate padding, ... <a title="SQL Server LEN vs DATALENGTH" class="read-more" href="https://sqlserverguides.com/sql-server-len-vs-datalength/" aria-label="Read more about SQL Server LEN vs DATALENGTH">Read more</a>]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph"><strong>SQL Server LEN vs DATALENGTH</strong> comes down to what you measure. <code>LEN</code> counts characters but excludes trailing spaces. <code>DATALENGTH</code> counts the bytes representing an expression, including trailing spaces in string values. Unicode encoding and fixed-length data types make that distinction especially important.</p>



<p class="wp-block-paragraph">You’ll learn how to choose the right function, validate incoming data, investigate padding, and avoid expensive length checks on large tables.</p>



<h2 class="wp-block-heading">SQL Server LEN vs DATALENGTH: The Core Difference</h2>



<p class="wp-block-paragraph">Use <strong>LEN</strong> when the requirement concerns character length, excluding trailing ordinary spaces. Use <strong>DATALENGTH</strong> when the requirement concerns the byte representation of a value. Neither function measures a column’s declared maximum capacity.</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th class="has-text-align-left" data-align="left">Behavior</th><th class="has-text-align-left" data-align="left">LEN</th><th class="has-text-align-left" data-align="left">DATALENGTH</th></tr></thead><tbody><tr><td>Measures</td><td>Characters</td><td>Bytes</td></tr><tr><td>Trailing ordinary spaces</td><td>Excluded</td><td>Included</td></tr><tr><td>Leading and internal spaces</td><td>Counted</td><td>Included in byte count</td></tr><tr><td>Unicode strings</td><td>Character count depends on collation rules</td><td>Bytes depend on encoding</td></tr><tr><td>NULL input</td><td>Returns NULL</td><td>Returns NULL</td></tr><tr><td>Common purpose</td><td>Business validation</td><td>Byte limits and data profiling</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">Both functions work in SQL Server, Azure SQL Database, and Azure SQL Managed Instance. Moving a database to a managed Azure service does not make character length equal byte length.</p>



<p class="wp-block-paragraph">Their syntax is simple:</p>



<pre class="wp-block-preformatted"><code>SELECT<br>    LEN('Order-1001') AS CharacterCount,<br>    DATALENGTH('Order-1001') AS ByteCount;</code></pre>



<p class="wp-block-paragraph">After executing the query above, I got the expected output as shown in the screenshot below.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="873" height="260" src="https://sqlserverguides.com/wp-content/uploads/2026/11/SQL-Server-LEN-vs-DATALENGTH.jpg" alt="" class="wp-image-24131" srcset="https://sqlserverguides.com/wp-content/uploads/2026/11/SQL-Server-LEN-vs-DATALENGTH.jpg 873w, https://sqlserverguides.com/wp-content/uploads/2026/11/SQL-Server-LEN-vs-DATALENGTH-300x89.jpg 300w, https://sqlserverguides.com/wp-content/uploads/2026/11/SQL-Server-LEN-vs-DATALENGTH-766x228.jpg 766w" sizes="auto, (max-width: 873px) 100vw, 873px" /></figure>
</div>


<p class="wp-block-paragraph">Both results are <code>10</code> because the example uses ASCII characters in a <code>varchar</code> literal. That agreement is convenient, but it is not a rule you should build into an international application.</p>



<p class="wp-block-paragraph">For most non-<code>max</code> inputs, these functions return <code>int</code>. For supported large-value types such as <code>varchar(max)</code> and <code>nvarchar(max)</code>, they return <code>bigint</code>.</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">Pro Tip: I label diagnostic columns <code>CharacterCount</code> and <code>ByteCount</code>, not simply <code>Length</code>. Clear units prevent the wrong result from becoming an application rule.</p>
</blockquote>



<h3 class="wp-block-heading">SQL Server LEN vs DATALENGTH With Trailing Spaces</h3>



<p class="wp-block-paragraph">Trailing spaces are ordinary space characters at the end of a string. They commonly arrive through CSV imports, older desktop applications, and fixed-width integrations.</p>



<p class="wp-block-paragraph">Run this read-only example:</p>



<pre class="wp-block-preformatted"><code>DECLARE @CustomerCode varchar(20) = 'ABC   ';<br><br>SELECT<br>    '[' + @CustomerCode + ']' AS VisibleValue,<br>    LEN(@CustomerCode) AS CharacterCount,<br>    DATALENGTH(@CustomerCode) AS ByteCount;</code></pre>



<p class="wp-block-paragraph">The results are: See the screenshot below for reference.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="937" height="361" src="https://sqlserverguides.com/wp-content/uploads/2026/11/sql-server-len-vs-datalength-trailing-spaces.jpg" alt="sql server len vs datalength trailing spaces" class="wp-image-24132" srcset="https://sqlserverguides.com/wp-content/uploads/2026/11/sql-server-len-vs-datalength-trailing-spaces.jpg 937w, https://sqlserverguides.com/wp-content/uploads/2026/11/sql-server-len-vs-datalength-trailing-spaces-300x116.jpg 300w, https://sqlserverguides.com/wp-content/uploads/2026/11/sql-server-len-vs-datalength-trailing-spaces-766x295.jpg 766w" sizes="auto, (max-width: 937px) 100vw, 937px" /></figure>
</div>


<p class="wp-block-paragraph">The brackets expose the spaces in the result grid. <code>LEN</code> excludes the three trailing spaces, while <code>DATALENGTH</code> includes their bytes.<a rel="noopener" target="_blank" href="https://learn.microsoft.com/en-us/sql/t-sql/functions/len-transact-sql?view=sql-server-ver17"></a></p>



<p class="wp-block-paragraph">Leading and internal spaces behave differently:</p>



<pre class="wp-block-preformatted"><code>SELECT<br>    LEN('  A B  ') AS CharacterCount,<br>    DATALENGTH('  A B  ') AS ByteCount;</code></pre>



<p class="wp-block-paragraph">After executing the query above, I got the expected output as shown in the screenshot below.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="817" height="253" src="https://sqlserverguides.com/wp-content/uploads/2026/11/sql-len-vs-datalength.jpg" alt="sql len vs datalength" class="wp-image-24133" srcset="https://sqlserverguides.com/wp-content/uploads/2026/11/sql-len-vs-datalength.jpg 817w, https://sqlserverguides.com/wp-content/uploads/2026/11/sql-len-vs-datalength-765x237.jpg 765w, https://sqlserverguides.com/wp-content/uploads/2026/11/sql-len-vs-datalength-300x93.jpg 300w" sizes="auto, (max-width: 817px) 100vw, 817px" /></figure>
</div>


<p class="wp-block-paragraph">The results are <code>5</code> and <code>7</code>. The leading spaces and the space between <code>A</code> and <code>B</code> count toward <code>LEN</code>; only the final two ordinary spaces are excluded.</p>



<p class="wp-block-paragraph">Do not interpret this as “LEN removes all whitespace.” Tabs, line breaks, and other Unicode whitespace require separate rules.</p>



<h3 class="wp-block-heading">Count characters while preserving trailing spaces</h3>



<p class="wp-block-paragraph">Appending a non-space marker makes the original trailing spaces internal:</p>



<pre class="wp-block-preformatted"><code>DECLARE @CustomerCode varchar(20) = 'ABC   ';<br><br>SELECT<br>    LEN(CAST(@CustomerCode AS varchar(max)) + '#') - 1<br>        AS CharacterCountIncludingTrailingSpaces;</code></pre>



<p class="wp-block-paragraph">The result is <code>6</code>. Casting to <code>varchar(max)</code> prevents ordinary bounded-string concatenation from truncating the appended marker. See the screenshot below for reference.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="305" src="https://sqlserverguides.com/wp-content/uploads/2026/11/len-vs-datalength-sql-server-1024x305.jpg" alt="len vs datalength sql server" class="wp-image-24134" srcset="https://sqlserverguides.com/wp-content/uploads/2026/11/len-vs-datalength-sql-server-1024x305.jpg 1024w, https://sqlserverguides.com/wp-content/uploads/2026/11/len-vs-datalength-sql-server-300x89.jpg 300w, https://sqlserverguides.com/wp-content/uploads/2026/11/len-vs-datalength-sql-server-765x228.jpg 765w, https://sqlserverguides.com/wp-content/uploads/2026/11/len-vs-datalength-sql-server.jpg 1074w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p class="wp-block-paragraph">For <code>nvarchar</code>, use <code>nvarchar(max)</code> and <code>N'#'</code>. This technique preserves SQL Server’s character-counting behavior; it does not turn the result into a count of visual symbols.</p>



<p class="wp-block-paragraph">If spaces should be removed instead, define that cleanup explicitly. This <a rel="noopener" target="_blank" href="https://sqlserverguides.com/trim-function-in-sql-server/">SQL Server TRIM guide</a> explains trimming options.</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">Pro Tip: I display suspicious strings inside brackets before proposing cleanup. Invisible padding is much easier to explain when the team can actually see it.</p>
</blockquote>



<h3 class="wp-block-heading">Understand CHAR, VARCHAR, NCHAR, and NVARCHAR</h3>



<p class="wp-block-paragraph">Data types determine how SQL Server represents values. Choosing the wrong type can create padding, lose characters, or make validation misleading.</p>



<p class="wp-block-paragraph"><code>char</code> and <code>nchar</code> are fixed-length string types. <code>varchar</code> and <code>nvarchar</code> are variable-length types.</p>



<pre class="wp-block-preformatted"><code>DECLARE @FixedCode char(10) = 'ABC';<br>DECLARE @VariableCode varchar(10) = 'ABC';<br>DECLARE @UnicodeCode nvarchar(10) = N'ABC';<br><br>SELECT<br>    LEN(@FixedCode) AS FixedCharacters,<br>    DATALENGTH(@FixedCode) AS FixedBytes,<br>    LEN(@VariableCode) AS VariableCharacters,<br>    DATALENGTH(@VariableCode) AS VariableBytes,<br>    LEN(@UnicodeCode) AS UnicodeCharacters,<br>    DATALENGTH(@UnicodeCode) AS UnicodeBytes;</code></pre>



<p class="wp-block-paragraph">Expected results:</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th class="has-text-align-left" data-align="left">Measurement</th><th class="has-text-align-left" data-align="left">Result</th></tr></thead><tbody><tr><td>FixedCharacters</td><td>3</td></tr><tr><td>FixedBytes</td><td>10</td></tr><tr><td>VariableCharacters</td><td>3</td></tr><tr><td>VariableBytes</td><td>3</td></tr><tr><td>UnicodeCharacters</td><td>3</td></tr><tr><td>UnicodeBytes</td><td>6</td></tr></tbody></table></figure>



<p class="wp-block-paragraph"><code>char(10)</code> pads the value to its fixed width. <code>varchar(10)</code> does not add that padding. The three basic Latin characters in <code>nvarchar</code> use six bytes.</p>



<p class="wp-block-paragraph">The declaration size also matters:</p>



<ul class="wp-block-list">
<li><code>varchar(50)</code> permits up to 50 bytes, not necessarily 50 characters.</li>



<li><code>nvarchar(50)</code> permits 50 byte-pairs, or 100 bytes of string payload.</li>



<li>Some Unicode characters require more than one byte-pair in <code>nvarchar</code>.</li>
</ul>



<p class="wp-block-paragraph">For customer names, variable-length storage usually fits the changing input better than fixed-width padding. Fixed-width codes can justify <code>char</code>, but only when the domain actually requires a fixed width.</p>



<p class="wp-block-paragraph">Also specify lengths explicitly. A declaration such as <code>DECLARE @Code varchar</code> defaults to length <code>1</code>, which can lose data before any later check runs.<a rel="noopener" target="_blank" href="https://learn.microsoft.com/en-us/sql/t-sql/data-types/char-and-varchar-transact-sql?view=sql-server-ver17"></a></p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">Pro Tip: I check the parameter and variable declarations before blaming the table. An undersized intermediate variable can destroy the evidence before the INSERT statement executes.</p>
</blockquote>



<h3 class="wp-block-heading">Unicode, UTF-8, and Collation Change the Results</h3>



<p class="wp-block-paragraph">Unicode represents characters across languages. An encoding determines how those characters become bytes. A collation controls comparison and sorting rules and can also affect encoding and character handling.</p>



<h4 class="wp-block-heading">NVARCHAR is not always two bytes per character</h4>



<p class="wp-block-paragraph">Many commonly used characters occupy two bytes in <code>nvarchar</code>. Supplementary characters use a UTF-16 surrogate pair: two code units occupying four bytes.</p>



<p class="wp-block-paragraph">Under a supplementary-character-aware, or SC, collation, <code>LEN</code> counts a surrogate pair as one character.</p>



<pre class="wp-block-preformatted"><code>DECLARE @SupplementaryCharacter nvarchar(2) =<br>    CONVERT(nvarchar(2), 0x3DD800DE);<br><br>SELECT<br>    LEN(<br>        @SupplementaryCharacter<br>        COLLATE Latin1_General_100_CI_AS_SC<br>    ) AS CharacterCount,<br>    DATALENGTH(@SupplementaryCharacter) AS ByteCount;</code></pre>



<p class="wp-block-paragraph">The results are <code>1</code> and <code>4</code>. The hexadecimal input creates a supplementary Unicode character without depending on an editor preserving its visible symbol.</p>



<p class="wp-block-paragraph">Therefore, <code>DATALENGTH(value) / 2</code> measures UTF-16 code units for an <code>nvarchar</code> value, not universally characters.</p>



<p class="wp-block-paragraph">Even SC-aware <code>LEN</code> is not a complete count of user-perceived symbols. A displayed character can consist of multiple Unicode code points, such as a letter plus a combining accent. Apply user-interface limits in the application using the appropriate text-processing rules.</p>



<h3 class="wp-block-heading">UTF-8 makes VARCHAR variable-width</h3>



<p class="wp-block-paragraph">SQL Server 2019 and later support UTF-8 collations for <code>char</code> and <code>varchar</code>. With UTF-8, one character can require multiple bytes.<a rel="noopener" target="_blank" href="https://learn.microsoft.com/en-us/sql/t-sql/data-types/char-and-varchar-transact-sql?view=sql-server-ver17"></a></p>



<p class="wp-block-paragraph">Run this example on a platform supporting the named collation:</p>



<pre class="wp-block-preformatted"><code>DECLARE @Utf8Example TABLE<br>(<br>    CustomerName varchar(20)<br>        COLLATE Latin1_General_100_CI_AS_SC_UTF8<br>);<br><br>INSERT INTO @Utf8Example (CustomerName)<br>VALUES (N'café');<br><br>SELECT<br>    CustomerName,<br>    LEN(CustomerName) AS CharacterCount,<br>    DATALENGTH(CustomerName) AS ByteCount<br>FROM @Utf8Example;</code></pre>



<p class="wp-block-paragraph">The results are <code>4</code> characters and <code>5</code> bytes. The Unicode literal preserves the accented character before conversion into the UTF-8 column.</p>



<p class="wp-block-paragraph">This is why a 50-character application limit does not guarantee that text fits in <code>varchar(50)</code>. Review <a rel="noopener" target="_blank" href="https://sqlserverguides.com/sql-server-unicode-function/">Unicode function behavior</a> when troubleshooting multilingual values.</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">Pro Tip: I include accented names, Asian-language text, and supplementary characters in migration tests. ASCII-only test data hides the encoding problems most likely to affect real customers.</p>
</blockquote>



<h3 class="wp-block-heading">Build Validation Around the Actual Business Rule</h3>



<p class="wp-block-paragraph">An e-commerce system might have two requirements:</p>



<ol class="wp-block-list">
<li>Product codes must contain between 1 and 30 meaningful characters.</li>



<li>A downstream UTF-8 export permits at most 40 bytes per code.</li>
</ol>



<p class="wp-block-paragraph">Those are different rules. One function cannot safely stand in for the other.</p>



<h4 class="wp-block-heading">Handle NULL and empty strings deliberately</h4>



<pre class="wp-block-preformatted"><code>SELECT<br>    LEN(CAST(NULL AS varchar(20))) AS NullCharacterCount,<br>    DATALENGTH(CAST(NULL AS varchar(20))) AS NullByteCount,<br>    LEN('') AS EmptyCharacterCount,<br>    DATALENGTH('') AS EmptyByteCount,<br>    LEN('   ') AS SpacesCharacterCount,<br>    DATALENGTH('   ') AS SpacesByteCount;</code></pre>



<p class="wp-block-paragraph">The NULL expressions return <code>NULL</code>; empty strings return <code>0</code> for both functions. Three ordinary spaces produce <code>0</code> from <code>LEN</code> and <code>3</code> from <code>DATALENGTH</code>.</p>



<p class="wp-block-paragraph">NULL means missing or unknown, not an empty string. This distinction matters because a <code>CHECK</code> constraint accepts an unknown result, so a length check alone does not reject NULL.</p>



<h4 class="wp-block-heading">Enforce the requirement in a constraint</h4>



<p class="wp-block-paragraph">A constraint is a database rule enforced during data changes. The following table-variable example demonstrates validation without creating a permanent application table:</p>



<pre class="wp-block-preformatted"><code>DECLARE @ProductCodeValidation TABLE<br>(<br>    ProductCode nvarchar(100) NOT NULL,<br>    CHECK (LEN(ProductCode) BETWEEN 1 AND 30)<br>);<br><br>INSERT INTO @ProductCodeValidation (ProductCode)<br>VALUES (N'SKU-1001');<br><br>SELECT ProductCode<br>FROM @ProductCodeValidation;</code></pre>



<p class="wp-block-paragraph"><code>NOT NULL</code> rejects missing values. The length constraint rejects empty strings and strings containing only ordinary spaces.</p>



<p class="wp-block-paragraph">However, <code>N'SKU-1001 '</code> still passes. Decide whether to preserve, reject, or normalize trailing spaces rather than letting <code>LEN</code> make that decision accidentally. Review these <a rel="noopener" target="_blank" href="https://sqlserverguides.com/sql-constraints/">SQL constraint fundamentals</a> before applying permanent rules.</p>



<p class="wp-block-paragraph">Validate before converting into a narrower variable or column. Once text has been truncated, measuring the shortened value cannot reveal its original length. For related failures, see this <a rel="noopener" target="_blank" href="https://sqlserverguides.com/string-or-binary-data-would-be-truncated-in-table/">string or binary data truncation troubleshooting guide</a>.</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">Pro Tip: I document character limits and byte limits separately in interface contracts. “Maximum length 30” is incomplete unless everyone agrees on the unit and encoding.</p>
</blockquote>



<h3 class="wp-block-heading">Profile Data Without Confusing Payload With Database Size</h3>



<p class="wp-block-paragraph">Before changing a column definition, measure real values. A maximum declared width says little about typical customer input.</p>



<pre class="wp-block-preformatted"><code>DECLARE @CustomerSample TABLE<br>(<br>    CustomerName nvarchar(200)<br>);<br><br>INSERT INTO @CustomerSample (CustomerName)<br>VALUES (N'Anne'), (N'María'), (N'Li  '), (NULL);<br><br>SELECT<br>    COUNT_BIG(*) AS TotalRows,<br>    MAX(LEN(CustomerName)) AS MaximumCharacters,<br>    MAX(DATALENGTH(CustomerName)) AS MaximumBytes,<br>    SUM(CAST(DATALENGTH(CustomerName) AS bigint))<br>        AS TotalPayloadBytes,<br>    AVG(CAST(DATALENGTH(CustomerName) AS decimal(19,2)))<br>        AS AveragePayloadBytes<br>FROM @CustomerSample;</code></pre>



<p class="wp-block-paragraph">This set-based query measures the sample without processing rows in a loop. The explicit <code>bigint</code> conversion protects a large aggregate from an <code>int</code> overflow.</p>



<p class="wp-block-paragraph"><code>MAX</code>, <code>SUM</code>, and <code>AVG</code> ignore NULL inputs. The average therefore describes non-NULL names, while <code>COUNT_BIG(*)</code> includes every row.</p>



<p class="wp-block-paragraph">Do not treat <code>TotalPayloadBytes</code> as table size. It excludes row metadata, page overhead, indexes, free space, transaction logs, and other allocation details. Compression can also change physical storage without making <code>DATALENGTH</code> a compressed-page measurement.</p>



<p class="wp-block-paragraph">Use a <a rel="noopener" target="_blank" href="https://sqlserverguides.com/check-database-table-size-in-sql-server/">database table-size query</a> for allocation analysis.</p>



<p class="wp-block-paragraph">On Azure SQL Database, better sizing decisions can reduce unnecessary storage growth. But selecting a smaller column does not automatically shrink existing files or lower provisioned compute charges.</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">Pro Tip: I pair length profiling with allocation measurements. Payload tells me about the data; allocation tells me what the database has actually reserved and used.</p>
</blockquote>



<h3 class="wp-block-heading">Frequently Asked Questions</h3>



<h4 class="wp-block-heading">Why does LEN return fewer characters than expected?</h4>



<p class="wp-block-paragraph"><code>LEN</code> excludes trailing ordinary spaces. Collation rules also affect supplementary-character counting, so check the expression’s data type and collation before assuming the result is wrong.</p>



<h4 class="wp-block-heading">Does DATALENGTH include trailing spaces?</h4>



<p class="wp-block-paragraph">Yes, when those spaces exist in the string expression being measured. It also reflects fixed-width padding, which explains why a short value in <code>char(10)</code> can produce ten bytes.</p>



<h4 class="wp-block-heading">Can I divide DATALENGTH by two for NVARCHAR?</h4>



<p class="wp-block-paragraph">That gives the number of UTF-16 code units, not always the number of characters. Supplementary characters occupy two code units but count as one character under an SC-aware collation.</p>



<h4 class="wp-block-heading">Which function should I use to prevent truncation?</h4>



<p class="wp-block-paragraph">Match the destination’s capacity and encoding. Use byte measurements for a byte-limited destination, but measure the converted destination representation when encodings differ; validate before narrowing the value.</p>



<h4 class="wp-block-heading">Does DATALENGTH show disk space used by a row?</h4>



<p class="wp-block-paragraph">No. It measures the byte representation of the expression, not the complete row, index allocation, compressed page footprint, or database file size. Use storage-allocation measurements for capacity planning.</p>



<p class="wp-block-paragraph">You May Also Like</p>



<ul class="wp-block-list">
<li><a href="https://sqlserverguides.com/sql-server-charindex-vs-patindex/" target="_blank" rel="noreferrer noopener">SQL Server CHARINDEX vs PATINDEX</a></li>



<li><a href="https://sqlserverguides.com/sql-server-count-characters-in-string/" target="_blank" rel="noopener">Count characters in a SQL Server string</a></li>



<li><a href="https://sqlserverguides.com/sql-null/" target="_blank" rel="noopener">Understand SQL NULL values</a></li>



<li><a href="https://sqlserverguides.com/cast-function-in-sql-server/" target="_blank" rel="noopener">Use CAST for explicit SQL Server conversions</a></li>



<li><a href="https://sqlserverguides.com/sql-indexes-best-practices/" target="_blank" rel="noopener">Apply SQL Server indexing best practices</a></li>



<li><a href="https://sqlserverguides.com/sql-database-design-best-practices/" target="_blank" rel="noopener">Review database design best practices</a></li>
</ul>



<p class="wp-block-paragraph"><code>LEN</code> measures characters without trailing ordinary spaces, while <code>DATALENGTH</code> measures the bytes representing a value. Match validation to the actual data type, encoding, and business requirement, then test boundary cases before deployment. I hope you found this article helpful.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>SQL Server CAST vs CONVERT</title>
		<link>https://sqlserverguides.com/sql-server-cast-vs-convert/</link>
		
		<dc:creator><![CDATA[Bijay Kumar Sahoo]]></dc:creator>
		<pubDate>Tue, 10 Nov 2026 16:44:45 +0000</pubDate>
				<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[SQL Server CAST vs CONVERT]]></category>
		<guid isPermaLink="false">https://sqlserverguides.com/?p=24122</guid>

					<description><![CDATA[A nightly order import fails because one row contains “pending” in an amount column. Meanwhile, a report displays dates differently between environments, and a customer lookup scans far more data than expected. Each problem involves conversion, but each needs a different fix. The SQL Server CAST vs CONVERT decision is straightforward: use CAST for standard, ... <a title="SQL Server CAST vs CONVERT" class="read-more" href="https://sqlserverguides.com/sql-server-cast-vs-convert/" aria-label="Read more about SQL Server CAST vs CONVERT">Read more</a>]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">A nightly order import fails because one row contains “pending” in an amount column. Meanwhile, a report displays dates differently between environments, and a customer lookup scans far more data than expected. Each problem involves conversion, but each needs a different fix.</p>



<p class="wp-block-paragraph">The <strong>SQL Server CAST vs CONVERT</strong> decision is straightforward: use CAST for standard, readable type conversion and CONVERT when you need its style parameter, especially for date parsing or formatted output. Neither function automatically validates your business rules or guarantees better performance.</p>



<p class="wp-block-paragraph">You’ll learn how to choose between them, handle invalid input, preserve numeric precision, and avoid conversions that interfere with efficient queries.</p>



<h2 class="wp-block-heading">SQL Server CAST vs CONVERT: The Main Differences</h2>



<p class="wp-block-paragraph">Both functions perform explicit conversion: you tell SQL Server which data type the result should use. An implicit conversion happens automatically when SQL Server reconciles different types in an expression.</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>Feature</th><th>CAST</th><th>CONVERT</th></tr></thead><tbody><tr><td>Basic purpose</td><td>Convert an expression to another type</td><td>Convert an expression to another type</td></tr><tr><td>Syntax</td><td><code>CAST(expression AS type)</code></td><td><code>CONVERT(type, expression [, style])</code></td></tr><tr><td>SQL portability</td><td>Uses standard SQL syntax</td><td>Uses T-SQL-specific syntax</td></tr><tr><td>Style parameter</td><td>Not available</td><td>Available for supported conversions</td></tr><tr><td>Invalid supported conversion</td><td>Usually raises an error</td><td>Usually raises an error</td></tr><tr><td>Error-tolerant counterpart</td><td>TRY_CAST</td><td>TRY_CONVERT</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">T-SQL is Microsoft’s SQL dialect. These functions work in SQL Server, Azure SQL Database, and Azure SQL Managed Instance.</p>



<p class="wp-block-paragraph">CAST improves portability, but identical behavior across database products is not guaranteed. Supported types, rounding, and date interpretation still vary.</p>



<p class="wp-block-paragraph">CONVERT’s style parameter controls certain conversions involving dates, times, money, floating-point values, and binary data. It is not a universal formatting argument that applies identically to every type.</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">Pro Tip: I would make CAST the default in a coding standard and require a clear reason—usually a documented style—for choosing CONVERT.</p>
</blockquote>



<h2 class="wp-block-heading">Compare CAST and CONVERT Syntax With Simple Examples</h2>



<p class="wp-block-paragraph">Start with equivalent conversions:</p>



<pre class="wp-block-preformatted"><code>SELECT<br>    CAST('125' AS int) AS UsingCast,<br>    CONVERT(int, '125') AS UsingConvert;</code></pre>



<p class="wp-block-paragraph">Both return the integer <code>125</code>. Check out the screenshot below for your reference.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="836" height="251" src="https://sqlserverguides.com/wp-content/uploads/2026/11/SQL-Server-CAST-vs-CONVERT.jpg" alt="" class="wp-image-24123" srcset="https://sqlserverguides.com/wp-content/uploads/2026/11/SQL-Server-CAST-vs-CONVERT.jpg 836w, https://sqlserverguides.com/wp-content/uploads/2026/11/SQL-Server-CAST-vs-CONVERT-300x90.jpg 300w, https://sqlserverguides.com/wp-content/uploads/2026/11/SQL-Server-CAST-vs-CONVERT-766x230.jpg 766w" sizes="auto, (max-width: 836px) 100vw, 836px" /></figure>
</div>


<p class="wp-block-paragraph">The target type determines what values the result can represent. Converting text to an integer requires valid integer text within the integer range.</p>



<h3 class="wp-block-heading">Convert a number to text</h3>



<pre class="wp-block-preformatted"><code>DECLARE @OrderId int = 10425;<br><br>SELECT<br>    CAST(@OrderId AS varchar(20)) AS CastOrderId,<br>    CONVERT(varchar(20), @OrderId) AS ConvertOrderId;</code></pre>



<p class="wp-block-paragraph">Both return the text <code>10425</code>. See the screenshot below for reference.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="307" src="https://sqlserverguides.com/wp-content/uploads/2026/11/cast-vs-convert-sql-1024x307.jpg" alt="cast vs convert sql" class="wp-image-24124" srcset="https://sqlserverguides.com/wp-content/uploads/2026/11/cast-vs-convert-sql-1024x307.jpg 1024w, https://sqlserverguides.com/wp-content/uploads/2026/11/cast-vs-convert-sql-300x90.jpg 300w, https://sqlserverguides.com/wp-content/uploads/2026/11/cast-vs-convert-sql-767x230.jpg 767w, https://sqlserverguides.com/wp-content/uploads/2026/11/cast-vs-convert-sql.jpg 1051w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p class="wp-block-paragraph">This is useful when building an export label. It does not change the original variable or a stored column.</p>



<p class="wp-block-paragraph">Always specify string length. For CAST and CONVERT, an omitted character length defaults to 30; in variable declarations and data definitions, the default can instead be 1. Depending on the conversion, insufficient length can truncate text or cause an error.</p>



<h3 class="wp-block-heading">Understand NULL behavior</h3>



<pre class="wp-block-preformatted"><code>SELECT<br>    CAST(NULL AS int) AS CastResult,<br>    CONVERT(date, NULL) AS ConvertResult;</code></pre>



<p class="wp-block-paragraph">Both results are NULL. Conversion does not turn missing information into zero or an empty string. See the screenshot below for reference.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="848" height="248" src="https://sqlserverguides.com/wp-content/uploads/2026/11/sql-cast-vs-convert.jpg" alt="sql cast vs convert" class="wp-image-24125" srcset="https://sqlserverguides.com/wp-content/uploads/2026/11/sql-cast-vs-convert.jpg 848w, https://sqlserverguides.com/wp-content/uploads/2026/11/sql-cast-vs-convert-300x88.jpg 300w, https://sqlserverguides.com/wp-content/uploads/2026/11/sql-cast-vs-convert-766x224.jpg 766w" sizes="auto, (max-width: 848px) 100vw, 848px" /></figure>
</div>


<p class="wp-block-paragraph">For additional examples, see <a rel="noopener" target="_blank" href="https://sqlserverguides.com/cast-function-in-sql-server/">using CAST in SQL Server</a> and <a rel="noopener" target="_blank" href="https://sqlserverguides.com/convert-function-in-sql-server/">using the CONVERT function</a>.</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">Pro Tip: I would specify string length even in diagnostic queries. Examples copied into production should not depend on context-sensitive defaults.</p>
</blockquote>



<h3 class="wp-block-heading">SQL Server CAST vs CONVERT for Dates and Times</h3>



<p class="wp-block-paragraph">CONVERT is especially useful when text dates arrive in a documented format.</p>



<p class="wp-block-paragraph">The string <code>03/04/2026</code> is ambiguous. It can mean March 4 or April 3. Relying on session language or date-format settings can produce different results between environments.</p>



<h3 class="wp-block-heading">Parse an explicit input format</h3>



<pre class="wp-block-preformatted"><code>SELECT<br>    CONVERT(date, '03/04/2026', 101) AS USDate,<br>    CONVERT(date, '03/04/2026', 103) AS BritishDate;</code></pre>



<p class="wp-block-paragraph">After executing the above query, I got the expected output. See the screenshot below for reference.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="239" src="https://sqlserverguides.com/wp-content/uploads/2026/11/cast-vs-convert-sql-server-1024x239.jpg" alt="cast vs convert sql server" class="wp-image-24126" srcset="https://sqlserverguides.com/wp-content/uploads/2026/11/cast-vs-convert-sql-server-1024x239.jpg 1024w, https://sqlserverguides.com/wp-content/uploads/2026/11/cast-vs-convert-sql-server-766x179.jpg 766w, https://sqlserverguides.com/wp-content/uploads/2026/11/cast-vs-convert-sql-server-300x70.jpg 300w, https://sqlserverguides.com/wp-content/uploads/2026/11/cast-vs-convert-sql-server.jpg 1027w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p class="wp-block-paragraph">Style 101 interprets the text as month/day/year, producing March 4. Style 103 interprets it as day/month/year, producing April 3.</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>Style</th><th>Typical format</th><th>Example</th></tr></thead><tbody><tr><td>101</td><td><code>mm/dd/yyyy</code></td><td><code>11/10/2026</code></td></tr><tr><td>103</td><td><code>dd/mm/yyyy</code></td><td><code>10/11/2026</code></td></tr><tr><td>112</td><td><code>yyyymmdd</code></td><td><code>20261110</code></td></tr><tr><td>23</td><td><code>yyyy-mm-dd</code></td><td><code>2026-11-10</code></td></tr><tr><td>126</td><td>ISO-style date and time</td><td><code>2026-11-10T14:35:27.123</code></td></tr></tbody></table></figure>



<p class="wp-block-paragraph">Styles describe supported parsing or output behavior; they do not change a date column into stored formatted text.</p>



<h3 class="wp-block-heading">Format a typed date for export</h3>



<pre class="wp-block-preformatted"><code>DECLARE @CreatedAt datetime2(3) =<br>    '2026-11-10T14:35:27.123';<br><br>SELECT<br>    CONVERT(char(8), @CreatedAt, 112)<br>        AS CompactDate,<br>    CONVERT(char(10), @CreatedAt, 23)<br>        AS ReadableDate,<br>    CONVERT(varchar(23), @CreatedAt, 126)<br>        AS TimestampText;</code></pre>



<p class="wp-block-paragraph">The results are <code>20261110</code>, <code>2026-11-10</code>, and <code>2026-11-10T14:35:27.123</code>. Check out the screenshot below for your reference.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="883" height="520" src="https://sqlserverguides.com/wp-content/uploads/2026/11/cast-vs-convert-sql-server-performance.jpg" alt="cast vs convert sql server performance" class="wp-image-24127" srcset="https://sqlserverguides.com/wp-content/uploads/2026/11/cast-vs-convert-sql-server-performance.jpg 883w, https://sqlserverguides.com/wp-content/uploads/2026/11/cast-vs-convert-sql-server-performance-300x177.jpg 300w, https://sqlserverguides.com/wp-content/uploads/2026/11/cast-vs-convert-sql-server-performance-768x452.jpg 768w" sizes="auto, (max-width: 883px) 100vw, 883px" /></figure>
</div>


<p class="wp-block-paragraph">Store dates in date/time columns and format them at the output boundary. Text storage makes validation, sorting, and date arithmetic harder.</p>



<p class="wp-block-paragraph">Also, datetime2 does not carry a time-zone offset. Adding a <code>Z</code> to formatted output does not make an unspecified local timestamp UTC.</p>



<p class="wp-block-paragraph">See <a rel="noopener" target="_blank" href="https://sqlserverguides.com/how-to-convert-varchar-to-date-in-sql-server/">converting varchar values to dates</a> for related parsing examples.</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">Pro Tip: I would document the source format beside every import conversion. A style number without its intended format is easy to misinterpret during maintenance.</p>
</blockquote>



<h3 class="wp-block-heading">Preserve Numeric Precision and Understand Rounding</h3>



<p class="wp-block-paragraph">CAST and CONVERT apply the same underlying rules for equivalent numeric conversions. The important decisions are the source type, target range, precision, and scale.</p>



<p class="wp-block-paragraph">Precision is the total number of decimal digits. Scale is the number after the decimal point.</p>



<pre class="wp-block-preformatted"><code>SELECT<br>    CAST(123.4567 AS decimal(10, 2)) AS CastAmount,<br>    CONVERT(decimal(10, 2), 123.4567) AS ConvertAmount;</code></pre>



<p class="wp-block-paragraph">Both return <code>123.46</code>.</p>



<p class="wp-block-paragraph">Reducing decimal scale normally rounds. Converting a decimal number to int instead truncates its fractional portion:</p>



<pre class="wp-block-preformatted"><code>SELECT<br>    CAST(123.99 AS int) AS PositiveInteger,<br>    CONVERT(int, -123.99) AS NegativeInteger;</code></pre>



<p class="wp-block-paragraph">The results are <code>123</code> and <code>-123</code>. Check out the screenshot below for your reference.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="913" height="317" src="https://sqlserverguides.com/wp-content/uploads/2026/11/t-sql-cast-vs-convert.jpg" alt="t sql cast vs convert" class="wp-image-24128" srcset="https://sqlserverguides.com/wp-content/uploads/2026/11/t-sql-cast-vs-convert.jpg 913w, https://sqlserverguides.com/wp-content/uploads/2026/11/t-sql-cast-vs-convert-766x266.jpg 766w, https://sqlserverguides.com/wp-content/uploads/2026/11/t-sql-cast-vs-convert-300x104.jpg 300w" sizes="auto, (max-width: 913px) 100vw, 913px" /></figure>
</div>


<p class="wp-block-paragraph">Do not generalize this behavior to every source type. Conversion rules can differ for money, floating-point, and character values.</p>



<h3 class="wp-block-heading">Convert before integer division</h3>



<pre class="wp-block-preformatted"><code>SELECT<br>    CAST(5 / 2 AS decimal(10, 2))<br>        AS ConvertedTooLate,<br>    CAST(5 AS decimal(10, 2)) / 2<br>        AS FractionPreserved;</code></pre>



<p class="wp-block-paragraph">The first expression returns <code>2.00</code>. Integer division already discarded the fraction before CAST ran.</p>



<h3 class="wp-block-heading">Test the target range</h3>



<p class="wp-block-paragraph">A decimal(5,2) supports three digits before the decimal point. It cannot hold <code>1234.56</code>.</p>



<p class="wp-block-paragraph">A value can also overflow after rounding: <code>999.995</code> cannot become <code>1000.00</code> in decimal(5,2).</p>



<p class="wp-block-paragraph">Choose types from documented maximums rather than current sample values. Avoid using float for contractual monetary amounts that require exact decimal representation.</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">Pro Tip: I would test both the largest expected value and a value that rounds across a boundary. Those cases expose weaknesses that ordinary amounts miss.</p>
</blockquote>



<h3 class="wp-block-heading">Use TRY_CAST and TRY_CONVERT for Untrusted Input</h3>



<p class="wp-block-paragraph">CAST and CONVERT can stop a statement when a supported conversion fails. TRY_CAST and TRY_CONVERT return NULL for those failures instead.</p>



<p class="wp-block-paragraph">TRY_CONVERT also accepts a style argument, making it useful for imported dates. Both are available in modern SQL Server versions, including SQL Server 2012 and later.learn.microsoft+1</p>



<h3 class="wp-block-heading">Validate an import without writing data</h3>



<p class="wp-block-paragraph">This example uses inline rows and a common table expression, or CTE—a named result set for the following statement.</p>



<pre class="wp-block-preformatted"><code>WITH SourceRows AS<br>(<br>    SELECT *<br>    FROM<br>    (<br>        VALUES<br>            (1, N'125.50', N'11/10/2026'),<br>            (2, N'pending', N'11/10/2026'),<br>            (3, N'', N'02/30/2026'),<br>            (4, NULL, NULL)<br>    ) AS v(SourceRowId, AmountText, OrderDateText)<br>),<br>Parsed AS<br>(<br>    SELECT<br>        SourceRowId,<br>        NULLIF(LTRIM(RTRIM(AmountText)), N'')<br>            AS CleanAmountText,<br>        TRY_CAST(<br>            NULLIF(LTRIM(RTRIM(AmountText)), N'')<br>            AS decimal(12, 2)<br>        ) AS ParsedAmount,<br>        TRY_CONVERT(<br>            date,<br>            NULLIF(LTRIM(RTRIM(OrderDateText)), N''),<br>            101<br>        ) AS ParsedOrderDate<br>    FROM SourceRows<br>)<br>SELECT<br>    SourceRowId,<br>    ParsedAmount,<br>    ParsedOrderDate,<br>    CASE<br>        WHEN CleanAmountText IS NULL THEN 'Missing amount'<br>        WHEN ParsedAmount IS NULL THEN 'Invalid amount'<br>        ELSE 'Valid amount'<br>    END AS AmountStatus<br>FROM Parsed;</code></pre>



<p class="wp-block-paragraph">Trimming and NULLIF normalize ordinary blank input before conversion. TRY_CAST handles the amount; TRY_CONVERT interprets dates using style 101.</p>



<p class="wp-block-paragraph">The invalid February date becomes NULL. Add a separate date-status expression in a complete validation workflow.</p>



<p class="wp-block-paragraph">Do not immediately replace every failed value with zero. That can conceal rejected revenue or inventory quantities.</p>



<h3 class="wp-block-heading">Know the limits</h3>



<p class="wp-block-paragraph">TRY functions are not universal error suppression. An explicitly prohibited conversion, such as integer directly to XML, still raises an error. Successful conversion also does not guarantee validity: negative quantities or implausible dates may still violate business rules.learn.microsoft+1</p>



<p class="wp-block-paragraph">Review <a rel="noopener" target="_blank" href="https://sqlserverguides.com/tryconvert-function-in-sql-server/">TRY_CONVERT examples</a> when building a staging process.</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">Pro Tip: I would preserve the source row identifier, raw value, and rejection reason so an import can be corrected and replayed without guesswork.</p>
</blockquote>



<h3 class="wp-block-heading">Avoid Conversion-Driven Performance Problems</h3>



<p class="wp-block-paragraph">There is no useful blanket rule that CAST is faster than CONVERT. Equivalent expressions often produce equivalent plans.</p>



<p class="wp-block-paragraph">The larger concern is where conversion occurs.</p>



<h3 class="wp-block-heading">Match parameter and column types</h3>



<p class="wp-block-paragraph">Suppose OrderNumber is a varchar column with an index:</p>



<pre class="wp-block-preformatted"><code><em>-- Assumes dbo.Orders exists.</em><br>DECLARE @OrderNumber varchar(20) = '10425';<br><br>SELECT<br>    OrderId,<br>    OrderNumber<br>FROM dbo.Orders<br>WHERE OrderNumber = @OrderNumber;</code></pre>



<p class="wp-block-paragraph">Matching types avoids an unnecessary conversion.</p>



<p class="wp-block-paragraph">By contrast, converting every OrderNumber to int can fail on alphanumeric values and interfere with efficient index access. An index seek navigates to matching entries; a scan reads a broader set.</p>



<p class="wp-block-paragraph">Leading zeros also matter. The identifiers <code>0010425</code> and <code>10425</code> may be different business values even though their numeric conversions match.</p>



<h3 class="wp-block-heading">Prefer clear timestamp ranges</h3>



<pre class="wp-block-preformatted"><code><em>-- Assumes OrderDate is datetime2(3).</em><br>DECLARE @Start datetime2(3) = '2026-11-10T00:00:00.000';<br>DECLARE @End datetime2(3) = '2026-11-11T00:00:00.000';<br><br>SELECT OrderId, OrderDate<br>FROM dbo.Orders<br>WHERE OrderDate &gt;= @Start<br>  AND OrderDate &lt; @End;</code></pre>



<p class="wp-block-paragraph">This half-open range includes the starting boundary and excludes the next day.</p>



<p class="wp-block-paragraph">SQL Server can optimize some casts from datetime to date, so “any function prevents a seek” is too absolute. Nevertheless, a direct range makes intent explicit and is straightforward to test.</p>



<p class="wp-block-paragraph">Inspect actual execution plans, conversion warnings, logical reads, and runtime. Query Store, when enabled, helps compare historical plans and performance.</p>



<p class="wp-block-paragraph">See <a rel="noopener" target="_blank" href="https://sqlserverguides.com/sql-query-optimization-tips/">SQL query optimization tips</a> before adding indexes or increasing Azure compute.</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">Pro Tip: I would investigate column-side conversions before debating CAST versus CONVERT syntax. Expression placement usually matters more than the function name.</p>
</blockquote>



<h3 class="wp-block-heading">Frequently Asked Questions</h3>



<h4 class="wp-block-heading">Which is better: CAST or CONVERT?</h4>



<p class="wp-block-paragraph">Use CAST for ordinary conversions and clearer standard SQL syntax. Use CONVERT when a supported style parameter provides necessary parsing or output control.</p>



<h4 class="wp-block-heading">Is CONVERT faster than CAST in SQL Server?</h4>



<p class="wp-block-paragraph">Not inherently. Compare the actual plan and workload; source types, expression placement, and index access usually matter more than choosing between equivalent syntax.</p>



<h4 class="wp-block-heading">Can CAST format a date as yyyy-mm-dd?</h4>



<p class="wp-block-paragraph">CAST has no style parameter. Use <code>CONVERT(char(10), DateColumn, 23)</code> when you specifically need that text output, while keeping stored dates in date/time types.</p>



<h4 class="wp-block-heading">Why does TRY_CAST return NULL?</h4>



<p class="wp-block-paragraph">The source may be NULL, invalid for the target type, or outside its range. Preserve raw input and validation status so you can distinguish those situations.</p>



<h4 class="wp-block-heading">Will TRY_CONVERT prevent every conversion error?</h4>



<p class="wp-block-paragraph">No. Explicitly prohibited conversions still raise errors. It also does not prevent truncation or rounding that counts as a successful conversion, so validate those separately.</p>



<p class="wp-block-paragraph">You May Also Like</p>



<ul class="wp-block-list">
<li><a href="https://sqlserverguides.com/sql-server-len-vs-datalength/" target="_blank" rel="noreferrer noopener">SQL Server LEN vs DATALENGTH</a></li>



<li><a href="https://sqlserverguides.com/error-converting-data-type-varchar-to-numeric/" target="_blank" rel="noopener">Fixing varchar-to-numeric conversion errors</a></li>



<li><a href="https://sqlserverguides.com/sql-server-date-formatting/" target="_blank" rel="noopener">Understanding SQL Server date formats</a></li>



<li><a href="https://sqlserverguides.com/case-statement-in-sql-server/" target="_blank" rel="noopener">Using CASE expressions for validation</a></li>



<li><a href="https://sqlserverguides.com/sql-database-design-best-practices/" target="_blank" rel="noopener">SQL database design best practices</a></li>



<li><a href="https://sqlserverguides.com/sql-indexes-best-practices/" target="_blank" rel="noopener">SQL Server index best practices</a></li>



<li><a href="https://sqlserverguides.com/sql-server-lag-and-lead-functions/" target="_blank" rel="noreferrer noopener">SQL Server LAG and LEAD Functions</a></li>
</ul>



<p class="wp-block-paragraph">CAST handles standard type conversion, while CONVERT adds style-based control for supported formats. Preserve source meaning, validate failures explicitly, and test execution plans before deploying conversion changes. I hope you found this article helpful.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>SQL COUNT vs COUNT DISTINCT Difference</title>
		<link>https://sqlserverguides.com/sql-count-vs-count-distinct-difference/</link>
		
		<dc:creator><![CDATA[Bijay Kumar Sahoo]]></dc:creator>
		<pubDate>Tue, 10 Nov 2026 14:52:39 +0000</pubDate>
				<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[SQL COUNT vs COUNT DISTINCT Difference]]></category>
		<guid isPermaLink="false">https://sqlserverguides.com/?p=24115</guid>

					<description><![CDATA[A sales dashboard shows 40,000 customers, but the customer table contains only 12,000 accounts. The report joined customers to orders and counted the resulting rows. Repeat buyers appeared several times, turning an order count into an inflated customer count. The SQL COUNT vs COUNT DISTINCT difference comes down to what you count: COUNT(*) counts rows, ... <a title="SQL COUNT vs COUNT DISTINCT Difference" class="read-more" href="https://sqlserverguides.com/sql-count-vs-count-distinct-difference/" aria-label="Read more about SQL COUNT vs COUNT DISTINCT Difference">Read more</a>]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">A sales dashboard shows 40,000 customers, but the customer table contains only 12,000 accounts. The report joined customers to orders and counted the resulting rows. Repeat buyers appeared several times, turning an order count into an inflated customer count.</p>



<p class="wp-block-paragraph">The <strong>SQL COUNT vs COUNT DISTINCT</strong> difference comes down to what you count: <code>COUNT(*)</code> counts rows, <code>COUNT(column)</code> counts non-NULL values, and <code>COUNT(DISTINCT column)</code> counts unique non-NULL values. These expressions answer different business questions.</p>



<p class="wp-block-paragraph">You’ll learn how to choose the correct expression, handle joins and missing values, and tune exact counts without changing what the report means.</p>



<h2 class="wp-block-heading">SQL COUNT vs COUNT DISTINCT: The Main Difference</h2>



<p class="wp-block-paragraph">COUNT is an aggregate function: it summarizes a set of rows into a single result. Adding DISTINCT changes the calculation by eliminating duplicate expression values before counting.</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>Expression</th><th>Counts duplicates?</th><th>Counts NULL?</th><th>Typical purpose</th></tr></thead><tbody><tr><td><code>COUNT(*)</code></td><td>Yes, as separate rows</td><td>Includes rows containing NULL</td><td>Total matching rows</td></tr><tr><td><code>COUNT(CustomerId)</code></td><td>Yes</td><td>No</td><td>Rows with a known customer</td></tr><tr><td><code>COUNT(DISTINCT CustomerId)</code></td><td>No</td><td>No</td><td>Unique known customers</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">All three operate on the rows produced by the query’s filters and joins. They do not necessarily count an entire base table.</p>



<p class="wp-block-paragraph">For example, filtering an orders query to November means the count applies only to qualifying November rows. Adding a join may multiply those rows before aggregation.</p>



<p class="wp-block-paragraph">These behaviors apply to SQL Server, Azure SQL Database, and Azure SQL Managed Instance. COUNT returns an <code>int</code>; COUNT_BIG provides equivalent counting behavior with a <code>bigint</code> result for larger totals.</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">Pro Tip: I would name the metric before writing the query: “order rows,” “identified orders,” and “unique buyers” require different expressions.</p>
</blockquote>



<h3 class="wp-block-heading">Run a SQL COUNT vs COUNT DISTINCT Example</h3>



<p class="wp-block-paragraph">This self-contained example uses a common table expression, or CTE, to name an inline result set. It creates no permanent objects.</p>



<pre class="wp-block-preformatted"><code>WITH Orders AS<br>(<br>    SELECT *<br>    FROM<br>    (<br>        VALUES<br>            (1001, 101, 'East'),<br>            (1002, 101, 'East'),<br>            (1003, 102, 'West'),<br>            (1004, NULL, 'West'),<br>            (1005, 103, 'East'),<br>            (1006, 103, 'East')<br>    ) AS v(OrderId, CustomerId, Region)<br>)<br>SELECT<br>    COUNT(*) AS TotalOrders,<br>    COUNT(CustomerId) AS OrdersWithCustomerId,<br>    COUNT(DISTINCT CustomerId) AS UniqueCustomers<br>FROM Orders;</code></pre>



<p class="wp-block-paragraph">The results are as shown in the screenshot below:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="938" height="763" src="https://sqlserverguides.com/wp-content/uploads/2026/11/sql-count-vs-count-distinct-difference.jpg" alt="sql count vs count distinct difference" class="wp-image-24116" srcset="https://sqlserverguides.com/wp-content/uploads/2026/11/sql-count-vs-count-distinct-difference.jpg 938w, https://sqlserverguides.com/wp-content/uploads/2026/11/sql-count-vs-count-distinct-difference-300x244.jpg 300w, https://sqlserverguides.com/wp-content/uploads/2026/11/sql-count-vs-count-distinct-difference-767x624.jpg 767w" sizes="auto, (max-width: 938px) 100vw, 938px" /></figure>
</div>


<p class="wp-block-paragraph">There are six orders. Five contain a customer identifier. Those five references represent three customers: 101, 102, and 103.</p>



<p class="wp-block-paragraph">The NULL customer could represent guest checkout or incomplete source data. Its meaning belongs in the data specification; the count cannot determine it.</p>



<p class="wp-block-paragraph">A CTE exists only for the statement immediately following it. Repeat the CTE when running another independent example.</p>



<p class="wp-block-paragraph">For additional syntax, see <a rel="noopener" target="_blank" href="https://sqlserverguides.com/how-to-use-count-function-in-sql-server/">using COUNT in SQL Server</a>.</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">Pro Tip: I would validate a count against six understandable rows before running it against six million. Small examples expose definition mistakes quickly.</p>
</blockquote>



<h3 class="wp-block-heading">Understand NULL, Empty Strings, and Empty Results</h3>



<p class="wp-block-paragraph">NULL means missing, unknown, or inapplicable information. It is not a blank string or zero.</p>



<pre class="wp-block-preformatted"><code>SELECT<br>    COUNT(*) AS TotalRows,<br>    COUNT(v.Code) AS NonNullCodes,<br>    COUNT(DISTINCT v.Code) AS UniqueCodes<br>FROM<br>(<br>    VALUES<br>        (CAST('A' AS varchar(10))),<br>        ('A'),<br>        (''),<br>        (NULL)<br>) AS v(Code);</code></pre>



<p class="wp-block-paragraph">This returns four rows, three non-NULL codes, and two distinct codes. The empty string contributes a value. See the screenshot below for reference.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="851" height="580" src="https://sqlserverguides.com/wp-content/uploads/2026/11/sql-count-vs-count-distinct.jpg" alt="sql count vs count distinct" class="wp-image-24117" srcset="https://sqlserverguides.com/wp-content/uploads/2026/11/sql-count-vs-count-distinct.jpg 851w, https://sqlserverguides.com/wp-content/uploads/2026/11/sql-count-vs-count-distinct-300x204.jpg 300w, https://sqlserverguides.com/wp-content/uploads/2026/11/sql-count-vs-count-distinct-767x523.jpg 767w" sizes="auto, (max-width: 851px) 100vw, 851px" /></figure>
</div>


<p class="wp-block-paragraph">String uniqueness follows the expression’s collation—the comparison rules governing characteristics such as case and accent sensitivity. Under a case-insensitive collation, <code>ABC</code> and <code>abc</code> may count as one value.</p>



<p class="wp-block-paragraph">Do not substitute a placeholder merely to include NULL in a distinct count. A placeholder that appears in real data can merge unrelated categories.</p>



<h3 class="wp-block-heading">Include NULL as one category</h3>



<pre class="wp-block-preformatted"><code>SELECT COUNT(*) AS DistinctCategoriesIncludingNull<br>FROM<br>(<br>    SELECT DISTINCT v.CustomerId<br>    FROM<br>    (<br>        VALUES (101), (101), (102), (NULL), (NULL)<br>    ) AS v(CustomerId)<br>) AS d;</code></pre>



<p class="wp-block-paragraph">This returns <code>3</code>. SELECT DISTINCT retains one NULL category; the outer COUNT(*) counts that row. In contrast, COUNT(DISTINCT CustomerId) excludes it.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="1007" height="457" src="https://sqlserverguides.com/wp-content/uploads/2026/11/count-vs-distinct-count-in-sql.jpg" alt="count vs distinct count in sql" class="wp-image-24118" srcset="https://sqlserverguides.com/wp-content/uploads/2026/11/count-vs-distinct-count-in-sql.jpg 1007w, https://sqlserverguides.com/wp-content/uploads/2026/11/count-vs-distinct-count-in-sql-300x136.jpg 300w, https://sqlserverguides.com/wp-content/uploads/2026/11/count-vs-distinct-count-in-sql-767x348.jpg 767w" sizes="auto, (max-width: 1007px) 100vw, 1007px" /></figure>
</div>


<h3 class="wp-block-heading">Count an empty result</h3>



<p class="wp-block-paragraph">Without GROUP BY, a COUNT aggregate returns one row containing zero when nothing matches. With GROUP BY, an empty input produces no groups and therefore no result rows.</p>



<p class="wp-block-paragraph">Review <a rel="noopener" target="_blank" href="https://sqlserverguides.com/sql-null/">SQL NULL behavior</a> when missing values affect reporting.</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">Pro Tip: I would decide explicitly whether “unknown” is excluded, counted as one category, or reported separately. Each approach produces a different metric.</p>
</blockquote>



<h3 class="wp-block-heading">Count Within Groups Without Double-Counting Totals</h3>



<p class="wp-block-paragraph">GROUP BY divides qualifying rows into groups before calculating aggregates.</p>



<pre class="wp-block-preformatted"><code>SELECT<br>    v.Region,<br>    COUNT(*) AS OrderCount,<br>    COUNT(DISTINCT v.CustomerId) AS UniqueCustomers<br>FROM<br>(<br>    VALUES<br>        ('East', 101),<br>        ('East', 101),<br>        ('East', 102),<br>        ('West', 101),<br>        ('West', 103)<br>) AS v(Region, CustomerId)<br>GROUP BY v.Region;</code></pre>



<p class="wp-block-paragraph">East has three orders and two unique customers. West has two orders and two unique customers.</p>



<p class="wp-block-paragraph">However, the overall unique-customer count is three, not four. Customer 101 appears in both groups.</p>



<p class="wp-block-paragraph">Distinct counts are generally not additive. Summing daily unique visitors does not necessarily produce monthly unique visitors; summing tenant-level users may not produce organization-wide users.</p>



<h3 class="wp-block-heading">Filter groups with HAVING</h3>



<pre class="wp-block-preformatted"><code>SELECT<br>    v.CustomerId,<br>    COUNT(*) AS OrderCount<br>FROM<br>(<br>    VALUES<br>        (101, 1001),<br>        (101, 1002),<br>        (102, 1003)<br>) AS v(CustomerId, OrderId)<br>GROUP BY v.CustomerId<br>HAVING COUNT(*) &gt; 1;</code></pre>



<p class="wp-block-paragraph">This returns customer 101 with two orders. WHERE filters input rows; HAVING filters aggregated groups.</p>



<p class="wp-block-paragraph">See <a rel="noopener" target="_blank" href="https://sqlserverguides.com/how-to-use-group-by-clause-in-sql-server/">GROUP BY examples</a> for more grouping patterns.</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">Pro Tip: I would calculate an overall distinct total independently rather than sum grouped distinct counts unless the groups are provably disjoint.</p>
</blockquote>



<h3 class="wp-block-heading">Fix Inflated Counts After Joins</h3>



<p class="wp-block-paragraph">A one-to-many join produces multiple result rows for one parent. That behavior is correct, but counting those rows may answer the wrong question.</p>



<p class="wp-block-paragraph">The next example models customers and their orders:</p>



<pre class="wp-block-preformatted"><code>WITH Customers AS<br>(<br>    SELECT CustomerId<br>    FROM (VALUES (101), (102), (103)) AS v(CustomerId)<br>),<br>Orders AS<br>(<br>    SELECT *<br>    FROM<br>    (<br>        VALUES<br>            (1001, 101),<br>            (1002, 101),<br>            (1003, 102)<br>    ) AS v(OrderId, CustomerId)<br>)<br>SELECT<br>    COUNT(*) AS JoinedRows,<br>    COUNT(o.OrderId) AS MatchedOrders,<br>    COUNT(DISTINCT c.CustomerId) AS AllCustomers,<br>    COUNT(DISTINCT o.CustomerId) AS BuyingCustomers<br>FROM Customers AS c<br>LEFT JOIN Orders AS o<br>    ON o.CustomerId = c.CustomerId;</code></pre>



<p class="wp-block-paragraph">The results are four joined rows, three orders, three customers, and two buying customers.</p>



<p class="wp-block-paragraph">LEFT JOIN preserves customer 103 with NULL order columns. Consequently, COUNT(*) includes that unmatched row, while COUNT(o.OrderId) does not.</p>



<h3 class="wp-block-heading">Count children per parent</h3>



<p class="wp-block-paragraph">When grouping by customer, use the nonnullable child key:</p>



<pre class="wp-block-preformatted"><code><em>-- Assumes these application tables already exist.</em><br>SELECT<br>    c.CustomerId,<br>    COUNT(o.OrderId) AS OrderCount<br>FROM dbo.Customers AS c<br>LEFT JOIN dbo.Orders AS o<br>    ON o.CustomerId = c.CustomerId<br>GROUP BY c.CustomerId;</code></pre>



<p class="wp-block-paragraph">Assuming OrderId is a nonnullable order identifier, customers without orders receive zero rather than one.</p>



<p class="wp-block-paragraph">If another join introduces order lines, even COUNT(o.OrderId) can multiply. Aggregate orders first, use an appropriate distinct key, or use EXISTS when the question is simply whether a match exists.</p>



<p class="wp-block-paragraph">See <a rel="noopener" target="_blank" href="https://sqlserverguides.com/sql-left-join/">SQL Server LEFT JOIN examples</a>.</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">Pro Tip: I would inspect the joined rows before adding DISTINCT. Deduplication can hide an incorrect join condition instead of fixing it.</p>
</blockquote>



<h3 class="wp-block-heading">Count Unique Combinations and Conditional Values</h3>



<p class="wp-block-paragraph">SQL Server’s COUNT(DISTINCT expression) accepts one expression, not a comma-separated list of columns. To count combinations, deduplicate the columns in a derived table.</p>



<pre class="wp-block-preformatted"><code>SELECT COUNT(*) AS UniqueTenantCustomers<br>FROM<br>(<br>    SELECT DISTINCT<br>        v.TenantId,<br>        v.CustomerId<br>    FROM<br>    (<br>        VALUES<br>            (1, 101),<br>            (1, 101),<br>            (2, 101),<br>            (2, 102)<br>    ) AS v(TenantId, CustomerId)<br>) AS d;</code></pre>



<p class="wp-block-paragraph">This returns three unique tenant/customer pairs.</p>



<p class="wp-block-paragraph">That distinction matters in a multi-tenant application where CustomerId is unique only within a tenant.</p>



<p class="wp-block-paragraph">Avoid joining values into a string to simulate a composite key. Different pairs can produce the same concatenated value, and NULL handling introduces additional complications.</p>



<p class="wp-block-paragraph">The derived-table approach includes distinct combinations containing NULL. Add explicit non-NULL filters if those combinations should be excluded.</p>



<h3 class="wp-block-heading">Count only qualifying customers</h3>



<pre class="wp-block-preformatted"><code>SELECT<br>    COUNT(<br>        CASE WHEN v.Status = 'Paid' THEN 1 END<br>    ) AS PaidOrders,<br>    COUNT(<br>        DISTINCT CASE<br>            WHEN v.Status = 'Paid' THEN v.CustomerId<br>        END<br>    ) AS UniquePayingCustomers<br>FROM<br>(<br>    VALUES<br>        (101, 'Paid'),<br>        (101, 'Paid'),<br>        (102, 'Pending'),<br>        (103, 'Paid')<br>) AS v(CustomerId, Status);</code></pre>



<p class="wp-block-paragraph">The results are three paid orders and two unique paying customers.</p>



<p class="wp-block-paragraph">CASE returns NULL for nonmatching rows, which COUNT ignores. Do not add <code>ELSE 0</code> to the first expression: zero is non-NULL and would count.</p>



<p class="wp-block-paragraph">Explore <a rel="noopener" target="_blank" href="https://sqlserverguides.com/case-statement-in-sql-server/">CASE expressions in SQL Server</a> for related conditional aggregates.</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">Pro Tip: I would keep composite business keys as separate columns throughout deduplication rather than invent a string encoding for them.</p>
</blockquote>



<h3 class="wp-block-heading">Performance, Large Counts, and Production Accuracy</h3>



<p class="wp-block-paragraph">COUNT DISTINCT often requires more work than counting rows because SQL Server must identify unique values. Execution plans may use sorting, hashing, or already ordered index data.</p>



<p class="wp-block-paragraph">A memory grant is workspace memory allocated to a query. If a sort or hash operation needs more than available, it may spill intermediate work to tempdb, SQL Server’s temporary workspace database.</p>



<h4 class="wp-block-heading">Tune the workload, not the spelling</h4>



<p class="wp-block-paragraph">Use this sequence:</p>



<ol class="wp-block-list">
<li>Confirm the business metric and filtering scope.</li>



<li>Inspect the actual execution plan.</li>



<li>Measure logical reads and elapsed time.</li>



<li>Check row estimates and statistics.</li>



<li>Evaluate supporting indexes.</li>



<li>Recheck performance under representative concurrency.</li>
</ol>



<p class="wp-block-paragraph">An index matching filters and counted keys can help, but its maintenance adds write and storage costs. COUNT(*) does not imply SQL Server must retrieve every column, and COUNT(1) is not a reliable performance improvement.</p>



<p class="wp-block-paragraph">Review <a rel="noopener" target="_blank" href="https://sqlserverguides.com/sql-query-optimization-tips/">SQL query optimization guidance</a> before increasing Azure compute capacity.</p>



<h4 class="wp-block-heading">Avoid integer overflow</h4>



<pre class="wp-block-preformatted"><code><em>-- Assumes the application table exists.</em><br>SELECT<br>    COUNT_BIG(*) AS OrderRows,<br>    COUNT_BIG(DISTINCT CustomerId) AS UniqueCustomers<br>FROM dbo.Orders;</code></pre>



<p class="wp-block-paragraph">COUNT_BIG returns bigint. COUNT uses int, whose maximum is 2,147,483,647; casting COUNT’s output afterward does not prevent overflow inside the aggregate.<a rel="noopener" target="_blank" href="https://learn.microsoft.com/en-us/sql/t-sql/functions/count-transact-sql?view=sql-server-ver17">learn.microsoft</a></p>



<h4 class="wp-block-heading">Consider approximate counts selectively</h4>



<p class="wp-block-paragraph">SQL Server 2019 and later, Azure SQL Database, and Managed Instance support APPROX_COUNT_DISTINCT. It uses less memory for large distinct-count workloads, with documented error of up to 2% within 97% probability. It is unsuitable when billing, reconciliation, or contractual reports require exact totals.<a rel="noopener" target="_blank" href="https://learn.microsoft.com/en-us/sql/t-sql/functions/approx-count-distinct-transact-sql?view=sql-server-ver17">learn.microsoft</a></p>



<h3 class="wp-block-heading">Frequently Asked Questions</h3>



<h4 class="wp-block-heading">Does COUNT(column) remove duplicates?</h4>



<p class="wp-block-paragraph">No. It counts every non-NULL occurrence, including repeated values. Add DISTINCT when you need unique non-NULL values.</p>



<h4 class="wp-block-heading">Is COUNT(*) different from COUNT(1)?</h4>



<p class="wp-block-paragraph">Both count qualifying rows because the constant 1 is never NULL. Use COUNT(*) to communicate row-counting intent; changing it to COUNT(1) is not a general tuning technique.</p>



<h4 class="wp-block-heading">Can SQL Server count distinct values across multiple columns?</h4>



<p class="wp-block-paragraph">Yes, by selecting distinct column combinations in a subquery and applying COUNT(*) outside it. SQL Server does not accept <code>COUNT(DISTINCT ColumnA, ColumnB)</code>.</p>



<h4 class="wp-block-heading">Can I use COUNT DISTINCT with OVER?</h4>



<p class="wp-block-paragraph">SQL Server does not support DISTINCT in COUNT’s window-function syntax. Aggregate distinct counts by the required grouping keys, then join those results back when row-level output is needed.</p>



<h4 class="wp-block-heading">Why is COUNT DISTINCT smaller than COUNT(*)?</h4>



<p class="wp-block-paragraph">Repeated values count once, and NULL values are excluded. Joins can also multiply rows without creating additional distinct entities, making the difference larger.</p>



<p class="wp-block-paragraph">You May Also Like</p>



<ul class="wp-block-list">
<li><a href="https://sqlserverguides.com/countbig-function-in-sql-server/" target="_blank" rel="noopener">COUNT_BIG examples in SQL Server</a></li>



<li><a href="https://sqlserverguides.com/sql-distinct/" target="_blank" rel="noopener">SQL DISTINCT and duplicate elimination</a></li>



<li><a href="https://sqlserverguides.com/how-to-find-duplicate-records-in-sql/" target="_blank" rel="noopener">Finding duplicate records in SQL</a></li>



<li><a href="https://sqlserverguides.com/sql-indexes-best-practices/" target="_blank" rel="noopener">SQL Server index best practices</a></li>



<li><a href="https://sqlserverguides.com/primary-key-vs-foreign-key/" target="_blank" rel="noopener">Primary keys vs. foreign keys</a></li>
</ul>



<p class="wp-block-paragraph">COUNT(*) measures rows, COUNT(column) measures non-NULL occurrences, and COUNT(DISTINCT column) measures unique non-NULL values. Define the metric and verify join behavior before tuning the query. I hope you found this article helpful.</p>



<p class="wp-block-paragraph"></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>SQL Server CEILING</title>
		<link>https://sqlserverguides.com/sql-server-ceiling/</link>
		
		<dc:creator><![CDATA[Bijay Kumar Sahoo]]></dc:creator>
		<pubDate>Tue, 10 Nov 2026 12:16:53 +0000</pubDate>
				<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[SQL Server CEILING]]></category>
		<guid isPermaLink="false">https://sqlserverguides.com/?p=24107</guid>

					<description><![CDATA[An order-processing report says 25 items fit into two cartons that each hold 12. The query runs without errors, but the warehouse needs three cartons. Integer division removed the remainder before the rounding function could see it. SQL Server CEILING returns the smallest whole-number value greater than or equal to its input. It helps calculate ... <a title="SQL Server CEILING" class="read-more" href="https://sqlserverguides.com/sql-server-ceiling/" aria-label="Read more about SQL Server CEILING">Read more</a>]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">An order-processing report says 25 items fit into two cartons that each hold 12. The query runs without errors, but the warehouse needs three cartons. Integer division removed the remainder before the rounding function could see it.</p>



<p class="wp-block-paragraph"><strong>SQL Server CEILING</strong> returns the smallest whole-number value greater than or equal to its input. It helps calculate cartons, result pages, billing increments, and capacity requirements—but only when the expression feeding it preserves the information you need.<a rel="noopener" target="_blank" href="https://learn.microsoft.com/en-us/sql/t-sql/functions/ceiling-transact-sql?view=sql-server-ver17"></a></p>



<p class="wp-block-paragraph">You’ll learn how to use CEILING, handle negative values and data types, and test rounding rules without modifying production data.</p>



<h2 class="wp-block-heading">How SQL Server CEILING Works</h2>



<p class="wp-block-paragraph">CEILING is a built-in mathematical function in T-SQL, Microsoft’s SQL dialect. It is available in SQL Server, Azure SQL Database, and Azure SQL Managed Instance. Its syntax accepts one numeric expression:</p>



<pre class="wp-block-preformatted"><code>CEILING(numeric_expression)</code></pre>



<p class="wp-block-paragraph">A numeric expression can be a number, column, variable, or calculation.</p>



<pre class="wp-block-preformatted"><code>SELECT<br>    CEILING(12.01) AS FractionalValue,<br>    CEILING(12.00) AS WholeValue,<br>    CEILING(0.01) AS SmallValue,<br>    CEILING(0) AS ZeroValue;</code></pre>



<p class="wp-block-paragraph">The numerical results are <code>13</code>, <code>12</code>, <code>1</code>, and <code>0</code>. A value already at a whole-number boundary stays unchanged. </p>



<p class="wp-block-paragraph">After running the query above, I got the expected output shown in the screenshot below.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="810" height="315" src="https://sqlserverguides.com/wp-content/uploads/2026/11/SQL-Server-CEILING.jpg" alt="SQL Server CEILING" class="wp-image-24108" srcset="https://sqlserverguides.com/wp-content/uploads/2026/11/SQL-Server-CEILING.jpg 810w, https://sqlserverguides.com/wp-content/uploads/2026/11/SQL-Server-CEILING-300x117.jpg 300w, https://sqlserverguides.com/wp-content/uploads/2026/11/SQL-Server-CEILING-766x298.jpg 766w" sizes="auto, (max-width: 810px) 100vw, 810px" /></figure>
</div>


<p class="wp-block-paragraph">“Rounds up” means toward positive infinity, not necessarily away from zero. This distinction becomes important with negative adjustments and credits.</p>



<pre class="wp-block-preformatted"><code>SELECT<br>    CEILING(-12.01) AS NegativeFraction,<br>    CEILING(-12.00) AS NegativeWhole,<br>    CEILING(-0.01) AS SmallNegative;</code></pre>



<p class="wp-block-paragraph">The results are <code>-12</code>, <code>-12</code>, and <code>0</code>. Negative twelve is greater than negative twelve point zero one, so it satisfies the ceiling rule.</p>



<p class="wp-block-paragraph">After running the query above, I got the expected output shown in the screenshot below.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="829" height="276" src="https://sqlserverguides.com/wp-content/uploads/2026/11/sql-server-ceiling-function.jpg" alt="sql server ceiling function" class="wp-image-24109" srcset="https://sqlserverguides.com/wp-content/uploads/2026/11/sql-server-ceiling-function.jpg 829w, https://sqlserverguides.com/wp-content/uploads/2026/11/sql-server-ceiling-function-766x255.jpg 766w, https://sqlserverguides.com/wp-content/uploads/2026/11/sql-server-ceiling-function-300x100.jpg 300w" sizes="auto, (max-width: 829px) 100vw, 829px" /></figure>
</div>


<p class="wp-block-paragraph"><a href="https://learn.microsoft.com/en-us/sql/t-sql/functions/ceiling-transact-sql?view=sql-server-ver17" target="_blank" rel="noopener"></a>CEILING returns a whole-number value, but that does not mean its SQL data type is always <code>int</code>.</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">Pro Tip: I would describe the rule as “the next whole value toward positive infinity” in specifications. That wording avoids confusion when negative amounts enter the system.</p>
</blockquote>



<h3 class="wp-block-heading">Compare SQL Server CEILING, FLOOR, and ROUND</h3>



<p class="wp-block-paragraph">These functions answer different questions:</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th class="has-text-align-left" data-align="left">Input</th><th class="has-text-align-left" data-align="left">CEILING</th><th class="has-text-align-left" data-align="left">FLOOR</th><th class="has-text-align-left" data-align="left">ROUND with length 0</th></tr></thead><tbody><tr><td>12.2</td><td>13</td><td>12</td><td>12</td></tr><tr><td>12.8</td><td>13</td><td>12</td><td>13</td></tr><tr><td>-12.2</td><td>-12</td><td>-13</td><td>-12</td></tr><tr><td>-12.8</td><td>-12</td><td>-13</td><td>-13</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">CEILING chooses the smallest whole value at or above the input. FLOOR chooses the largest whole value at or below it. ROUND selects a value at a specified precision and uses commercial rounding, with halfway values rounded away from zero.</p>



<pre class="wp-block-preformatted"><code>SELECT<br>    CEILING(12.2) AS RoundedUp,<br>    FLOOR(12.2) AS RoundedDown,<br>    ROUND(12.2, 0) AS RoundedNearest,<br>    ROUND(12.8, 0, 1) AS Truncated;</code></pre>



<p class="wp-block-paragraph">The last expression returns <code>12.0</code>. A nonzero third argument makes ROUND truncate rather than round.</p>



<p class="wp-block-paragraph">Use CEILING when a partial unit requires another complete unit. Use ROUND when the requirement is nearest-value rounding. Use FLOOR when the requirement is a lower boundary.</p>



<p class="wp-block-paragraph">For additional comparisons, see <a rel="noopener" target="_blank" href="https://sqlserverguides.com/sql-server-floor/">SQL Server FLOOR examples</a>.</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">Pro Tip: I would test positive and negative examples before choosing a rounding function. A rule that looks correct for sales charges can behave differently for refunds.</p>
</blockquote>



<h3 class="wp-block-heading">Avoid Integer Division Before Applying CEILING</h3>



<p class="wp-block-paragraph">The most common CEILING mistake happens before the function executes.</p>



<pre class="wp-block-preformatted"><code>SELECT CEILING(25 / 12) AS IncorrectCartons;</code></pre>



<p class="wp-block-paragraph">Both operands are integers. SQL Server evaluates <code>25 / 12</code> as <code>2</code>, discarding the fractional portion. CEILING then receives <code>2</code> and correctly returns <code>2</code>. The original remainder is already gone. See the screenshot below for reference.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="892" height="171" src="https://sqlserverguides.com/wp-content/uploads/2026/11/sql-server-ceiling-function-syntax.jpg" alt="sql server ceiling function syntax" class="wp-image-24110" srcset="https://sqlserverguides.com/wp-content/uploads/2026/11/sql-server-ceiling-function-syntax.jpg 892w, https://sqlserverguides.com/wp-content/uploads/2026/11/sql-server-ceiling-function-syntax-767x147.jpg 767w, https://sqlserverguides.com/wp-content/uploads/2026/11/sql-server-ceiling-function-syntax-300x58.jpg 300w" sizes="auto, (max-width: 892px) 100vw, 892px" /></figure>
</div>


<p class="wp-block-paragraph"><a href="https://learn.microsoft.com/en-us/sql/t-sql/language-elements/divide-transact-sql?view=sql-server-ver17" target="_blank" rel="noopener"></a>Convert an operand before division:</p>



<pre class="wp-block-preformatted"><code>SELECT<br>    CEILING(<br>        CAST(25 AS decimal(19, 4)) / 12<br>    ) AS RequiredCartons;</code></pre>



<p class="wp-block-paragraph">This returns <code>3</code>. See the screenshot below for reference.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="815" height="277" src="https://sqlserverguides.com/wp-content/uploads/2026/11/sql-server-ceiling-round-up.jpg" alt="sql server ceiling round up" class="wp-image-24111" srcset="https://sqlserverguides.com/wp-content/uploads/2026/11/sql-server-ceiling-round-up.jpg 815w, https://sqlserverguides.com/wp-content/uploads/2026/11/sql-server-ceiling-round-up-300x102.jpg 300w, https://sqlserverguides.com/wp-content/uploads/2026/11/sql-server-ceiling-round-up-768x261.jpg 768w" sizes="auto, (max-width: 815px) 100vw, 815px" /></figure>
</div>


<p class="wp-block-paragraph">Casting after division does not solve the problem:</p>



<pre class="wp-block-preformatted"><code>SELECT<br>    CEILING(<br>        CAST(25 / 12 AS decimal(19, 4))<br>    ) AS StillIncorrect;</code></pre>



<p class="wp-block-paragraph">The expression still returns <code>2</code>.</p>



<p class="wp-block-paragraph">Precision is the total number of digits a decimal type supports. Scale is the number of digits after the decimal point. Choose both deliberately, especially when intermediate calculations involve large quantities or very small fractions. SQL Server limits decimal precision to 38 digits and applies specific rules to arithmetic results.<a rel="noopener" target="_blank" href="https://learn.microsoft.com/en-us/sql/t-sql/data-types/precision-scale-and-length-transact-sql?view=sql-server-ver17"></a></p>



<p class="wp-block-paragraph">Review <a rel="noopener" target="_blank" href="https://sqlserverguides.com/cast-function-in-sql-server/">CAST examples in SQL Server</a> when designing numeric expressions.</p>



<p class="wp-block-paragraph">For extremely large integer counts, decimal division can itself round away a tiny remainder. An integer quotient-and-remainder approach may be preferable when exact grouping matters across the full supported range.</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">Pro Tip: I would inspect each operand’s data type before troubleshooting CEILING itself. The function cannot restore fractional information lost earlier in the expression.</p>
</blockquote>



<h3 class="wp-block-heading">Calculate Cartons With Safe Input Handling</h3>



<p class="wp-block-paragraph">Suppose an order line contains a quantity and a carton capacity. The business rule requires one additional carton whenever items remain.</p>



<p class="wp-block-paragraph">The following query uses inline sample rows. It does not create or change permanent tables.</p>



<pre class="wp-block-preformatted"><code>SELECT<br>    o.OrderLineId,<br>    o.Quantity,<br>    o.CartonCapacity,<br>    CASE<br>        WHEN o.Quantity IS NULL<br>             OR o.CartonCapacity IS NULL<br>            THEN 'Missing input'<br>        WHEN o.Quantity &lt; 0<br>             OR o.CartonCapacity &lt;= 0<br>            THEN 'Invalid input'<br>        ELSE 'Valid'<br>    END AS CalculationStatus,<br>    CASE<br>        WHEN o.Quantity >= 0<br>             AND o.CartonCapacity > 0<br>        THEN CEILING(<br>            CAST(o.Quantity AS decimal(19, 4))<br>            / NULLIF(o.CartonCapacity, 0)<br>        )<br>    END AS RequiredCartons<br>FROM<br>(<br>    VALUES<br>        (101, 25, 12),<br>        (102, 24, 12),<br>        (103, 0, 12),<br>        (104, 10, 0),<br>        (105, -1, 12),<br>        (106, NULL, 12)<br>) AS o(OrderLineId, Quantity, CartonCapacity);</code></pre>



<p class="wp-block-paragraph">The valid rows produce <code>3</code>, <code>2</code>, and <code>0</code> cartons. Invalid or missing inputs produce NULL, accompanied by an explanatory status.Check out the screenshot below for your reference.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="833" height="710" src="https://sqlserverguides.com/wp-content/uploads/2026/11/sql-server-ceiling-2-decimal-places.jpg" alt="sql server ceiling 2 decimal places" class="wp-image-24112" srcset="https://sqlserverguides.com/wp-content/uploads/2026/11/sql-server-ceiling-2-decimal-places.jpg 833w, https://sqlserverguides.com/wp-content/uploads/2026/11/sql-server-ceiling-2-decimal-places-767x654.jpg 767w, https://sqlserverguides.com/wp-content/uploads/2026/11/sql-server-ceiling-2-decimal-places-300x256.jpg 300w" sizes="auto, (max-width: 833px) 100vw, 833px" /></figure>
</div>


<p class="wp-block-paragraph">NULLIF converts a zero denominator to NULL. CASE expresses the broader business validation: a capacity must be positive, and an order quantity cannot be negative.</p>



<p class="wp-block-paragraph">For persistent order tables, enforce stable rules with <a rel="noopener" target="_blank" href="https://sqlserverguides.com/sql-constraints/">SQL Server constraints</a>. For example, capacity should usually be NOT NULL with a CHECK constraint requiring a positive value. A CHECK condition alone does not necessarily reject NULL.</p>



<p class="wp-block-paragraph">Keep return merchandise separate if negative quantities represent legitimate returns. Do not force two different workflows into one undocumented rounding rule.</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">Pro Tip: I would return a calculation status alongside NULL during validation. Otherwise, a dashboard can silently treat invalid source data as an ordinary missing result.</p>
</blockquote>



<h3 class="wp-block-heading">Calculate Result Pages and Batch Counts</h3>



<p class="wp-block-paragraph">CEILING is useful when an application displays a fixed number of records per page.</p>



<pre class="wp-block-preformatted"><code>DECLARE @TotalRows bigint = 101;<br>DECLARE @PageSize int = 25;<br><br>SELECT<br>    CEILING(<br>        CAST(@TotalRows AS decimal(28, 6))<br>        / NULLIF(@PageSize, 0)<br>    ) AS TotalPages;</code></pre>



<p class="wp-block-paragraph">This returns <code>5</code>.</p>



<p class="wp-block-paragraph">Validate that total rows are nonnegative and page size is positive before running the calculation. NULLIF prevents a zero division, but it does not make a negative page size meaningful.</p>



<h3 class="wp-block-heading">Use exact integer arithmetic for large counts</h3>



<p class="wp-block-paragraph">For nonnegative integer totals and a positive page size, quotient-and-remainder arithmetic avoids decimal precision concerns:</p>



<pre class="wp-block-preformatted"><code>DECLARE @TotalRows bigint = 101;<br>DECLARE @PageSize bigint = 25;<br><br>IF @TotalRows IS NULL<br>   OR @TotalRows &lt; 0<br>   OR @PageSize IS NULL<br>   OR @PageSize &lt;= 0<br>BEGIN<br>    THROW 50001,<br>        'Total rows must be nonnegative; page size must be positive.',<br>        1;<br>END;<br><br>SELECT<br>    (@TotalRows / @PageSize)<br>    + CASE<br>        WHEN @TotalRows % @PageSize = 0 THEN 0<br>        ELSE 1<br>      END AS TotalPages;</code></pre>



<p class="wp-block-paragraph">The <code>%</code> operator returns the remainder. This produces the same ceiling-of-division result under the stated input rules.</p>



<p class="wp-block-paragraph">Avoid casually using <code>(total + size - 1) / size</code>: the addition can overflow near the data type’s upper limit.</p>



<p class="wp-block-paragraph">Also distinguish page counting from efficient pagination. Calculating five pages does not establish a stable row order or make a large OFFSET query inexpensive.</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">Pro Tip: I would define whether an empty result has zero pages or one empty display page. That is an application decision, not something CEILING should decide accidentally.</p>
</blockquote>



<h3 class="wp-block-heading">Round Billing Values to an Increment</h3>



<p class="wp-block-paragraph">CEILING accepts one argument; it has no decimal-places parameter. To round toward positive infinity at a particular increment, divide by the increment, apply CEILING, and multiply back.</p>



<p class="wp-block-paragraph">For fifteen-minute billing:</p>



<pre class="wp-block-preformatted"><code>DECLARE @Minutes decimal(12, 2) = 31.00;<br>DECLARE @Increment decimal(12, 2) = 15.00;<br><br>SELECT<br>    CAST(<br>        CEILING(@Minutes / NULLIF(@Increment, 0))<br>        * @Increment<br>        AS decimal(12, 2)<br>    ) AS BillableMinutes;</code></pre>



<p class="wp-block-paragraph">The result is <code>45.00</code>.</p>



<p class="wp-block-paragraph">Thirty minutes stays at thirty. Any positive amount beyond thirty requires another increment.</p>



<h3 class="wp-block-heading">Round upward to cents</h3>



<pre class="wp-block-preformatted">sql<code>DECLARE @Amount decimal(12, 4) = 19.2301;

SELECT
    CAST(
        CEILING(@Amount * 100.0) / 100.0
        AS decimal(12, 2)
    ) AS AmountRoundedUp;</code></pre>



<p class="wp-block-paragraph">This returns <code>19.24</code>.</p>



<p class="wp-block-paragraph">For a negative amount of <code>-19.2301</code>, the same expression returns <code>-19.23</code>, not <code>-19.24</code>. If a contract requires rounding negative values away from zero, that is a different rule.</p>



<p class="wp-block-paragraph">Use decimal inputs for contractual calculations. Float and real are approximate numeric types; small representation differences around boundaries can produce an unexpected extra increment.</p>



<p class="wp-block-paragraph">Also decide whether rounding applies per line item or after aggregation. Rounding two separate amounts upward can produce a different total from rounding their sum once.</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">Pro Tip: I would document the increment, sign rule, and rounding stage together. Those three decisions determine the invoice, not just the selected SQL function.</p>
</blockquote>



<h2 class="wp-block-heading">Inspect Return Types and Prevent Overflow</h2>



<p class="wp-block-paragraph">CEILING’s return type depends on its input. Integer inputs return integer-family results, while float inputs return float. Money inputs return money. Decimal behavior should be checked against the target engine and its documented behavior.<a rel="noopener" target="_blank" href="https://learn.microsoft.com/en-us/sql/t-sql/functions/ceiling-transact-sql?view=sql-server-ver17"></a></p>



<p class="wp-block-paragraph">Inspect the metadata directly:</p>



<pre class="wp-block-preformatted"><code>DECLARE @Value decimal(12, 4) = 19.2301;<br><br>SELECT<br>    CEILING(@Value) AS RoundedValue,<br>    SQL_VARIANT_PROPERTY(<br>        CEILING(@Value), 'BaseType'<br>    ) AS ResultType,<br>    SQL_VARIANT_PROPERTY(<br>        CEILING(@Value), 'Precision'<br>    ) AS ResultPrecision,<br>    SQL_VARIANT_PROPERTY(<br>        CEILING(@Value), 'Scale'<br>    ) AS ResultScale;</code></pre>



<p class="wp-block-paragraph">This reports the actual result metadata from your database rather than relying on how a query grid displays the value.</p>



<p class="wp-block-paragraph">An explicit final CAST gives an API or report a defined output type, but it can overflow if the value exceeds that type’s range:</p>



<pre class="wp-block-preformatted"><code>SELECT<br>    TRY_CONVERT(<br>        int,<br>        CEILING(<br>            CAST(2147483647.1 AS decimal(20, 1))<br>        )<br>    ) AS IntResult;</code></pre>



<p class="wp-block-paragraph">The ceiling is <code>2147483648</code>, which exceeds the maximum int value. TRY_CONVERT therefore returns NULL.</p>



<p class="wp-block-paragraph">Do not silently accept that NULL in a billing or inventory process. Record or reject the out-of-range value.</p>



<p class="wp-block-paragraph">See <a rel="noopener" target="_blank" href="https://sqlserverguides.com/tryconvert-function-in-sql-server/">TRY_CONVERT examples</a> for controlled conversion handling.</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">Pro Tip: I would test the maximum supported input and the resulting output type together. A valid intermediate calculation can still fail when assigned to a narrower column.</p>
</blockquote>



<h3 class="wp-block-heading">Frequently Asked Questions</h3>



<h4 class="wp-block-heading">What does CEILING do in SQL Server?</h4>



<p class="wp-block-paragraph">It returns the smallest whole-number value greater than or equal to its input. For example, <code>CEILING(7.01)</code> returns <code>8</code>, while <code>CEILING(7.00)</code> returns <code>7</code>.<a rel="noopener" target="_blank" href="https://learn.microsoft.com/en-us/sql/t-sql/functions/ceiling-transact-sql?view=sql-server-ver17"></a></p>



<h4 class="wp-block-heading">Why does CEILING return 2 instead of 3?</h4>



<p class="wp-block-paragraph">Integer division may have removed the fractional portion before CEILING ran. Convert an operand before division, such as <code>CEILING(CAST(25 AS decimal(19,4)) / 12)</code>.<a rel="noopener" target="_blank" href="https://learn.microsoft.com/en-us/sql/t-sql/language-elements/divide-transact-sql?view=sql-server-ver17"></a></p>



<h4 class="wp-block-heading">How does CEILING handle negative numbers?</h4>



<p class="wp-block-paragraph">It moves toward positive infinity. Therefore, <code>CEILING(-7.8)</code> returns <code>-7</code>, not <code>-8</code>. Use a different expression if the business rule requires rounding away from zero.</p>



<h4 class="wp-block-heading">Can CEILING round to two decimal places?</h4>



<p class="wp-block-paragraph">Not directly; it accepts only one argument. Scale the value, apply CEILING, and scale it back, while checking precision and the required negative-number behavior.</p>



<h4 class="wp-block-heading">Does CEILING always return an int?</h4>



<p class="wp-block-paragraph">No. The result type depends on the input type, and a whole-number value can still have a decimal, money, or float representation. Inspect metadata and cast explicitly when consumers require a particular type.<a rel="noopener" target="_blank" href="https://learn.microsoft.com/en-us/sql/t-sql/functions/ceiling-transact-sql?view=sql-server-ver17"></a></p>



<p class="wp-block-paragraph">You May Also Like</p>



<ul class="wp-block-list">
<li><a href="https://sqlserverguides.com/sql-null/" target="_blank" rel="noopener">How SQL NULL values affect calculations</a></li>



<li><a href="https://sqlserverguides.com/case-statement-in-sql-server/" target="_blank" rel="noopener">Using CASE expressions for business rules</a></li>



<li><a href="https://sqlserverguides.com/sql-query-optimization-tips/" target="_blank" rel="noopener">SQL Server query optimization tips</a></li>



<li><a href="https://sqlserverguides.com/how-to-use-sum-function-in-sql-server/" target="_blank" rel="noopener">Calculating totals with SUM</a></li>



<li><a href="https://sqlserverguides.com/sql-database-design-best-practices/" target="_blank" rel="noopener">SQL database design best practices</a></li>
</ul>



<p class="wp-block-paragraph">SQL Server CEILING helps calculate whole-unit requirements, page counts, and upward billing increments. Preserve the necessary precision, define negative-value behavior, and test boundaries before deploying the calculation. I hope you found this article helpful.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>SQL Server NULLIF: Syntax, Examples</title>
		<link>https://sqlserverguides.com/sql-server-nullif/</link>
		
		<dc:creator><![CDATA[Bijay Kumar Sahoo]]></dc:creator>
		<pubDate>Tue, 10 Nov 2026 09:53:20 +0000</pubDate>
				<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[SQL Server NULLIF]]></category>
		<guid isPermaLink="false">https://sqlserverguides.com/?p=24097</guid>

					<description><![CDATA[SQL Server NULLIF compares two expressions and returns NULL when they are equal. Otherwise, it returns the first expression. That makes it useful for protecting division, normalizing placeholder values, and excluding specific values from calculations. You’ll learn how to use NULLIF correctly, control data types, combine it with other expressions, and test reporting logic without ... <a title="SQL Server NULLIF: Syntax, Examples" class="read-more" href="https://sqlserverguides.com/sql-server-nullif/" aria-label="Read more about SQL Server NULLIF: Syntax, Examples">Read more</a>]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph"><strong>SQL Server NULLIF</strong> compares two expressions and returns NULL when they are equal. Otherwise, it returns the first expression. That makes it useful for protecting division, normalizing placeholder values, and excluding specific values from calculations.<a rel="noopener" target="_blank" href="https://learn.microsoft.com/en-us/sql/t-sql/language-elements/nullif-transact-sql?view=sql-server-ver17"></a></p>



<p class="wp-block-paragraph">You’ll learn how to use NULLIF correctly, control data types, combine it with other expressions, and test reporting logic without changing production data.</p>



<h2 class="wp-block-heading">How SQL Server NULLIF Works</h2>



<p class="wp-block-paragraph">NULLIF is a built-in T-SQL function. T-SQL is Microsoft’s SQL dialect, used by SQL Server, Azure SQL Database, and Azure SQL Managed Instance.</p>



<p class="wp-block-paragraph">Its syntax takes exactly two arguments:</p>



<pre class="wp-block-preformatted"><code>NULLIF(expression1, expression2)</code></pre>



<p class="wp-block-paragraph">Each argument is a scalar expression: a value such as a column, variable, literal, or calculation.</p>



<p class="wp-block-paragraph">The behavior is straightforward:</p>



<pre class="wp-block-preformatted"><code>SELECT<br>    NULLIF(10, 10) AS EqualValues,<br>    NULLIF(10, 20) AS DifferentValues,<br>    NULLIF(0, 0) AS ZeroValue;</code></pre>



<p class="wp-block-paragraph">After running the query above, I got the expected output shown in the screenshot below.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="801" height="282" src="https://sqlserverguides.com/wp-content/uploads/2026/11/SQL-Server-NULLIF.jpg" alt="SQL Server NULLIF" class="wp-image-24098" srcset="https://sqlserverguides.com/wp-content/uploads/2026/11/SQL-Server-NULLIF.jpg 801w, https://sqlserverguides.com/wp-content/uploads/2026/11/SQL-Server-NULLIF-767x270.jpg 767w, https://sqlserverguides.com/wp-content/uploads/2026/11/SQL-Server-NULLIF-300x106.jpg 300w" sizes="auto, (max-width: 801px) 100vw, 801px" /></figure>
</div>


<p class="wp-block-paragraph">Expected results:</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th class="has-text-align-left" data-align="left">EqualValues</th><th class="has-text-align-left" data-align="left">DifferentValues</th><th class="has-text-align-left" data-align="left">ZeroValue</th></tr></thead><tbody><tr><td>NULL</td><td>10</td><td>NULL</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">The function returns the first expression when the comparison is not true. It does not return a Boolean value or the second expression. Its result has the data type of the first expression.<a rel="noopener" target="_blank" href="https://learn.microsoft.com/en-us/sql/t-sql/language-elements/nullif-transact-sql?view=sql-server-ver17"></a></p>



<p class="wp-block-paragraph">NULL represents missing, unknown, or inapplicable information. It is not the same as zero or an empty string. For background, see <a rel="noopener" target="_blank" href="https://sqlserverguides.com/sql-null/">how SQL NULL values work</a>.</p>



<h4 class="wp-block-heading">The equivalent CASE expression</h4>



<p class="wp-block-paragraph">You can express the same basic logic with CASE:</p>



<pre class="wp-block-preformatted"><code>DECLARE @Actual int = 10;<br>DECLARE @Expected int = 10;<br><br>SELECT<br>    CASE<br>        WHEN @Actual = @Expected THEN NULL<br>        ELSE @Actual<br>    END AS ComparisonResult;</code></pre>



<p class="wp-block-paragraph">This returns NULL because the values match. NULLIF is the concise choice for one equality comparison; CASE is clearer when several conditions require different results. After running the query above, I got the expected output shown in the screenshot below.</p>



<p class="wp-block-paragraph"><a href="https://learn.microsoft.com/en-us/sql/t-sql/language-elements/nullif-transact-sql?view=sql-server-ver17" target="_blank" rel="noopener"></a></p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="870" height="417" src="https://sqlserverguides.com/wp-content/uploads/2026/11/nullif-sql-server.jpg" alt="nullif sql server" class="wp-image-24099" srcset="https://sqlserverguides.com/wp-content/uploads/2026/11/nullif-sql-server.jpg 870w, https://sqlserverguides.com/wp-content/uploads/2026/11/nullif-sql-server-300x144.jpg 300w, https://sqlserverguides.com/wp-content/uploads/2026/11/nullif-sql-server-768x368.jpg 768w" sizes="auto, (max-width: 870px) 100vw, 870px" /></figure>
</div>


<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">Pro Tip: I would use NULLIF for a single “turn this matching value into NULL” rule and switch to CASE when the business rule needs explanation.</p>
</blockquote>



<h3 class="wp-block-heading">Prevent Divide-by-Zero Errors With SQL Server NULLIF</h3>



<p class="wp-block-paragraph">The common safe-division pattern is:</p>



<pre class="wp-block-preformatted"><code>numerator / NULLIF(denominator, 0)</code></pre>



<p class="wp-block-paragraph">When the denominator is zero, NULLIF returns NULL. Division by NULL produces NULL instead of attempting division by zero.</p>



<h3 class="wp-block-heading">Run a self-contained sales example</h3>



<p class="wp-block-paragraph">This query uses inline sample rows, so it does not create or modify a permanent table:</p>



<pre class="wp-block-preformatted"><code>SELECT<br>    s.ProductId,<br>    s.Revenue,<br>    s.UnitsSold,<br>    CAST(<br>        s.Revenue / NULLIF(s.UnitsSold, 0)<br>        AS decimal(19, 2)<br>    ) AS RevenuePerUnit<br>FROM<br>(<br>    VALUES<br>        (101, CAST(1200.00 AS decimal(19, 2)), 12),<br>        (102, CAST(450.00 AS decimal(19, 2)), 0),<br>        (103, CAST(0.00 AS decimal(19, 2)), 5),<br>        (104, CAST(300.00 AS decimal(19, 2)), NULL)<br>) AS s(ProductId, Revenue, UnitsSold);</code></pre>



<p class="wp-block-paragraph">The calculation returns:</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th class="has-text-align-left" data-align="left">ProductId</th><th class="has-text-align-left" data-align="left">RevenuePerUnit</th></tr></thead><tbody><tr><td>101</td><td>100.00</td></tr><tr><td>102</td><td>NULL</td></tr><tr><td>103</td><td>0.00</td></tr><tr><td>104</td><td>NULL</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">After running the query above, I got the expected output shown in the screenshot below.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="829" src="https://sqlserverguides.com/wp-content/uploads/2026/11/nullif-sql-server-example-1024x829.jpg" alt="nullif sql server example" class="wp-image-24100" srcset="https://sqlserverguides.com/wp-content/uploads/2026/11/nullif-sql-server-example-1024x829.jpg 1024w, https://sqlserverguides.com/wp-content/uploads/2026/11/nullif-sql-server-example-300x243.jpg 300w, https://sqlserverguides.com/wp-content/uploads/2026/11/nullif-sql-server-example-767x621.jpg 767w, https://sqlserverguides.com/wp-content/uploads/2026/11/nullif-sql-server-example.jpg 1028w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p class="wp-block-paragraph">The distinction matters. Product 103 has a valid zero revenue-per-unit result. Products 102 and 104 do not have a usable denominator.</p>



<p class="wp-block-paragraph">NULLIF protects the calculation but does not explain why units are zero or missing. Investigate those rows separately if they indicate a failed import or incomplete transaction.</p>



<h3 class="wp-block-heading">Protect the denominator directly</h3>



<p class="wp-block-paragraph">Do not rely exclusively on a WHERE condition such as <code>UnitsSold &lt;&gt; 0</code> to protect an otherwise unsafe calculation. SQL Server can choose an execution order different from the order in which query clauses appear. Protect the expression itself.<a rel="noopener" target="_blank" href="https://learn.microsoft.com/en-us/answers/a/444303"></a></p>



<p class="wp-block-paragraph">Similarly, placing NULLIF around an entire division is too late:</p>



<pre class="wp-block-preformatted"><code><em>-- Protect the denominator, not the completed division.</em><br>SELECT 100.0 / NULLIF(0, 0) AS SafeResult;</code></pre>



<p class="wp-block-paragraph">After running the query above, I got the expected output shown in the screenshot below.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="860" height="187" src="https://sqlserverguides.com/wp-content/uploads/2026/11/sql-server-nullif-function.jpg" alt="sql server nullif function" class="wp-image-24101" srcset="https://sqlserverguides.com/wp-content/uploads/2026/11/sql-server-nullif-function.jpg 860w, https://sqlserverguides.com/wp-content/uploads/2026/11/sql-server-nullif-function-300x65.jpg 300w, https://sqlserverguides.com/wp-content/uploads/2026/11/sql-server-nullif-function-763x166.jpg 763w" sizes="auto, (max-width: 860px) 100vw, 860px" /></figure>
</div>


<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">Pro Tip: I would keep a zero-denominator test case beside every ratio calculation. A query that works only with normal data is not adequately tested.</p>
</blockquote>



<h3 class="wp-block-heading">Control Data Types Before Dividing</h3>



<p class="wp-block-paragraph">NULLIF does not automatically convert integer arithmetic into decimal arithmetic.</p>



<pre class="wp-block-preformatted"><code>SELECT<br>    5 / NULLIF(2, 0) AS IntegerResult,<br>    CAST(5 AS decimal(19, 4))<br>        / NULLIF(2, 0) AS DecimalResult;</code></pre>



<p class="wp-block-paragraph">After running the query above, I got the expected output shown in the screenshot below.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="829" height="293" src="https://sqlserverguides.com/wp-content/uploads/2026/11/nullif-sql-example.jpg" alt="nullif sql example" class="wp-image-24102" srcset="https://sqlserverguides.com/wp-content/uploads/2026/11/nullif-sql-example.jpg 829w, https://sqlserverguides.com/wp-content/uploads/2026/11/nullif-sql-example-767x271.jpg 767w, https://sqlserverguides.com/wp-content/uploads/2026/11/nullif-sql-example-300x106.jpg 300w" sizes="auto, (max-width: 829px) 100vw, 829px" /></figure>
</div>


<p class="wp-block-paragraph">The first expression returns <code>2</code>. The second represents <code>2.5</code>, with its displayed scale determined by SQL Server’s decimal rules.</p>



<p class="wp-block-paragraph">Integer division discards the fractional portion. Casting the result afterward cannot recover it:</p>



<pre class="wp-block-preformatted"><code>SELECT<br>    CAST(5 / NULLIF(2, 0) AS decimal(19, 2))<br>        AS TooLate,<br>    CAST(<br>        CAST(5 AS decimal(19, 4)) / NULLIF(2, 0)<br>        AS decimal(19, 2)<br>    ) AS CorrectResult;</code></pre>



<p class="wp-block-paragraph">After running the query above, I got the expected output shown in the screenshot below.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="966" height="401" src="https://sqlserverguides.com/wp-content/uploads/2026/11/sql-server-nullif-divide-by-zero.jpg" alt="sql server nullif divide by zero" class="wp-image-24103" srcset="https://sqlserverguides.com/wp-content/uploads/2026/11/sql-server-nullif-divide-by-zero.jpg 966w, https://sqlserverguides.com/wp-content/uploads/2026/11/sql-server-nullif-divide-by-zero-300x125.jpg 300w, https://sqlserverguides.com/wp-content/uploads/2026/11/sql-server-nullif-divide-by-zero-766x318.jpg 766w" sizes="auto, (max-width: 966px) 100vw, 966px" /></figure>
</div>


<p class="wp-block-paragraph">This returns <code>2.00</code> and <code>2.50</code>. Cast an operand before division, then cast the final value if your output requires a specific scale.<a rel="noopener" target="_blank" href="https://learn.microsoft.com/tr-tr/archive/msdn-technet-forums/f0941052-2a48-4bc9-8150-07128c16b794"></a></p>



<p class="wp-block-paragraph">For more examples, see <a rel="noopener" target="_blank" href="https://sqlserverguides.com/cast-function-in-sql-server/">using CAST in SQL Server</a>.</p>



<h3 class="wp-block-heading">Avoid implicit conversion surprises</h3>



<p class="wp-block-paragraph">An implicit conversion happens when SQL Server changes a data type automatically.</p>



<p class="wp-block-paragraph">Although NULLIF returns the first argument’s type, comparing its arguments can require conversion:</p>



<pre class="wp-block-preformatted"><code>SELECT NULLIF('10', 10) AS ConvertedComparison;</code></pre>



<p class="wp-block-paragraph">The numeric comparison succeeds and returns NULL. Replacing <code>'10'</code> with <code>'unknown'</code> can cause a conversion error.</p>



<p class="wp-block-paragraph">Use compatible types deliberately. For text imported from external systems, validate and convert it before using it in numeric calculations.</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">Pro Tip: I would specify decimal precision and scale explicitly for financial ratios rather than let a chain of implicit conversions define the output contract.</p>
</blockquote>



<h3 class="wp-block-heading">Clean Blank Strings and Placeholder Values</h3>



<p class="wp-block-paragraph">NULLIF can normalize a known placeholder into NULL without updating stored data.</p>



<pre class="wp-block-preformatted"><code>SELECT<br>    c.CustomerId,<br>    NULLIF(LTRIM(RTRIM(c.Phone)), '') AS CleanPhone<br>FROM<br>(<br>    VALUES<br>        (1, CAST(' 555-0101 ' AS varchar(30))),<br>        (2, CAST('' AS varchar(30))),<br>        (3, CAST('   ' AS varchar(30))),<br>        (4, CAST(NULL AS varchar(30)))<br>) AS c(CustomerId, Phone);</code></pre>



<p class="wp-block-paragraph">LTRIM and RTRIM remove ordinary leading and trailing spaces. NULLIF then converts the remaining empty string to NULL.</p>



<p class="wp-block-paragraph">The first row returns <code>555-0101</code>; the others return NULL.</p>



<p class="wp-block-paragraph">On SQL Server 2017 and later, basic TRIM can replace the nested trimming functions. Review <a rel="noopener" target="_blank" href="https://sqlserverguides.com/trim-function-in-sql-server/">SQL Server TRIM examples</a> before using version-specific syntax.</p>



<h3 class="wp-block-heading">Normalize placeholders carefully</h3>



<p class="wp-block-paragraph">A source system might use <code>'N/A'</code> for missing information:</p>



<pre class="wp-block-preformatted"><code>DECLARE @Reference varchar(30) = 'N/A';<br><br>SELECT NULLIF(@Reference, 'N/A') AS CleanReference;</code></pre>



<p class="wp-block-paragraph">This returns NULL, but the comparison follows SQL Server’s string-comparison rules. Collation controls characteristics such as case sensitivity; ordinary equality comparisons also commonly ignore trailing spaces.</p>



<p class="wp-block-paragraph">Trimming ordinary spaces does not remove every whitespace character. Tabs, line breaks, and nonbreaking spaces may require separate handling.</p>



<p class="wp-block-paragraph">Preview normalization with SELECT before considering stored-data changes. A legitimate identifier containing a placeholder-like value should not disappear because a cleanup rule was too broad.</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">Pro Tip: I would normalize a value only after confirming what the source system means by it. “Looks empty” and “means missing” are different requirements.</p>
</blockquote>



<h3 class="wp-block-heading">Combine NULLIF With COALESCE or ISNULL</h3>



<p class="wp-block-paragraph">NULLIF creates NULL when values match. COALESCE and ISNULL supply replacements when an expression is already NULL.</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th class="has-text-align-left" data-align="left">Expression</th><th class="has-text-align-left" data-align="left">Purpose</th></tr></thead><tbody><tr><td><code>NULLIF(a, b)</code></td><td>Return NULL when <code>a = b</code>; otherwise return <code>a</code></td></tr><tr><td><code>COALESCE(a, b, c)</code></td><td>Return the first non-NULL expression</td></tr><tr><td><code>ISNULL(a, b)</code></td><td>Replace NULL in <code>a</code> with <code>b</code></td></tr><tr><td><code>CASE</code></td><td>Apply conditional rules with separate branches</td></tr></tbody></table></figure>



<h3 class="wp-block-heading">Supply a reporting fallback</h3>



<pre class="wp-block-preformatted"><code>DECLARE @Revenue decimal(19, 2) = 450.00;<br>DECLARE @Units int = 0;<br><br>SELECT<br>    COALESCE(<br>        CAST(<br>            @Revenue / NULLIF(@Units, 0)<br>            AS decimal(19, 2)<br>        ),<br>        CAST(0 AS decimal(19, 2))<br>    ) AS DisplayRevenuePerUnit;</code></pre>



<p class="wp-block-paragraph">NULLIF protects the denominator. COALESCE then replaces the undefined result with zero.</p>



<p class="wp-block-paragraph">That fallback is a business decision, not a technical requirement. If zero means “valid result of zero,” using it for undefined ratios makes the report ambiguous.</p>



<p class="wp-block-paragraph">Often, keeping NULL and adding a separate status column is clearer.</p>



<p class="wp-block-paragraph">Learn more about <a rel="noopener" target="_blank" href="https://sqlserverguides.com/sql-server-coalesce-function/">SQL Server COALESCE</a> and <a rel="noopener" target="_blank" href="https://sqlserverguides.com/isnull-function-in-sql-server/">ISNULL replacement behavior</a>.</p>



<p class="wp-block-paragraph">ISNULL generally uses the first argument’s data type, while COALESCE resolves its result type using data-type precedence. Explicit casts help avoid unexpected conversion or truncation.<a rel="noopener" target="_blank" href="https://learn.microsoft.com/en-us/sql/t-sql/functions/isnull-transact-sql?view=sql-server-ver17"></a></p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">Pro Tip: I would preserve NULL in the calculation layer and apply presentation defaults only where the reporting requirement explicitly calls for them.</p>
</blockquote>



<h3 class="wp-block-heading">Use NULLIF in Averages and Aggregated Ratios</h3>



<p class="wp-block-paragraph">Aggregate functions summarize multiple rows. AVG ignores NULL inputs, so replacing selected values with NULL changes which rows contribute.</p>



<h3 class="wp-block-heading">Exclude zeros only when the business rule allows it</h3>



<pre class="wp-block-preformatted"><code>SELECT<br>    AVG(v.Amount) AS AverageIncludingZero,<br>    AVG(NULLIF(v.Amount, 0)) AS AverageExcludingZero<br>FROM<br>(<br>    VALUES<br>        (CAST(100.00 AS decimal(19, 2))),<br>        (CAST(0.00 AS decimal(19, 2))),<br>        (CAST(200.00 AS decimal(19, 2))),<br>        (CAST(NULL AS decimal(19, 2)))<br>) AS v(Amount);</code></pre>



<p class="wp-block-paragraph">The averages are <code>100</code> and <code>150</code>, respectively.</p>



<p class="wp-block-paragraph">The second calculation excludes zero. That is appropriate only if zero is a documented placeholder, not a genuine observation. Microsoft’s NULLIF examples demonstrate this pattern with budget data.<a rel="noopener" target="_blank" href="http://learn.microsoft.com/en-us/sql/t-sql/language-elements/nullif-transact-sql?view=sql-server-ver15"></a></p>



<p class="wp-block-paragraph">See <a rel="noopener" target="_blank" href="https://sqlserverguides.com/how-to-use-avg-function-in-sql-server/">how AVG works in SQL Server</a> for related aggregate behavior.</p>



<h3 class="wp-block-heading">Distinguish overall ratios from average row ratios</h3>



<pre class="wp-block-preformatted"><code>SELECT<br>    SUM(v.Revenue) / NULLIF(SUM(v.Units), 0)<br>        AS OverallRevenuePerUnit,<br>    AVG(v.Revenue / NULLIF(v.Units, 0))<br>        AS AverageRowRevenuePerUnit<br>FROM<br>(<br>    VALUES<br>        (CAST(100.00 AS decimal(19, 2)), 1),<br>        (CAST(900.00 AS decimal(19, 2)), 90)<br>) AS v(Revenue, Units);</code></pre>



<p class="wp-block-paragraph">The overall ratio is approximately <code>10.99</code>; the average row ratio is <code>55</code>.</p>



<p class="wp-block-paragraph">Neither is automatically wrong. They answer different questions: total revenue per total unit versus the average of row-level rates.</p>



<p class="wp-block-paragraph">Also decide how rows with missing or zero units contribute to the numerator. Protecting a denominator does not resolve mismatched populations.</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">Pro Tip: I would confirm the metric definition with a two-row example before implementing it across millions of transactions.</p>
</blockquote>



<h3 class="wp-block-heading">Frequently Asked Questions</h3>



<h4 class="wp-block-heading">What does NULLIF return in SQL Server?</h4>



<p class="wp-block-paragraph">It returns NULL when its two expressions compare equal. Otherwise, it returns the first expression, using that expression’s data type.<a rel="noopener" target="_blank" href="https://learn.microsoft.com/en-us/sql/t-sql/language-elements/nullif-transact-sql?view=sql-server-ver17"></a></p>



<h4 class="wp-block-heading">What happens when NULLIF receives NULL?</h4>



<p class="wp-block-paragraph"><code>NULLIF(CAST(NULL AS int), 0)</code> returns NULL. <code>NULLIF(5, CAST(NULL AS int))</code> returns <code>5</code>, because comparison with NULL is not true. Use IS NULL to test explicitly for missing values.</p>



<h4 class="wp-block-heading">Does NULLIF prevent every divide-by-zero error?</h4>



<p class="wp-block-paragraph">It protects a division by wrapping the denominator and converting 0 to NULL. Nested calculations may contain other unprotected denominators, so inspect each division separately.</p>



<h4 class="wp-block-heading">Is NULLIF the same as ISNULL?</h4>



<p class="wp-block-paragraph">No. NULLIF turns a matching value into NULL; ISNULL replaces an existing NULL with another value. They solve opposite parts of a missing-data workflow.</p>



<h4 class="wp-block-heading">Can NULLIF change stored table data?</h4>



<p class="wp-block-paragraph">Not by itself. In a SELECT query, it changes the returned expression, not the stored column. An INSERT or UPDATE using NULLIF can persist its result, so review write operations separately.</p>



<p class="wp-block-paragraph">You May Also Like</p>



<ul class="wp-block-list">
<li><a href="https://sqlserverguides.com/nullif-vs-coalesce/" target="_blank" rel="noopener">NULLIF vs. COALESCE in SQL Server</a></li>



<li><a href="https://sqlserverguides.com/case-statement-in-sql-server/" target="_blank" rel="noopener">Writing CASE expressions in SQL Server</a></li>



<li><a href="https://sqlserverguides.com/tryconvert-function-in-sql-server/" target="_blank" rel="noopener">Using TRY_CONVERT for safer conversions</a></li>



<li><a href="https://sqlserverguides.com/sql-indexes-best-practices/" target="_blank" rel="noopener">SQL Server index best practices</a></li>



<li><a href="https://sqlserverguides.com/sql-database-design-best-practices/" target="_blank" rel="noopener">SQL database design best practices</a></li>



<li><a href="https://sqlserverguides.com/sql-server-ceiling/" target="_blank" rel="noreferrer noopener">SQL Server CEILING</a></li>
</ul>



<p class="wp-block-paragraph">SQL Server NULLIF helps you protect division, normalize known placeholders, and control which values enter aggregate calculations. Preserve the difference between zero and unknown, then verify both numerical results and query behavior before deployment. I hope you found this article helpful.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How to Convert Rows Into Columns in SQL</title>
		<link>https://sqlserverguides.com/how-to-convert-rows-into-columns-in-sql/</link>
		
		<dc:creator><![CDATA[Bijay Kumar Sahoo]]></dc:creator>
		<pubDate>Wed, 04 Nov 2026 07:25:24 +0000</pubDate>
				<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[How to Convert Rows Into Columns in SQL]]></category>
		<guid isPermaLink="false">https://sqlserverguides.com/?p=24083</guid>

					<description><![CDATA[A finance team once asked me for a report that looked simple on paper: one line per product, with four columns for Q1 through Q4. Their database stored sales the way databases should, with one row per product per quarter. An analyst had been exporting the data to Excel and rebuilding the layout by hand ... <a title="How to Convert Rows Into Columns in SQL" class="read-more" href="https://sqlserverguides.com/how-to-convert-rows-into-columns-in-sql/" aria-label="Read more about How to Convert Rows Into Columns in SQL">Read more</a>]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">A finance team once asked me for a report that looked simple on paper: one line per product, with four columns for Q1 through Q4. Their database stored sales the way databases should, with one row per product per quarter. An analyst had been exporting the data to Excel and rebuilding the layout by hand every month. When a quarter was missing for one product, the copy-and-paste shifted a column and the numbers landed under the wrong heading for two weeks.</p>



<p class="wp-block-paragraph">This is the classic reason to <strong>convert rows into columns in SQL</strong>. The database holds narrow, tall data, and reports want wide, flat data. SQL Server gives you three solid ways to do it: the <code>PIVOT</code> operator, conditional aggregation with <code>CASE</code>, and dynamic SQL when the columns are not known in advance. This guide builds each one, explains the trade-offs, and covers NULLs, performance, and secure reporting in SQL Server and Azure SQL Database.</p>



<h2 class="wp-block-heading">What &#8220;Rows Into Columns&#8221; Means</h2>



<p class="wp-block-paragraph">Turning rows into columns is called <strong>pivoting</strong>. You take the distinct values from one column, such as Q1, Q2, Q3, and Q4, and turn each into its own column heading. At the same time, you <strong>aggregate</strong>, which means combine many rows into one value with a function like <code>SUM</code>, so each cell of the new grid holds a single number.</p>



<p class="wp-block-paragraph">Every pivot has three parts:</p>



<ul class="wp-block-list">
<li><strong>Row identifier:</strong> the column that stays as rows, such as <code>Product</code>.</li>



<li><strong>Pivot column:</strong> the column whose values become headings, such as <code>Quarter</code>.</li>



<li><strong>Value column:</strong> the data that fills the cells, such as <code>Revenue</code>, with an aggregate.</li>
</ul>



<p class="wp-block-paragraph">The opposite operation, turning columns back into rows, is called unpivoting; see <a rel="noopener" target="_blank" href="https://sqlserverguides.com/sql-unpivot/">SQL UNPIVOT</a>.</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph"><strong>Pro Tip:</strong> In my experience, I write down those three parts on paper before touching the keyboard. Nearly every broken pivot I have debugged was missing a clear answer to &#8220;which column becomes the headings?&#8221;</p>
</blockquote>



<h3 class="wp-block-heading">Create a Practice Table</h3>



<p class="wp-block-paragraph">A <strong>schema</strong> is the structure of your tables. Use a small sales table with realistic gaps and a duplicate.</p>



<pre class="wp-block-preformatted"><code>CREATE TABLE dbo.QuarterlySales (<br>    SaleID   INT IDENTITY(1,1) PRIMARY KEY,<br>    Product  VARCHAR(30)   NOT NULL,<br>    Quarter  CHAR(2)       NOT NULL,<br>    Revenue  DECIMAL(10,2) NOT NULL<br>);<br><br>INSERT INTO dbo.QuarterlySales (Product, Quarter, Revenue)<br>VALUES<br> ('Laptop',  'Q1', 100.00), ('Laptop',  'Q1',  20.00),<br> ('Laptop',  'Q2', 120.00), ('Laptop',  'Q3',  90.00), ('Laptop', 'Q4', 150.00),<br> ('Monitor', 'Q1',  60.00), ('Monitor', 'Q3',  70.00), ('Monitor', 'Q4',  80.00),<br> ('Dock',    'Q2',  30.00), ('Dock',    'Q3',  40.00);</code></pre>



<p class="wp-block-paragraph">After executing the above query, I got the expected output as shown in the screenshot below.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="870" height="401" src="https://sqlserverguides.com/wp-content/uploads/2026/11/convert-rows-into-columns-in-sql.jpg" alt="convert rows into columns in sql" class="wp-image-24084" srcset="https://sqlserverguides.com/wp-content/uploads/2026/11/convert-rows-into-columns-in-sql.jpg 870w, https://sqlserverguides.com/wp-content/uploads/2026/11/convert-rows-into-columns-in-sql-766x353.jpg 766w, https://sqlserverguides.com/wp-content/uploads/2026/11/convert-rows-into-columns-in-sql-300x138.jpg 300w" sizes="auto, (max-width: 870px) 100vw, 870px" /></figure>
</div>

<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="290" src="https://sqlserverguides.com/wp-content/uploads/2026/11/how-to-convert-rows-into-columns-in-sql-server-1024x290.jpg" alt="how to convert rows into columns in sql server" class="wp-image-24085" srcset="https://sqlserverguides.com/wp-content/uploads/2026/11/how-to-convert-rows-into-columns-in-sql-server-1024x290.jpg 1024w, https://sqlserverguides.com/wp-content/uploads/2026/11/how-to-convert-rows-into-columns-in-sql-server-300x85.jpg 300w, https://sqlserverguides.com/wp-content/uploads/2026/11/how-to-convert-rows-into-columns-in-sql-server-766x217.jpg 766w, https://sqlserverguides.com/wp-content/uploads/2026/11/how-to-convert-rows-into-columns-in-sql-server.jpg 1508w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p class="wp-block-paragraph">Run this only in a test database, because it inserts rows. Notice three deliberate details. Laptop has two Q1 rows that must be added together. Monitor has no Q2 row. Dock has no Q1 or Q4 rows. The expected wide result is:</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th class="has-text-align-left" data-align="left">Product</th><th class="has-text-align-left" data-align="left">Q1</th><th class="has-text-align-left" data-align="left">Q2</th><th class="has-text-align-left" data-align="left">Q3</th><th class="has-text-align-left" data-align="left">Q4</th></tr></thead><tbody><tr><td>Dock</td><td>NULL</td><td>30</td><td>40</td><td>NULL</td></tr><tr><td>Laptop</td><td>120</td><td>120</td><td>90</td><td>150</td></tr><tr><td>Monitor</td><td>60</td><td>NULL</td><td>70</td><td>80</td></tr></tbody></table></figure>



<h3 class="wp-block-heading">How to Convert Rows Into Columns in SQL With PIVOT</h3>



<p class="wp-block-paragraph">The <code>PIVOT</code> operator is built into T-SQL for this job. It works in SQL Server and Azure SQL Database.</p>



<pre class="wp-block-preformatted"><code>SELECT Product, [Q1], [Q2], [Q3], [Q4]<br>FROM (<br>    SELECT Product, Quarter, Revenue<br>    FROM dbo.QuarterlySales<br>) AS src<br>PIVOT (<br>    SUM(Revenue)<br>    FOR Quarter IN ([Q1], [Q2], [Q3], [Q4])<br>) AS p<br>ORDER BY Product;</code></pre>



<p class="wp-block-paragraph">Here is what each piece does:</p>



<ul class="wp-block-list">
<li><strong>The inner query</strong> (<code>src</code>) selects only the three columns the pivot needs. This matters a lot, and we come back to it below.</li>



<li><strong><code>SUM(Revenue)</code></strong> is the aggregate that fills each cell. Laptop&#8217;s two Q1 rows add up to 120.</li>



<li><strong><code>FOR Quarter IN (...)</code></strong> names the pivot column and lists the values that become headings. You must list them by hand. Square brackets are required for names that contain spaces or start with a digit.</li>



<li><strong><code>AS p</code></strong> gives the pivot result an alias, which SQL Server requires.</li>
</ul>



<p class="wp-block-paragraph">After executing the above query, I got the expected output as shown in the screenshot below.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="891" height="512" src="https://sqlserverguides.com/wp-content/uploads/2026/11/How-to-Convert-Rows-Into-Columns-in-SQL.jpg" alt="How to Convert Rows Into Columns in SQL" class="wp-image-24086" srcset="https://sqlserverguides.com/wp-content/uploads/2026/11/How-to-Convert-Rows-Into-Columns-in-SQL.jpg 891w, https://sqlserverguides.com/wp-content/uploads/2026/11/How-to-Convert-Rows-Into-Columns-in-SQL-300x172.jpg 300w, https://sqlserverguides.com/wp-content/uploads/2026/11/How-to-Convert-Rows-Into-Columns-in-SQL-767x441.jpg 767w" sizes="auto, (max-width: 891px) 100vw, 891px" /></figure>
</div>


<p class="wp-block-paragraph">The output matches the table above. Missing combinations, like Monitor Q2, appear as NULL because no row existed to aggregate. A <strong>NULL</strong> is a missing or unknown value, not zero. To show zeros, wrap each column with <code>COALESCE</code>, which returns the first non-NULL value; see <a rel="noopener" target="_blank" href="https://sqlserverguides.com/sql-server-coalesce-function/">the COALESCE function</a> and <a rel="noopener" target="_blank" href="https://sqlserverguides.com/sql-null/">how SQL handles NULL</a>.</p>



<pre class="wp-block-preformatted"><code>SELECT Product,<br>       COALESCE([Q1], 0) AS Q1,<br>       COALESCE([Q2], 0) AS Q2,<br>       COALESCE([Q3], 0) AS Q3,<br>       COALESCE([Q4], 0) AS Q4<br>FROM (SELECT Product, Quarter, Revenue FROM dbo.QuarterlySales) AS src<br>PIVOT (SUM(Revenue) FOR Quarter IN ([Q1], [Q2], [Q3], [Q4])) AS p;</code></pre>



<p class="wp-block-paragraph">After executing the above query, I got the expected output as shown in the screenshot below.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="316" src="https://sqlserverguides.com/wp-content/uploads/2026/11/how-to-convert-rows-into-columns-in-sql-query-1024x316.jpg" alt="" class="wp-image-24087" srcset="https://sqlserverguides.com/wp-content/uploads/2026/11/how-to-convert-rows-into-columns-in-sql-query-1024x316.jpg 1024w, https://sqlserverguides.com/wp-content/uploads/2026/11/how-to-convert-rows-into-columns-in-sql-query-768x237.jpg 768w, https://sqlserverguides.com/wp-content/uploads/2026/11/how-to-convert-rows-into-columns-in-sql-query-300x92.jpg 300w, https://sqlserverguides.com/wp-content/uploads/2026/11/how-to-convert-rows-into-columns-in-sql-query.jpg 1338w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<h4 class="wp-block-heading">The Hidden-Column Trap</h4>



<p class="wp-block-paragraph"><code>PIVOT</code> groups by every column in the source that is not the pivot column or the value column. If you write <code>SELECT * FROM dbo.QuarterlySales PIVOT (...)</code>, the unique <code>SaleID</code> becomes part of the grouping, and every row ends up on its own line with mostly NULLs. Always use a subquery that selects only the columns you need, as shown above.</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph"><strong>Pro Tip:</strong> I once debugged a report that returned ten times too many rows because someone added a <code>LastModified</code> column to the source. Selecting exactly three columns in the inner query protects you from that kind of drift.</p>
</blockquote>



<h3 class="wp-block-heading">Method 2: Conditional Aggregation With CASE</h3>



<p class="wp-block-paragraph">You can get the same result with ordinary <code>GROUP BY</code> and <code>CASE</code>. This is called <strong>conditional aggregation</strong>: each column sums only the rows that match its heading. See <a rel="noopener" target="_blank" href="https://sqlserverguides.com/case-statement-in-sql-server/">the CASE statement</a>, <a rel="noopener" target="_blank" href="https://sqlserverguides.com/how-to-use-sum-function-in-sql-server/">the SUM function</a>, and <a rel="noopener" target="_blank" href="https://sqlserverguides.com/how-to-use-group-by-clause-in-sql-server/">GROUP BY</a>.</p>



<pre class="wp-block-preformatted"><code>SELECT<br>    Product,<br>    SUM(CASE WHEN Quarter = 'Q1' THEN Revenue ELSE 0 END) AS Q1,<br>    SUM(CASE WHEN Quarter = 'Q2' THEN Revenue ELSE 0 END) AS Q2,<br>    SUM(CASE WHEN Quarter = 'Q3' THEN Revenue ELSE 0 END) AS Q3,<br>    SUM(CASE WHEN Quarter = 'Q4' THEN Revenue ELSE 0 END) AS Q4<br>FROM dbo.QuarterlySales<br>GROUP BY Product<br>ORDER BY Product;</code></pre>



<p class="wp-block-paragraph">After executing the above query, I got the expected output as shown in the screenshot below.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="429" src="https://sqlserverguides.com/wp-content/uploads/2026/11/how-to-convert-rows-into-columns-sql-server-1024x429.jpg" alt="how to convert rows into columns sql server" class="wp-image-24088" srcset="https://sqlserverguides.com/wp-content/uploads/2026/11/how-to-convert-rows-into-columns-sql-server-1024x429.jpg 1024w, https://sqlserverguides.com/wp-content/uploads/2026/11/how-to-convert-rows-into-columns-sql-server-300x126.jpg 300w, https://sqlserverguides.com/wp-content/uploads/2026/11/how-to-convert-rows-into-columns-sql-server-766x321.jpg 766w, https://sqlserverguides.com/wp-content/uploads/2026/11/how-to-convert-rows-into-columns-sql-server.jpg 1229w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p class="wp-block-paragraph">Each <code>CASE</code> returns the revenue when the row belongs to that quarter and 0 otherwise. <code>SUM</code> adds them up per product. The <code>ELSE 0</code> gives zeros instead of NULLs. If you leave out <code>ELSE</code>, missing combinations come back as NULL.</p>



<h3 class="wp-block-heading">PIVOT vs. CASE</h3>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th class="has-text-align-left" data-align="left">Question</th><th class="has-text-align-left" data-align="left">PIVOT</th><th class="has-text-align-left" data-align="left">CASE (conditional aggregation)</th></tr></thead><tbody><tr><td>Code length for many columns</td><td>Shorter</td><td>Longer</td></tr><tr><td>Multiple aggregates (sum and count)</td><td>Awkward</td><td>Easy</td></tr><tr><td>Different logic per column</td><td>Not possible</td><td>Easy</td></tr><tr><td>Works on all SQL dialects</td><td>No (T-SQL and a few others)</td><td>Yes</td></tr><tr><td>Familiar to new teammates</td><td>Often unfamiliar</td><td>Usually clear</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">Both read the table once, so performance is usually similar. I use <code>PIVOT</code> for quick one-aggregate layouts and <code>CASE</code> when a report needs counts, sums, and custom rules side by side. Pick the one your team can maintain.</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph"><strong>Pro Tip:</strong> In my experience, teams that learn conditional aggregation first rarely need <code>PIVOT</code>. It handles more cases, and it ports to other databases if you ever migrate.</p>
</blockquote>



<h3 class="wp-block-heading">Method 3: Dynamic Pivot When Columns Change</h3>



<p class="wp-block-paragraph">Both methods above hard-code the headings. That breaks the day a new value appears, such as Q5 or a new region. When the list of values changes, build the column list from the data with <strong>dynamic SQL</strong>, which means assembling a SQL statement as text and running it at run time. Read more in <a rel="noopener" target="_blank" href="https://sqlserverguides.com/dynamic-sql/">dynamic SQL</a>.</p>



<pre class="wp-block-preformatted"><code>DECLARE @cols NVARCHAR(MAX), @sql NVARCHAR(MAX);<br><br>SELECT @cols = STRING_AGG(CAST(QUOTENAME(Quarter) AS NVARCHAR(MAX)), N', ')<br>               WITHIN GROUP (ORDER BY Quarter)<br>FROM (SELECT DISTINCT Quarter FROM dbo.QuarterlySales) AS q;<br><br>SET @sql = N'<br>SELECT Product, ' + @cols + N'<br>FROM (SELECT Product, Quarter, Revenue FROM dbo.QuarterlySales) AS src<br>PIVOT (SUM(Revenue) FOR Quarter IN (' + @cols + N')) AS p<br>ORDER BY Product;';<br><br>EXEC sys.sp_executesql @sql;</code></pre>



<p class="wp-block-paragraph">Step by step:</p>



<ul class="wp-block-list">
<li><strong><code>SELECT DISTINCT Quarter</code></strong> finds the headings that exist right now.</li>



<li><strong><code>QUOTENAME</code></strong> wraps each value in brackets and escapes special characters. This is essential for safety and for names with spaces. See <a href="https://sqlserverguides.com/quotename-function-in-sql-server/" target="_blank" rel="noopener">QUOTENAME</a>.</li>



<li><strong><code>STRING_AGG</code></strong> joins the values into a comma-separated list, ordered with <code>WITHIN GROUP</code>. It requires SQL Server 2017 or later and is available in Azure SQL Database. See <a href="https://sqlserverguides.com/sql-server-string_agg-function/" target="_blank" rel="noopener">STRING_AGG</a>. On older versions, the <code>FOR XML PATH</code> trick is the traditional replacement.</li>



<li><strong><code>sp_executesql</code></strong> runs the generated statement.</li>
</ul>



<p class="wp-block-paragraph">After executing the above query, I got the expected output as shown in the screenshot below.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="488" src="https://sqlserverguides.com/wp-content/uploads/2026/11/convert-columns-into-rows-in-sql-1024x488.jpg" alt="sql how to convert rows into columns" class="wp-image-24089" srcset="https://sqlserverguides.com/wp-content/uploads/2026/11/convert-columns-into-rows-in-sql-1024x488.jpg 1024w, https://sqlserverguides.com/wp-content/uploads/2026/11/convert-columns-into-rows-in-sql-300x143.jpg 300w, https://sqlserverguides.com/wp-content/uploads/2026/11/convert-columns-into-rows-in-sql-766x365.jpg 766w, https://sqlserverguides.com/wp-content/uploads/2026/11/convert-columns-into-rows-in-sql.jpg 1413w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p class="wp-block-paragraph">Dynamic SQL carries risks. If any heading value comes from user input, an attacker could try <strong>SQL injection</strong>, which means slipping extra SQL commands into the text. <code>QUOTENAME</code> neutralizes this for identifiers, but never concatenate raw user input anywhere else in the statement. </p>



<p class="wp-block-paragraph">Also remember that dynamic SQL does not benefit from <strong>ownership chaining</strong>, the rule that lets a procedure access tables its owner can access without extra grants. The caller needs permission on the underlying table, or the procedure must use <code>EXECUTE AS</code>.</p>



<p class="wp-block-paragraph">Wide results have limits too. A result set can hold a large number of columns, but a report with hundreds of dynamic columns is hard to read and slow to render. If the headings number in the dozens, consider doing the final layout in the reporting tool or application.</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph"><strong>Pro Tip:</strong> I log the generated <code>@sql</code> text to a debug table during testing. Seeing the exact statement makes dynamic pivot bugs obvious in seconds, instead of staring at a string in a debugger.</p>
</blockquote>



<h3 class="wp-block-heading">Pivot Dates and Months</h3>



<p class="wp-block-paragraph">Real reports often pivot dates. Raw dates make poor headings, because every day would become a column. Convert them to a month or a quarter first:</p>



<pre class="wp-block-preformatted"><code>SELECT Product,<br>       SUM(CASE WHEN MONTH(SaleDate) = 1 THEN Revenue ELSE 0 END) AS Jan,<br>       SUM(CASE WHEN MONTH(SaleDate) = 2 THEN Revenue ELSE 0 END) AS Feb,<br>       SUM(CASE WHEN MONTH(SaleDate) = 3 THEN Revenue ELSE 0 END) AS Mar<br>FROM dbo.DailySales<br>WHERE SaleDate >= '2026-01-01' AND SaleDate &lt; '2026-04-01'<br>GROUP BY Product;</code></pre>



<p class="wp-block-paragraph">This assumes a <code>DailySales</code> table with a <code>SaleDate</code> column. The date filter uses a half-open range, which includes January 1 and excludes April 1, and it keeps the column bare so SQL Server can use an index. For month functions, see <a rel="noopener" target="_blank" href="https://sqlserverguides.com/sql-server-get-month-from-date/">getting the month from a date</a>. For the full date-pivot pattern, read <a rel="noopener" target="_blank" href="https://sqlserverguides.com/pivot-date-column-in-sql-server/">pivoting a date column</a>.</p>



<h3 class="wp-block-heading">Turn Rows Into a Single Column</h3>



<p class="wp-block-paragraph">Sometimes &#8220;rows into columns&#8221; means joining many rows into one text value, such as a comma-separated list of tags. That is a different task. Use <code>STRING_AGG</code>:</p>



<pre class="wp-block-preformatted"><code>SELECT Product, STRING_AGG(Quarter, ', ') WITHIN GROUP (ORDER BY Quarter) AS QuartersSold<br>FROM dbo.QuarterlySales<br>GROUP BY Product;</code></pre>



<p class="wp-block-paragraph">This returns lines such as &#8220;Q1, Q1, Q2, Q3, Q4&#8221; for Laptop. Use <code>SELECT DISTINCT</code> in a subquery if you want each quarter once. The result is text, so you can no longer aggregate it, which is why this approach suits display and exports more than analysis.</p>



<h3 class="wp-block-heading">Performance, Indexing, and Reuse</h3>



<p class="wp-block-paragraph">A pivot reads the source rows once, groups them, and spreads values across columns. The cost depends mostly on how many rows you scan, not on the pivot itself. To keep it fast:</p>



<ul class="wp-block-list">
<li><strong>Filter first.</strong> Restrict by date or tenant in the source subquery so you pivot fewer rows.</li>



<li><strong>Index the grouping and filter columns.</strong> An index on <code>(Product, Quarter)</code> that includes <code>Revenue</code> lets SQL Server read a narrow structure. See <a href="https://sqlserverguides.com/how-to-create-index-in-sql-server/" target="_blank" rel="noopener">how to create an index in SQL Server</a>. Check the actual execution plan first, because each index slows inserts and updates.</li>



<li><strong>Pre-aggregate large tables.</strong> For hundreds of millions of rows, keep a summary table updated nightly and pivot that instead.</li>



<li><strong>Use a CTE for clarity.</strong> A common table expression names an intermediate step; compare it with a temp table in <a href="https://sqlserverguides.com/sql-server-cte-vs-temp-table/" target="_blank" rel="noopener">CTE vs. temp table</a>.</li>
</ul>



<p class="wp-block-paragraph">Save the final query in a <strong>view</strong> or a stored procedure so every report uses the same layout; see <a rel="noopener" target="_blank" href="https://sqlserverguides.com/sql-server-views/">SQL Server views</a> and <a rel="noopener" target="_blank" href="https://sqlserverguides.com/create-stored-procedure-in-sql-server/">creating a stored procedure</a>. For more tuning ideas, see <a rel="noopener" target="_blank" href="https://sqlserverguides.com/sql-query-optimization-tips/">SQL query optimization tips</a>. In Azure SQL Database, use <strong>Query Store</strong>, which records query run times, to confirm that a change helped.</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph"><strong>Pro Tip:</strong> In my experience, the best pivot optimization is a date filter. Pivoting five years of history to show the last quarter wastes compute, which on serverless Azure SQL Database also wastes money.</p>
</blockquote>



<h3 class="wp-block-heading">Frequently Asked Questions</h3>



<h4 class="wp-block-heading">How do I convert rows into columns in SQL Server?</h4>



<p class="wp-block-paragraph">Use the <code>PIVOT</code> operator, or use <code>GROUP BY</code> with <code>SUM(CASE WHEN ... THEN ... END)</code> for each new column. Both turn distinct values from one column into column headings and aggregate a value column into the cells.</p>



<h4 class="wp-block-heading">What is the difference between PIVOT and CASE for pivoting?</h4>



<p class="wp-block-paragraph"><code>PIVOT</code> is shorter for one aggregate across many columns. <code>CASE</code> is more flexible because you can use several aggregates and custom logic per column, and it works in most SQL dialects. Performance is usually similar.</p>



<h4 class="wp-block-heading">How do I pivot when I do not know the column values in advance?</h4>



<p class="wp-block-paragraph">Build the column list from the data with <code>STRING_AGG</code> and <code>QUOTENAME</code>, assemble a dynamic <code>PIVOT</code> statement, and run it with <code>sp_executesql</code>. Validate inputs, and remember that the caller needs permission on the underlying table.</p>



<h4 class="wp-block-heading">Why does my PIVOT return duplicate rows or too many rows?</h4>



<p class="wp-block-paragraph">The source includes extra columns, such as an ID, and <code>PIVOT</code> groups by all of them. Select only the row identifier, pivot column, and value column in a subquery.</p>



<h4 class="wp-block-heading">How do I show zero instead of NULL in a pivot?</h4>



<p class="wp-block-paragraph">Wrap each pivoted column in <code>COALESCE(column, 0)</code>, or use <code>ELSE 0</code> inside the <code>CASE</code> expressions. Decide whether zero is accurate, since NULL can mean no data and zero means no sales.</p>



<p class="wp-block-paragraph">You learned how to convert rows into columns in SQL Server with <code>PIVOT</code>, conditional aggregation, and dynamic SQL, and how to handle NULLs, hidden grouping columns, and changing headings. Select only the columns the pivot needs, protect dynamic SQL with <code>QUOTENAME</code>, and give report users read-only access through a view. I hope you found this article helpful.</p>



<p class="wp-block-paragraph">You May Also Like</p>



<ul class="wp-block-list">
<li><a href="https://sqlserverguides.com/sql-server-split-string-into-rows/" target="_blank" rel="noopener">SQL Server string split into rows</a></li>



<li><a href="https://sqlserverguides.com/sql-server-json-to-table/" target="_blank" rel="noopener">Converting JSON to a table in SQL Server</a></li>



<li><a href="https://sqlserverguides.com/sql-server-group-by-date/" target="_blank" rel="noopener">How to group by date in SQL Server</a></li>



<li><a href="https://sqlserverguides.com/how-to-use-count-function-in-sql-server/" target="_blank" rel="noopener">How to use the COUNT function in SQL Server</a></li>



<li><a href="https://sqlserverguides.com/sql-cheat-sheet/" target="_blank" rel="noopener">SQL cheat sheet</a></li>
</ul>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How to Use CASE WHEN in SQL Server</title>
		<link>https://sqlserverguides.com/case-when-in-sql-server/</link>
		
		<dc:creator><![CDATA[Bijay Kumar Sahoo]]></dc:creator>
		<pubDate>Wed, 04 Nov 2026 05:41:44 +0000</pubDate>
				<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[How to Use CASE WHEN in SQL Server]]></category>
		<guid isPermaLink="false">https://sqlserverguides.com/?p=24072</guid>

					<description><![CDATA[A support lead once asked me why her &#8220;high priority&#8221; ticket report showed refunds as low priority. The developer had written a long chain of IF logic in the application, and every time the rules changed, the app and the report disagreed. We moved the rule into one T-SQL expression, and the two numbers matched ... <a title="How to Use CASE WHEN in SQL Server" class="read-more" href="https://sqlserverguides.com/case-when-in-sql-server/" aria-label="Read more about How to Use CASE WHEN in SQL Server">Read more</a>]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">A support lead once asked me why her &#8220;high priority&#8221; ticket report showed refunds as low priority. The developer had written a long chain of <code>IF</code> logic in the application, and every time the rules changed, the app and the report disagreed. We moved the rule into one T-SQL expression, and the two numbers matched on the first run.</p>



<p class="wp-block-paragraph">That expression was <code>CASE WHEN</code>, and learning <strong>how to use CASE WHEN in SQL Server</strong> is one of the best investments a developer or analyst can make. It adds if/then logic directly inside a query, so labels, buckets, custom sorting, and conditional totals all come from the database in one pass. This guide covers both forms of <code>CASE</code>, the common patterns, the NULL and data-type traps, performance, and safe use in production on SQL Server or Azure SQL Database.</p>



<h2 class="wp-block-heading">What CASE Does and the Two Forms</h2>



<p class="wp-block-paragraph"><code>CASE</code> is an <strong>expression</strong>, not a statement. That means it returns a value and can be used anywhere a value is allowed: in <code>SELECT</code>, <code>WHERE</code>, <code>ORDER BY</code>, <code>GROUP BY</code>, aggregates, and <code>UPDATE</code>. SQL Server evaluates the conditions from top to bottom and returns the result for the first one that is true.</p>



<p class="wp-block-paragraph">There are two forms.</p>



<p class="wp-block-paragraph"><strong>Simple CASE</strong> compares one expression to a list of values:</p>



<pre class="wp-block-preformatted"><code>CASE Status<br>    WHEN 'Shipped' THEN 'Done'<br>    WHEN 'Pending' THEN 'Open'<br>    ELSE 'Other'<br>END</code></pre>



<p class="wp-block-paragraph"><strong>Searched CASE</strong> tests full conditions, so it handles ranges, <code>AND</code>/<code>OR</code>, and NULL checks:</p>



<pre class="wp-block-preformatted"><code>CASE<br>    WHEN Amount &lt; 100 THEN 'Small'<br>    WHEN Amount &lt; 500 THEN 'Medium'<br>    ELSE 'Large'<br>END</code></pre>



<p class="wp-block-paragraph">Use simple <code>CASE</code> for exact matches and searched <code>CASE</code> for everything else. If you leave out <code>ELSE</code> and no condition matches, the result is NULL. Always add an <code>ELSE</code> unless NULL is truly what you want.</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph"><strong>Pro Tip:</strong> In my experience, I default to the searched form even for exact matches. It costs nothing, and it avoids a rewrite when someone asks for a range or a NULL check later.</p>
</blockquote>



<h3 class="wp-block-heading">Create a Practice Table</h3>



<p class="wp-block-paragraph">A <strong>schema</strong> is the structure of your tables. Use a small orders table with edge cases: a NULL amount, mixed statuses, and values on both sides of each band.</p>



<pre class="wp-block-preformatted"><code>CREATE TABLE dbo.Orders (<br>    OrderID    INT IDENTITY(1,1) PRIMARY KEY,<br>    CustomerID INT NOT NULL,<br>    Amount     DECIMAL(10,2) NULL,<br>    Status     VARCHAR(20) NOT NULL,<br>    OrderDate  DATE NOT NULL<br>);<br><br>INSERT INTO dbo.Orders (CustomerID, Amount, Status, OrderDate)<br>VALUES<br> (101,   45.00, 'Shipped',   '2026-10-01'),<br> (102,  250.00, 'Pending',   '2026-10-03'),<br> (103, 1200.00, 'Shipped',   '2026-10-05'),<br> (101,    NULL, 'Cancelled', '2026-10-06'),<br> (104,   89.99, 'Returned',  '2026-10-08'),<br> (105,  600.00, 'Pending',   '2026-10-09');</code></pre>



<p class="wp-block-paragraph">Run this only in a test database, because it inserts rows. Order 4 has a NULL amount on purpose.</p>



<p class="wp-block-paragraph">After executing the query above, I got the expected output as shown in the screenshot below.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="912" height="568" src="https://sqlserverguides.com/wp-content/uploads/2026/11/case-when-in-sql-server.jpg" alt="case when in sql server" class="wp-image-24073" srcset="https://sqlserverguides.com/wp-content/uploads/2026/11/case-when-in-sql-server.jpg 912w, https://sqlserverguides.com/wp-content/uploads/2026/11/case-when-in-sql-server-300x187.jpg 300w, https://sqlserverguides.com/wp-content/uploads/2026/11/case-when-in-sql-server-767x478.jpg 767w" sizes="auto, (max-width: 912px) 100vw, 912px" /></figure>
</div>

<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="406" src="https://sqlserverguides.com/wp-content/uploads/2026/11/select-case-when-in-sql-server-1024x406.jpg" alt="select case when in sql server" class="wp-image-24074" srcset="https://sqlserverguides.com/wp-content/uploads/2026/11/select-case-when-in-sql-server-1024x406.jpg 1024w, https://sqlserverguides.com/wp-content/uploads/2026/11/select-case-when-in-sql-server-300x119.jpg 300w, https://sqlserverguides.com/wp-content/uploads/2026/11/select-case-when-in-sql-server-766x304.jpg 766w, https://sqlserverguides.com/wp-content/uploads/2026/11/select-case-when-in-sql-server.jpg 1187w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<h3 class="wp-block-heading">How to Use CASE WHEN in SQL Server SELECT Queries</h3>



<p class="wp-block-paragraph">The most common use is creating a label column. This query puts each order in a size band:</p>



<pre class="wp-block-preformatted"><code>SELECT<br>    OrderID,<br>    Amount,<br>    CASE<br>        WHEN Amount IS NULL THEN 'No amount'<br>        WHEN Amount &lt; 100   THEN 'Small'<br>        WHEN Amount &lt; 500   THEN 'Medium'<br>        ELSE 'Large'<br>    END AS OrderSize<br>FROM dbo.Orders;</code></pre>



<p class="wp-block-paragraph">After executing the query above, I got the expected output as shown in the screenshot below.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="894" height="573" src="https://sqlserverguides.com/wp-content/uploads/2026/11/how-to-use-case-when-in-sql-server.jpg" alt="how to use case when in sql server" class="wp-image-24075" srcset="https://sqlserverguides.com/wp-content/uploads/2026/11/how-to-use-case-when-in-sql-server.jpg 894w, https://sqlserverguides.com/wp-content/uploads/2026/11/how-to-use-case-when-in-sql-server-300x192.jpg 300w, https://sqlserverguides.com/wp-content/uploads/2026/11/how-to-use-case-when-in-sql-server-768x492.jpg 768w" sizes="auto, (max-width: 894px) 100vw, 894px" /></figure>
</div>


<p class="wp-block-paragraph">The results are Small, Medium, Large, No amount, Small, and Large for orders 1 to 6. Notice three details:</p>



<ul class="wp-block-list">
<li><strong>Order matters.</strong> SQL Server returns the first true branch. Because <code>Amount &lt; 100</code> comes before <code>Amount &lt; 500</code>, an order of 45 is Small, even though it is also below 500. If you reverse them, everything below 500 becomes Medium.</li>



<li><strong>The NULL check comes first.</strong> A NULL amount makes both <code>Amount &lt; 100</code> and <code>Amount &lt; 500</code> unknown, not true, so it would fall through to <code>ELSE</code> and be labeled Large. That is a silent bug. For more on this behavior, see <a href="https://sqlserverguides.com/sql-null/" target="_blank" rel="noopener">how SQL handles NULL</a>.</li>



<li><strong>Aliases name the result.</strong> <code>AS OrderSize</code> gives the new column a readable name.</li>
</ul>



<p class="wp-block-paragraph">You can also translate codes with a simple <code>CASE</code>:</p>



<pre class="wp-block-preformatted"><code>SELECT OrderID,<br>       CASE Status<br>           WHEN 'Shipped'   THEN 'Complete'<br>           WHEN 'Pending'   THEN 'In progress'<br>           WHEN 'Cancelled' THEN 'Closed'<br>           WHEN 'Returned'  THEN 'Closed'<br>           ELSE 'Unknown'<br>       END AS StatusGroup<br>FROM dbo.Orders;</code></pre>



<p class="wp-block-paragraph">After executing the query above, I got the expected output as shown in the screenshot below.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="928" height="572" src="https://sqlserverguides.com/wp-content/uploads/2026/11/case-when-then-in-sql-server.jpg" alt="case when then in sql server" class="wp-image-24080" srcset="https://sqlserverguides.com/wp-content/uploads/2026/11/case-when-then-in-sql-server.jpg 928w, https://sqlserverguides.com/wp-content/uploads/2026/11/case-when-then-in-sql-server-767x473.jpg 767w, https://sqlserverguides.com/wp-content/uploads/2026/11/case-when-then-in-sql-server-300x185.jpg 300w" sizes="auto, (max-width: 928px) 100vw, 928px" /></figure>
</div>


<p class="wp-block-paragraph">Keeping this mapping in one query, or better in a view, prevents the &#8220;app and report disagree&#8221; problem. See <a rel="noopener" target="_blank" href="https://sqlserverguides.com/sql-server-views/">SQL Server views</a>.</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph"><strong>Pro Tip:</strong> I write the NULL branch first in every searched <code>CASE</code>. It takes one line and removes a whole class of &#8220;why is this row in the wrong bucket&#8221; bugs.</p>
</blockquote>



<h3 class="wp-block-heading">The NULL Trap: <code>= NULL</code> Never Matches</h3>



<p class="wp-block-paragraph">This is the number one mistake. Inside <code>CASE</code>, <code>WHEN Amount = NULL</code> is never true, because comparing with NULL gives unknown.</p>



<pre class="wp-block-preformatted"><code><em>-- Wrong: never matches</em><br>CASE WHEN Amount = NULL THEN 'No amount' ELSE 'Has amount' END<br><br><em>-- Right</em><br>CASE WHEN Amount IS NULL THEN 'No amount' ELSE 'Has amount' END</code></pre>



<p class="wp-block-paragraph">The same trap exists in simple <code>CASE</code>. <code>CASE Amount WHEN NULL THEN ...</code> also never matches, because the simple form uses equality. Use the searched form with <code>IS NULL</code>.</p>



<p class="wp-block-paragraph">For shorter NULL handling, <code>COALESCE</code> and <code>ISNULL</code> often replace a whole <code>CASE</code>; see <a rel="noopener" target="_blank" href="https://sqlserverguides.com/sql-server-coalesce-function/">COALESCE</a> and <a rel="noopener" target="_blank" href="https://sqlserverguides.com/isnull-function-in-sql-server/">ISNULL</a>. For choosing between them, read <a rel="noopener" target="_blank" href="https://sqlserverguides.com/nullif-vs-coalesce/">NULLIF vs. COALESCE</a>.</p>



<h3 class="wp-block-heading">Use CASE in ORDER BY for Custom Sorting</h3>



<p class="wp-block-paragraph">Alphabetical order is rarely the business order. <code>CASE</code> in <code>ORDER BY</code> lets you define your own ranking:</p>



<pre class="wp-block-preformatted"><code>SELECT OrderID, Status, OrderDate<br>FROM dbo.Orders<br>ORDER BY<br>    CASE Status<br>        WHEN 'Pending'   THEN 1<br>        WHEN 'Shipped'   THEN 2<br>        WHEN 'Returned'  THEN 3<br>        WHEN 'Cancelled' THEN 4<br>        ELSE 5<br>    END,<br>    OrderDate DESC;</code></pre>



<p class="wp-block-paragraph">After executing the query above, I got the expected output as shown in the screenshot below.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="723" height="632" src="https://sqlserverguides.com/wp-content/uploads/2026/11/case-when-in-sql-server-example.jpg" alt="case when in sql server example" class="wp-image-24076" srcset="https://sqlserverguides.com/wp-content/uploads/2026/11/case-when-in-sql-server-example.jpg 723w, https://sqlserverguides.com/wp-content/uploads/2026/11/case-when-in-sql-server-example-300x262.jpg 300w" sizes="auto, (max-width: 723px) 100vw, 723px" /></figure>
</div>


<p class="wp-block-paragraph">The <code>CASE</code> maps each status to a number, and SQL Server sorts by that number first. Pending orders appear at the top, then Shipped, Returned, and Cancelled, with the newest order first inside each group. See <a rel="noopener" target="_blank" href="https://sqlserverguides.com/order-by-clause-in-sql-server/">ORDER BY in SQL Server</a> for the basics.</p>



<p class="wp-block-paragraph">A second use is putting NULLs last. SQL Server sorts NULLs first in ascending order, so this flips that:</p>



<pre class="wp-block-preformatted">sql<code>ORDER BY CASE WHEN Amount IS NULL THEN 1 ELSE 0 END, Amount;</code></pre>



<p class="wp-block-paragraph">The first sort key is 0 for rows with an amount and 1 for NULL rows, so NULLs fall to the end.</p>



<h3 class="wp-block-heading">Conditional Aggregation: Pivot-Style Reports</h3>



<p class="wp-block-paragraph">You can place <code>CASE</code> inside an aggregate function to count or sum only certain rows. This is called <strong>conditional aggregation</strong>, and it replaces many separate queries with one. See <a rel="noopener" target="_blank" href="https://sqlserverguides.com/how-to-use-sum-function-in-sql-server/">the SUM function</a> and <a rel="noopener" target="_blank" href="https://sqlserverguides.com/how-to-use-group-by-clause-in-sql-server/">GROUP BY</a>.</p>



<pre class="wp-block-preformatted"><code>SELECT<br>    COUNT(*) AS TotalOrders,<br>    SUM(CASE WHEN Status = 'Shipped'   THEN 1 ELSE 0 END) AS ShippedCount,<br>    SUM(CASE WHEN Status = 'Pending'   THEN 1 ELSE 0 END) AS PendingCount,<br>    SUM(CASE WHEN Status = 'Shipped'   THEN Amount ELSE 0 END) AS ShippedRevenue,<br>    SUM(CASE WHEN Status = 'Pending'   THEN Amount ELSE 0 END) AS PendingRevenue<br>FROM dbo.Orders;</code></pre>



<p class="wp-block-paragraph">After executing the query above, I got the expected output as shown in the screenshot below.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="263" src="https://sqlserverguides.com/wp-content/uploads/2026/11/case-when-in-sql-server-where-clause-1024x263.jpg" alt="case when in sql server where clause" class="wp-image-24077" srcset="https://sqlserverguides.com/wp-content/uploads/2026/11/case-when-in-sql-server-where-clause-1024x263.jpg 1024w, https://sqlserverguides.com/wp-content/uploads/2026/11/case-when-in-sql-server-where-clause-300x77.jpg 300w, https://sqlserverguides.com/wp-content/uploads/2026/11/case-when-in-sql-server-where-clause-767x197.jpg 767w, https://sqlserverguides.com/wp-content/uploads/2026/11/case-when-in-sql-server-where-clause.jpg 1522w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p class="wp-block-paragraph">With the sample data, this returns 6 total orders, 2 shipped, 2 pending, 1,245.00 in shipped revenue, and 850.00 in pending revenue. Each <code>CASE</code> returns 1 or the amount when the row qualifies and 0 otherwise, and <code>SUM</code> adds the results.</p>



<p class="wp-block-paragraph">Use <code>SUM(CASE ... THEN 1 ELSE 0 END)</code>, not <code>COUNT(CASE ... THEN 1 ELSE 0 END)</code>. <code>COUNT</code> counts every non-NULL value, so 0 is counted too. If you want <code>COUNT</code>, omit the <code>ELSE</code> so non-matching rows become NULL. For more on <code>COUNT</code>, see <a rel="noopener" target="_blank" href="https://sqlserverguides.com/how-to-use-count-function-in-sql-server/">the COUNT function</a>.</p>



<p class="wp-block-paragraph">For a full pivot with dynamic columns, SQL Server also has a <code>PIVOT</code> operator; see <a rel="noopener" target="_blank" href="https://sqlserverguides.com/pivot-in-sql-server-rows-to-columns/">pivoting rows to columns</a>. Conditional aggregation is often easier to read and works with any version.</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph"><strong>Pro Tip:</strong> I use conditional aggregation for dashboards because one query returns every tile. Ten small queries each scan the table; one <code>CASE</code>-based query scans it once.</p>
</blockquote>



<h3 class="wp-block-heading">Use CASE in UPDATE Statements</h3>



<p class="wp-block-paragraph"><code>CASE</code> lets one <code>UPDATE</code> apply different values to different rows. </p>



<p class="wp-block-paragraph"><strong>Warning:</strong> <code>UPDATE</code> overwrites data. Take a backup, preview with a <code>SELECT</code>, and use a transaction. See <a href="https://sqlserverguides.com/table-backup-in-sql-server/" target="_blank" rel="noopener">table backup in SQL Server</a>.</p>



<pre class="wp-block-preformatted"><code><em>-- Preview first</em><br>SELECT OrderID, Status,<br>       CASE WHEN Status = 'Pending' AND OrderDate &lt; '2026-10-05'<br>            THEN 'Delayed' ELSE Status END AS NewStatus<br>FROM dbo.Orders;<br><br>BEGIN TRANSACTION;<br><br>UPDATE dbo.Orders<br>SET Status = CASE<br>                 WHEN Status = 'Pending' AND OrderDate &lt; '2026-10-05' THEN 'Delayed'<br>                 ELSE Status<br>             END<br>WHERE Status = 'Pending';<br><br>SELECT @@ROWCOUNT AS RowsUpdated;<br><br><em>-- COMMIT TRANSACTION;   -- after verifying the count</em><br><em>-- ROLLBACK TRANSACTION; -- to undo</em></code></pre>



<p class="wp-block-paragraph">After executing the query above, I got the expected output as shown in the screenshot below.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="470" src="https://sqlserverguides.com/wp-content/uploads/2026/11/case-when-syntax-in-sql-server-1024x470.jpg" alt="case when syntax in sql server" class="wp-image-24078" srcset="https://sqlserverguides.com/wp-content/uploads/2026/11/case-when-syntax-in-sql-server-1024x470.jpg 1024w, https://sqlserverguides.com/wp-content/uploads/2026/11/case-when-syntax-in-sql-server-300x138.jpg 300w, https://sqlserverguides.com/wp-content/uploads/2026/11/case-when-syntax-in-sql-server-1536x704.jpg 1536w, https://sqlserverguides.com/wp-content/uploads/2026/11/case-when-syntax-in-sql-server-768x352.jpg 768w, https://sqlserverguides.com/wp-content/uploads/2026/11/case-when-syntax-in-sql-server.jpg 1570w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p class="wp-block-paragraph">The preview shows exactly what will change. The <code>WHERE Status = 'Pending'</code> limits the rows the update touches, and <code>ELSE Status</code> keeps the original value for rows that do not match. Without the <code>WHERE</code>, SQL Server would rewrite every row, including unchanged ones, which wastes log space and takes more locks. </p>



<p class="wp-block-paragraph">Check <code>@@ROWCOUNT</code> before you commit, and keep the transaction short to avoid blocking other sessions. When the new values come from another table, see <a href="https://sqlserverguides.com/sql-server-update-table-from-another-table/" target="_blank" rel="noopener">updating a table from another table</a>.</p>



<h3 class="wp-block-heading">Pitfalls: Data Types, Evaluation Order, and Division</h3>



<p class="wp-block-paragraph"><strong>Return types must be compatible.</strong> Every <code>THEN</code> and <code>ELSE</code> result in one <code>CASE</code> must resolve to a single data type, chosen by SQL Server&#8217;s <strong>data type precedence</strong>, the ranking that decides which type wins when types are mixed. If one branch returns a number and another returns text, SQL Server tries to convert the text to a number and fails:</p>



<pre class="wp-block-preformatted"><code><em>-- Fails when the ELSE branch is reached: 'Unknown' cannot become an INT</em><br>SELECT CASE WHEN Amount > 100 THEN 1 ELSE 'Unknown' END FROM dbo.Orders;</code></pre>



<p class="wp-block-paragraph">Make the types match, for example by casting the number to text. See <a rel="noopener" target="_blank" href="https://sqlserverguides.com/cast-function-in-sql-server/">the CAST function</a> and the related error <a rel="noopener" target="_blank" href="https://sqlserverguides.com/error-converting-data-type-varchar-to-numeric/">converting varchar to numeric</a>.</p>



<p class="wp-block-paragraph"><strong>Guard division, but know the limits.</strong> <code>CASE</code> is the standard way to avoid divide-by-zero:</p>



<pre class="wp-block-preformatted"><code>SELECT CASE WHEN Amount = 0 OR Amount IS NULL THEN NULL<br>            ELSE 100.0 / Amount END AS Ratio<br>FROM dbo.Orders;</code></pre>



<p class="wp-block-paragraph">SQL Server generally evaluates <code>CASE</code> branches in order, but the documentation warns that it does not guarantee evaluation order in every case, especially when aggregates appear inside the expression. For simple division, <code>NULLIF</code> is shorter and safer: <code>100.0 / NULLIF(Amount, 0)</code>.</p>



<p class="wp-block-paragraph"><strong>Nesting has a limit.</strong> SQL Server allows <code>CASE</code> expressions to nest up to 10 levels. If you need that many, move the rules into a lookup table and join to it. A mapping table is easier to change than code; see <a rel="noopener" target="_blank" href="https://sqlserverguides.com/join-in-sql-server/">joins in SQL Server</a>.</p>



<p class="wp-block-paragraph"><strong>Know the alternatives.</strong> <code>IIF</code> is shorthand for a two-branch <code>CASE</code>; see <a rel="noopener" target="_blank" href="https://sqlserverguides.com/sql-server-iif-logical-function/">the IIF function</a>. <code>CHOOSE</code> picks from a list by position; see <a rel="noopener" target="_blank" href="https://sqlserverguides.com/choose-function-in-sql-server/">the CHOOSE function</a>. Use <code>CASE</code> when you have more than two outcomes or need the clearest logic.</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph"><strong>Pro Tip:</strong> I once reviewed a <code>CASE</code> with twelve nested levels that nobody on the team dared touch. We replaced it with a six-row lookup table, and the next rule change took two minutes.</p>
</blockquote>



<h3 class="wp-block-heading">Use CASE in WHERE and Keep Queries Fast</h3>



<p class="wp-block-paragraph">You can place <code>CASE</code> in a <code>WHERE</code> clause, but you usually should not. Compare these two queries:</p>



<pre class="wp-block-preformatted"><code><em>-- Hard for the optimizer: the column is hidden inside an expression</em><br>SELECT OrderID FROM dbo.Orders<br>WHERE CASE WHEN Status = 'Shipped' THEN 1 ELSE 0 END = 1;<br><br><em>-- Better: a plain, index-friendly condition</em><br>SELECT OrderID FROM dbo.Orders<br>WHERE Status = 'Shipped';</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="398" src="https://sqlserverguides.com/wp-content/uploads/2026/11/sql-server-case-when-in-1024x398.jpg" alt="sql server case when in" class="wp-image-24079" srcset="https://sqlserverguides.com/wp-content/uploads/2026/11/sql-server-case-when-in-1024x398.jpg 1024w, https://sqlserverguides.com/wp-content/uploads/2026/11/sql-server-case-when-in-300x116.jpg 300w, https://sqlserverguides.com/wp-content/uploads/2026/11/sql-server-case-when-in-768x298.jpg 768w, https://sqlserverguides.com/wp-content/uploads/2026/11/sql-server-case-when-in.jpg 1311w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p class="wp-block-paragraph">A condition is <strong>sargable</strong> when SQL Server can use an index seek to find matching rows. Wrapping a column in a <code>CASE</code> or function usually makes it non-sargable, which forces a scan. Use ordinary <code>AND</code>/<code>OR</code> conditions in <code>WHERE</code>; see <a rel="noopener" target="_blank" href="https://sqlserverguides.com/where-condition-in-sql-server/">the WHERE condition</a>. Reserve <code>CASE</code> for the <code>SELECT</code> list, <code>ORDER BY</code>, and aggregates.</p>



<p class="wp-block-paragraph">When you do filter on a computed bucket often, an index on the base column helps, and a computed column can store the label. Create indexes only after checking the actual execution plan; see <a rel="noopener" target="_blank" href="https://sqlserverguides.com/how-to-create-index-in-sql-server/">how to create an index in SQL Server</a> and <a rel="noopener" target="_blank" href="https://sqlserverguides.com/sql-query-optimization-tips/">SQL query optimization tips</a>. Every index slows writes and takes storage.</p>



<p class="wp-block-paragraph">In Azure SQL Database, use <strong>Query Store</strong>, which records query run times and plans, to confirm that a rewrite helped.</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph"><strong>Pro Tip:</strong> In my experience, <code>CASE</code> itself is rarely the performance problem. The slow part is almost always putting it in <code>WHERE</code> or joining on its result against a big table.</p>
</blockquote>



<h2 class="wp-block-heading">Secure and Test CASE-Based Reports</h2>



<p class="wp-block-paragraph">Reports that bucket customers or flag risk are business logic, so treat them like code.</p>



<ol class="wp-block-list">
<li><strong>Put shared rules in a view or stored procedure</strong> so every report uses the same definition.</li>



<li><strong>Use a least-privilege reporting user.</strong> Grant <code>SELECT</code> on the view only. See <a href="https://sqlserverguides.com/sql-server-grant-select-on-table/" target="_blank" rel="noopener">how to grant SELECT</a>.</li>



<li><strong>Use Microsoft Entra ID authentication</strong> and managed identities instead of SQL passwords in scripts.</li>



<li><strong>Require encrypted connections.</strong> Verify with <code>SELECT encrypt_option FROM sys.dm_exec_connections WHERE session_id = @@SPID;</code>.</li>



<li><strong>Test boundaries.</strong> Include values at each band edge, plus NULLs, in your test data.</li>
</ol>



<pre class="wp-block-preformatted"><code>CREATE USER [orders-report] FROM EXTERNAL PROVIDER;<br>GRANT SELECT ON OBJECT::dbo.vw_OrderSize TO [orders-report];</code></pre>



<p class="wp-block-paragraph"><code>FROM EXTERNAL PROVIDER</code> creates a contained database user mapped to an Entra identity, so no password is stored. The grant allows reading one view. If a bad <code>UPDATE ... CASE</code> ever damages data, Azure SQL Database supports point-in-time restore into a new database, so you can compare and copy back correct values. Confirm your retention window in advance.</p>



<h3 class="wp-block-heading">CASE WHEN Quality Checklist</h3>



<ul class="wp-block-list">
<li><strong>Order your branches.</strong> The first true condition wins, so put narrow rules before broad ones.</li>



<li><strong>Handle NULL explicitly.</strong> Use <code>IS NULL</code>, never <code>= NULL</code>, and put that branch first.</li>



<li><strong>Always add <code>ELSE</code>.</strong> A missing <code>ELSE</code> quietly returns NULL.</li>



<li><strong>Match result types.</strong> Every branch must convert to one compatible data type.</li>



<li><strong>Keep <code>CASE</code> out of <code>WHERE</code>.</strong> Use plain conditions to preserve index seeks.</li>



<li><strong>Preview before updating.</strong> Run the <code>SELECT</code>, use a transaction, and check <code>@@ROWCOUNT</code>.</li>
</ul>



<h3 class="wp-block-heading">Frequently Asked Questions</h3>



<h4 class="wp-block-heading">What is CASE WHEN in SQL Server?</h4>



<p class="wp-block-paragraph"><code>CASE WHEN</code> is a conditional expression that returns different values based on conditions. It evaluates <code>WHEN</code> tests in order and returns the result of the first true one, or the <code>ELSE</code> value if none match. You can use it in <code>SELECT</code>, <code>ORDER BY</code>, <code>GROUP BY</code>, aggregates, and <code>UPDATE</code>.</p>



<h4 class="wp-block-heading">What is the difference between simple and searched CASE?</h4>



<p class="wp-block-paragraph">Simple <code>CASE</code> compares one expression to a list of values for equality. Searched <code>CASE</code> evaluates full Boolean conditions, so it handles ranges, <code>AND</code>/<code>OR</code>, and <code>IS NULL</code>. Searched <code>CASE</code> is more flexible and is the safer default.</p>



<h4 class="wp-block-heading">How do I handle NULL in CASE WHEN?</h4>



<p class="wp-block-paragraph">Use <code>WHEN column IS NULL</code>, not <code>= NULL</code>, and place it first so NULL rows do not fall into <code>ELSE</code>. For simple replacements, <code>COALESCE</code> or <code>ISNULL</code> may be shorter.</p>



<h4 class="wp-block-heading">Can I use CASE WHEN in a WHERE clause?</h4>



<p class="wp-block-paragraph">Yes, but it often prevents index seeks and slows queries. Prefer ordinary conditions with <code>AND</code> and <code>OR</code> in <code>WHERE</code>, and use <code>CASE</code> in the select list, <code>ORDER BY</code>, or aggregates.</p>



<h4 class="wp-block-heading">How many conditions can a CASE statement have?</h4>



<p class="wp-block-paragraph">There is no small fixed limit on the number of <code>WHEN</code> branches, but <code>CASE</code> expressions can nest only up to 10 levels. If you need dozens of rules, move them into a lookup table and join to it.</p>



<p class="wp-block-paragraph">You learned how to use CASE WHEN in SQL Server for labels, custom sorting, conditional totals, and updates, and how to avoid NULL, data type, and performance traps. Put the NULL branch first, always include <code>ELSE</code>, and preview every <code>UPDATE</code> with a <code>SELECT</code> and a transaction before you commit. I hope you found this article helpful.</p>



<p class="wp-block-paragraph">You May Also Like</p>



<ul class="wp-block-list">
<li><a href="https://sqlserverguides.com/sql-select-query-examples/" target="_blank" rel="noopener">SQL SELECT query examples</a></li>



<li><a href="https://sqlserverguides.com/sql-server-top-clause/" target="_blank" rel="noopener">SQL Server TOP clause</a></li>



<li><a href="https://sqlserverguides.com/sql-wildcard-characters/" target="_blank" rel="noopener">SQL wildcard characters</a></li>



<li><a href="https://sqlserverguides.com/how-to-use-if-else-in-sql-server-stored-procedure/" target="_blank" rel="noopener">How to use IF ELSE in a SQL Server stored procedure</a></li>



<li><a href="https://sqlserverguides.com/sql-cheat-sheet/" target="_blank" rel="noopener">SQL cheat sheet</a></li>
</ul>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How to Find Percentage of Total in SQL</title>
		<link>https://sqlserverguides.com/how-to-find-percentage-of-total-in-sql-server/</link>
		
		<dc:creator><![CDATA[Bijay Kumar Sahoo]]></dc:creator>
		<pubDate>Tue, 03 Nov 2026 17:06:01 +0000</pubDate>
				<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[How to Find Percentage of Total in SQL]]></category>
		<guid isPermaLink="false">https://sqlserverguides.com/?p=24061</guid>

					<description><![CDATA[A finance director once forwarded me a screenshot of her new sales dashboard. Every region showed a share of revenue of exactly 0 percent, except the largest one, which showed 100. The query looked fine. It divided each region&#8217;s sales by total sales and multiplied by 100. The columns held whole numbers, and SQL Server ... <a title="How to Find Percentage of Total in SQL" class="read-more" href="https://sqlserverguides.com/how-to-find-percentage-of-total-in-sql-server/" aria-label="Read more about How to Find Percentage of Total in SQL">Read more</a>]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">A finance director once forwarded me a screenshot of her new sales dashboard. Every region showed a share of revenue of exactly 0 percent, except the largest one, which showed 100. The query looked fine. It divided each region&#8217;s sales by total sales and multiplied by 100. The columns held whole numbers, and SQL Server did what it does with whole numbers: it threw away the decimals before the multiplication.</p>



<p class="wp-block-paragraph">That is the most common trap when you learn <strong>how to find percentage of total in SQL</strong>. The idea is simple: divide each part by the whole. Getting it right means choosing the right way to compute the whole, handling integer math and zero totals, and deciding what &#8220;total&#8221; means after filters and groups. This guide builds the answer step by step in T-SQL, then covers performance and secure reporting in SQL Server and Azure SQL Database.</p>



<h2 class="wp-block-heading">Create a Practice Table</h2>



<p class="wp-block-paragraph">A <strong>schema</strong> is the structure of your tables. Use a small sales table so you can check every result by hand.</p>



<pre class="wp-block-preformatted"><code>CREATE TABLE dbo.Sales (<br>    SalesID  INT IDENTITY(1,1) PRIMARY KEY,<br>    Region   VARCHAR(20)   NOT NULL,<br>    Category VARCHAR(20)   NOT NULL,<br>    Amount   DECIMAL(10,2) NOT NULL<br>);<br><br>INSERT INTO dbo.Sales (Region, Category, Amount)<br>VALUES<br> ('West',  'Hardware', 1200.00),<br> ('West',  'Software',  800.00),<br> ('East',  'Hardware',  600.00),<br> ('East',  'Software', 1400.00),<br> ('South', 'Hardware',  500.00),<br> ('South', 'Software',  500.00);</code></pre>



<p class="wp-block-paragraph">After executing the above query, I got the expected output as shown in the screenshot below.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="888" height="452" src="https://sqlserverguides.com/wp-content/uploads/2026/11/how-to-find-percentage-of-total-in-sql.jpg" alt="how to find percentage of total in sql" class="wp-image-24062" srcset="https://sqlserverguides.com/wp-content/uploads/2026/11/how-to-find-percentage-of-total-in-sql.jpg 888w, https://sqlserverguides.com/wp-content/uploads/2026/11/how-to-find-percentage-of-total-in-sql-766x390.jpg 766w, https://sqlserverguides.com/wp-content/uploads/2026/11/how-to-find-percentage-of-total-in-sql-300x153.jpg 300w" sizes="auto, (max-width: 888px) 100vw, 888px" /></figure>
</div>

<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="962" height="477" src="https://sqlserverguides.com/wp-content/uploads/2026/11/sql-how-to-calculate-percentage-of-total.jpg" alt="sql how to calculate percentage of total" class="wp-image-24063" srcset="https://sqlserverguides.com/wp-content/uploads/2026/11/sql-how-to-calculate-percentage-of-total.jpg 962w, https://sqlserverguides.com/wp-content/uploads/2026/11/sql-how-to-calculate-percentage-of-total-300x149.jpg 300w, https://sqlserverguides.com/wp-content/uploads/2026/11/sql-how-to-calculate-percentage-of-total-766x380.jpg 766w" sizes="auto, (max-width: 962px) 100vw, 962px" /></figure>
</div>


<p class="wp-block-paragraph">Run this only in a test database, because it inserts rows. The grand total is 5,000. Region totals are West 2,000, East 2,000, and South 1,000, so the expected shares are 40, 40, and 20 percent. Category totals are Hardware 2,300 (46 percent) and Software 2,700 (54 percent). Knowing the answers up front lets you verify each query.</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph"><strong>Pro Tip:</strong> In my experience, a six-row table with totals you can add in your head catches more percentage bugs than a million-row production table. I always verify the logic on tiny data first.</p>
</blockquote>



<h3 class="wp-block-heading">The Basic Idea and the Integer Division Trap</h3>



<p class="wp-block-paragraph">A percentage of total is <code>part / total * 100</code>. In T-SQL, the data type of the operands decides how division behaves. If both sides are integers, SQL Server performs <strong>integer division</strong> and drops the remainder.</p>



<pre class="wp-block-preformatted"><code>SELECT 1200 / 5000 * 100      AS WrongPercent,   <em>-- 0</em><br>       1200 * 100.0 / 5000    AS RightPercent;   <em>-- 24.000000</em></code></pre>



<p class="wp-block-paragraph">After executing the above query, I got the expected output as shown in the screenshot below.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="199" src="https://sqlserverguides.com/wp-content/uploads/2026/11/how-to-find-percentage-of-total-in-sql-server-1024x199.jpg" alt="how to find percentage of total in sql server" class="wp-image-24064" srcset="https://sqlserverguides.com/wp-content/uploads/2026/11/how-to-find-percentage-of-total-in-sql-server-1024x199.jpg 1024w, https://sqlserverguides.com/wp-content/uploads/2026/11/how-to-find-percentage-of-total-in-sql-server-300x58.jpg 300w, https://sqlserverguides.com/wp-content/uploads/2026/11/how-to-find-percentage-of-total-in-sql-server-763x148.jpg 763w, https://sqlserverguides.com/wp-content/uploads/2026/11/how-to-find-percentage-of-total-in-sql-server.jpg 1047w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p class="wp-block-paragraph">The first expression divides 1200 by 5000 and gets 0 because both are integers, then multiplies 0 by 100. The second multiplies by <code>100.0</code> first, which makes the whole expression decimal. Always start with <code>100.0</code> or cast a value to <code>DECIMAL</code> before dividing. For more on conversions, see <a rel="noopener" target="_blank" href="https://sqlserverguides.com/cast-function-in-sql-server/">the CAST function</a>.</p>



<p class="wp-block-paragraph">This is exactly what broke the finance dashboard. In our table <code>Amount</code> is already <code>DECIMAL</code>, but in many real tables the measure is an <code>INT</code> count.</p>



<h3 class="wp-block-heading">How to Find Percentage of Total in SQL With a Subquery</h3>



<p class="wp-block-paragraph">The oldest method computes the total in a separate query. A <strong>scalar subquery</strong> returns a single value and can be used inside another query. See <a rel="noopener" target="_blank" href="https://sqlserverguides.com/sql-subquery/">SQL subqueries</a>.</p>



<pre class="wp-block-preformatted"><code>SELECT<br>    SalesID,<br>    Region,<br>    Amount,<br>    CAST(Amount * 100.0 / (SELECT SUM(Amount) FROM dbo.Sales) AS DECIMAL(5,2)) AS PctOfTotal<br>FROM dbo.Sales<br>ORDER BY SalesID;</code></pre>



<p class="wp-block-paragraph">After executing the above query, I got the expected output as shown in the screenshot below.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="337" src="https://sqlserverguides.com/wp-content/uploads/2026/11/how-to-calculate-percentage-of-total-in-sql-1024x337.jpg" alt="how to calculate percentage of total in sql" class="wp-image-24065" srcset="https://sqlserverguides.com/wp-content/uploads/2026/11/how-to-calculate-percentage-of-total-in-sql-1024x337.jpg 1024w, https://sqlserverguides.com/wp-content/uploads/2026/11/how-to-calculate-percentage-of-total-in-sql-300x99.jpg 300w, https://sqlserverguides.com/wp-content/uploads/2026/11/how-to-calculate-percentage-of-total-in-sql-1536x506.jpg 1536w, https://sqlserverguides.com/wp-content/uploads/2026/11/how-to-calculate-percentage-of-total-in-sql-765x252.jpg 765w, https://sqlserverguides.com/wp-content/uploads/2026/11/how-to-calculate-percentage-of-total-in-sql.jpg 1585w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p class="wp-block-paragraph">The inner <code>SELECT SUM(Amount)</code> calculates 5,000 once, and each row divides by it. Results are 24.00, 16.00, 12.00, 28.00, 10.00, and 10.00. They add up to 100.</p>



<p class="wp-block-paragraph">This approach works on any SQL Server version and is easy to read. The trade-off is that SQL Server reads the table for the main query and again for the total. On small tables that is trivial. On big tables the second scan adds cost. For the <code>SUM</code> function itself, see <a rel="noopener" target="_blank" href="https://sqlserverguides.com/how-to-use-sum-function-in-sql-server/">how to use SUM in SQL Server</a>.</p>



<h3 class="wp-block-heading">Use a Window Function for the Cleanest Result</h3>



<p class="wp-block-paragraph">A <strong>window function</strong> calculates across a set of rows without collapsing them. With <code>SUM(Amount) OVER ()</code>, the empty parentheses mean &#8220;the whole result set.&#8221; Read more in <a rel="noopener" target="_blank" href="https://sqlserverguides.com/window-functions-in-sql-server/">window functions in SQL Server</a> and <a rel="noopener" target="_blank" href="https://sqlserverguides.com/sql-over-clause/">the OVER clause</a>.</p>



<pre class="wp-block-preformatted"><code>SELECT<br>    SalesID,<br>    Region,<br>    Amount,<br>    CAST(Amount * 100.0 / SUM(Amount) OVER () AS DECIMAL(5,2)) AS PctOfTotal<br>FROM dbo.Sales<br>ORDER BY SalesID;</code></pre>



<p class="wp-block-paragraph">After executing the above query, I got the expected output as shown in the screenshot below.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="360" src="https://sqlserverguides.com/wp-content/uploads/2026/11/how-to-find-percentage-of-total-sql-1024x360.jpg" alt="how to find percentage of total sql" class="wp-image-24066" srcset="https://sqlserverguides.com/wp-content/uploads/2026/11/how-to-find-percentage-of-total-sql-1024x360.jpg 1024w, https://sqlserverguides.com/wp-content/uploads/2026/11/how-to-find-percentage-of-total-sql-300x105.jpg 300w, https://sqlserverguides.com/wp-content/uploads/2026/11/how-to-find-percentage-of-total-sql-766x269.jpg 766w, https://sqlserverguides.com/wp-content/uploads/2026/11/how-to-find-percentage-of-total-sql.jpg 1444w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p class="wp-block-paragraph">This returns the same numbers as the subquery version. SQL Server calculates the total in the same pass and attaches it to every row. The query is shorter, and it avoids repeating the table name. This is the method I recommend for most reports.</p>



<h3 class="wp-block-heading">Protect Against Divide-by-Zero</h3>



<p class="wp-block-paragraph">If the total is zero, for example when a filter returns no sales or all amounts net to zero, you get a divide-by-zero error. Use <code>NULLIF</code>, which returns NULL when two values are equal, so the division returns NULL instead of failing. See <a rel="noopener" target="_blank" href="https://sqlserverguides.com/nullif-vs-coalesce/">NULLIF vs. COALESCE</a>.</p>



<pre class="wp-block-preformatted"><code>SELECT<br>    Region,<br>    Amount,<br>    CAST(Amount * 100.0 / NULLIF(SUM(Amount) OVER (), 0) AS DECIMAL(5,2)) AS PctOfTotal<br>FROM dbo.Sales;</code></pre>



<p class="wp-block-paragraph">After executing the above query, I got the expected output as shown in the screenshot below.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="267" src="https://sqlserverguides.com/wp-content/uploads/2026/11/calculate-percentage-of-total-in-sql-1024x267.jpg" alt="calculate percentage of total in sql" class="wp-image-24067" srcset="https://sqlserverguides.com/wp-content/uploads/2026/11/calculate-percentage-of-total-in-sql-1024x267.jpg 1024w, https://sqlserverguides.com/wp-content/uploads/2026/11/calculate-percentage-of-total-in-sql-767x200.jpg 767w, https://sqlserverguides.com/wp-content/uploads/2026/11/calculate-percentage-of-total-in-sql-300x78.jpg 300w, https://sqlserverguides.com/wp-content/uploads/2026/11/calculate-percentage-of-total-in-sql-1536x400.jpg 1536w, https://sqlserverguides.com/wp-content/uploads/2026/11/calculate-percentage-of-total-in-sql.jpg 1581w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p class="wp-block-paragraph">When the total is 0, the denominator becomes NULL and the percentage is NULL. Decide whether the report should show NULL, 0, or a message. Wrap with <code>COALESCE</code> if you want zero.</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph"><strong>Pro Tip:</strong> I once watched a nightly report fail because a single region had no sales on a holiday. Adding <code>NULLIF</code> to every denominator is now a habit, not an afterthought.</p>
</blockquote>



<h3 class="wp-block-heading">Percentage of Total by Group</h3>



<p class="wp-block-paragraph">Business questions usually ask for shares by region or category, not by row. Combine <code>GROUP BY</code> with a window function over the grouped results. See <a rel="noopener" target="_blank" href="https://sqlserverguides.com/how-to-use-group-by-clause-in-sql-server/">how to use GROUP BY in SQL Server</a>.</p>



<pre class="wp-block-preformatted"><code>SELECT<br>    Region,<br>    SUM(Amount) AS RegionSales,<br>    CAST(SUM(Amount) * 100.0 / SUM(SUM(Amount)) OVER () AS DECIMAL(5,2)) AS PctOfTotal<br>FROM dbo.Sales<br>GROUP BY Region<br>ORDER BY RegionSales DESC;</code></pre>



<p class="wp-block-paragraph">After executing the above query, I got the expected output as shown in the screenshot below.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="228" src="https://sqlserverguides.com/wp-content/uploads/2026/11/Find-Percentage-of-Total-in-SQL-server-1024x228.jpg" alt="Find Percentage of Total in SQL server" class="wp-image-24068" srcset="https://sqlserverguides.com/wp-content/uploads/2026/11/Find-Percentage-of-Total-in-SQL-server-1024x228.jpg 1024w, https://sqlserverguides.com/wp-content/uploads/2026/11/Find-Percentage-of-Total-in-SQL-server-300x67.jpg 300w, https://sqlserverguides.com/wp-content/uploads/2026/11/Find-Percentage-of-Total-in-SQL-server-767x171.jpg 767w, https://sqlserverguides.com/wp-content/uploads/2026/11/Find-Percentage-of-Total-in-SQL-server-1536x342.jpg 1536w, https://sqlserverguides.com/wp-content/uploads/2026/11/Find-Percentage-of-Total-in-SQL-server.jpg 1602w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p class="wp-block-paragraph">The inner <code>SUM(Amount)</code> is the group total. The outer <code>SUM(... ) OVER ()</code> adds those group totals together to get the grand total. This works because window functions run after <code>GROUP BY</code>. The result is West 40.00, East 40.00, and South 20.00.</p>



<p class="wp-block-paragraph">The nested <code>SUM(SUM(...))</code> looks odd the first time you see it. If it confuses your team, use a <strong>CTE</strong> (common table expression), a named temporary result you can query immediately. Compare it with a temp table in <a rel="noopener" target="_blank" href="https://sqlserverguides.com/sql-server-cte-vs-temp-table/">CTE vs. temp table</a>.</p>



<pre class="wp-block-preformatted"><code>WITH RegionTotals AS (<br>    SELECT Region, SUM(Amount) AS RegionSales<br>    FROM dbo.Sales<br>    GROUP BY Region<br>)<br>SELECT<br>    Region,<br>    RegionSales,<br>    CAST(RegionSales * 100.0 / SUM(RegionSales) OVER () AS DECIMAL(5,2)) AS PctOfTotal<br>FROM RegionTotals<br>ORDER BY RegionSales DESC;</code></pre>



<p class="wp-block-paragraph">After executing the above query, I got the expected output as shown in the screenshot below.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="371" src="https://sqlserverguides.com/wp-content/uploads/2026/11/calculate-percentage-of-total-sql-server-1024x371.jpg" alt="calculate percentage of total sql server" class="wp-image-24069" srcset="https://sqlserverguides.com/wp-content/uploads/2026/11/calculate-percentage-of-total-sql-server-1024x371.jpg 1024w, https://sqlserverguides.com/wp-content/uploads/2026/11/calculate-percentage-of-total-sql-server-300x109.jpg 300w, https://sqlserverguides.com/wp-content/uploads/2026/11/calculate-percentage-of-total-sql-server-1536x557.jpg 1536w, https://sqlserverguides.com/wp-content/uploads/2026/11/calculate-percentage-of-total-sql-server-767x278.jpg 767w, https://sqlserverguides.com/wp-content/uploads/2026/11/calculate-percentage-of-total-sql-server.jpg 1586w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p class="wp-block-paragraph">It returns the same result in two clear steps: aggregate first, then calculate the share.</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph"><strong>Pro Tip:</strong> I use the CTE version when the query will be maintained by someone else. Two readable steps beat one clever expression that nobody wants to touch.</p>
</blockquote>



<h3 class="wp-block-heading">Percentage Within a Group</h3>



<p class="wp-block-paragraph">Sometimes the &#8220;whole&#8221; is a subgroup. For example, you want each category&#8217;s share within its region. Add <code>PARTITION BY</code> to the window, which restarts the calculation for each group. See <a rel="noopener" target="_blank" href="https://sqlserverguides.com/sql-partition-by/">PARTITION BY</a>.</p>



<pre class="wp-block-preformatted"><code>SELECT<br>    Region,<br>    Category,<br>    SUM(Amount) AS CategorySales,<br>    CAST(SUM(Amount) * 100.0<br>         / SUM(SUM(Amount)) OVER (PARTITION BY Region) AS DECIMAL(5,2)) AS PctOfRegion<br>FROM dbo.Sales<br>GROUP BY Region, Category<br>ORDER BY Region, Category;</code></pre>



<p class="wp-block-paragraph">With <code>PARTITION BY Region</code>, the denominator is that region&#8217;s total. The output is East Hardware 30.00 and Software 70.00, South 50.00 and 50.00, and West Hardware 60.00 and Software 40.00. Each region&#8217;s percentages add to 100.</p>



<p class="wp-block-paragraph">Be clear about which total you are using. The three versions you may need are percent of the grand total, percent of the group, and percent of a filtered set. Label the column so readers know, for example <code>PctOfRegion</code> rather than just <code>Pct</code>.</p>



<h3 class="wp-block-heading">Combine Percentages With Filters Correctly</h3>



<p class="wp-block-paragraph">Filters change the denominator. This catches many people. A <code>WHERE</code> clause runs before window functions, so the total only includes the filtered rows.</p>



<pre class="wp-block-preformatted"><code><em>-- Percent of Hardware sales only (denominator excludes Software)</em><br>SELECT Region,<br>       SUM(Amount) AS HardwareSales,<br>       CAST(SUM(Amount) * 100.0 / SUM(SUM(Amount)) OVER () AS DECIMAL(5,2)) AS PctOfHardware<br>FROM dbo.Sales<br>WHERE Category = 'Hardware'<br>GROUP BY Region;</code></pre>



<p class="wp-block-paragraph">Here the total is 2,300, not 5,000. If you want each region&#8217;s Hardware sales as a share of all sales, calculate the percentage first and filter afterward:</p>



<pre class="wp-block-preformatted"><code>WITH Shares AS (<br>    SELECT Region, Category, Amount,<br>           Amount * 100.0 / SUM(Amount) OVER () AS PctOfGrandTotal<br>    FROM dbo.Sales<br>)<br>SELECT Region, Category, CAST(PctOfGrandTotal AS DECIMAL(5,2)) AS PctOfGrandTotal<br>FROM Shares<br>WHERE Category = 'Hardware';</code></pre>



<p class="wp-block-paragraph">The CTE calculates shares against all 5,000, then the outer <code>WHERE</code> filters the rows. The difference between <code>WHERE</code> before and after the window is explained further in <a rel="noopener" target="_blank" href="https://sqlserverguides.com/sql-having-vs-where/">HAVING vs. WHERE</a>.</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph"><strong>Pro Tip:</strong> When a stakeholder says &#8220;the numbers don&#8217;t add up,&#8221; I ask one question: &#8220;Percent of what?&#8221; Nine times out of ten the filter changed the denominator.</p>
</blockquote>



<h3 class="wp-block-heading">Add a Cumulative Percentage</h3>



<p class="wp-block-paragraph">A running total of percentages shows how fast sales accumulate, which supports Pareto-style questions like &#8220;which regions make up 80 percent of revenue?&#8221;</p>



<pre class="wp-block-preformatted"><code>WITH RegionTotals AS (<br>    SELECT Region, SUM(Amount) AS RegionSales<br>    FROM dbo.Sales<br>    GROUP BY Region<br>)<br>SELECT<br>    Region,<br>    RegionSales,<br>    CAST(SUM(RegionSales) OVER (ORDER BY RegionSales DESC, Region<br>                                ROWS UNBOUNDED PRECEDING) * 100.0<br>         / SUM(RegionSales) OVER () AS DECIMAL(5,2)) AS CumulativePct<br>FROM RegionTotals<br>ORDER BY RegionSales DESC, Region;</code></pre>



<p class="wp-block-paragraph">The window with <code>ORDER BY</code> and <code>ROWS UNBOUNDED PRECEDING</code> adds up values from the first row to the current one. With ties between West and East, the tie-breaker <code>Region</code> keeps the order stable. The result is West 40.00, East 80.00, and South 100.00. Always specify the <code>ROWS</code> frame explicitly; the default frame can behave differently with ties and is usually slower.</p>



<h3 class="wp-block-heading">Format and Round the Results</h3>



<p class="wp-block-paragraph">Keep percentages numeric in the database and format them in the application when possible. If you need text in T-SQL, use <code>CAST</code> and <code>CONCAT</code>:</p>



<pre class="wp-block-preformatted"><code>SELECT Region,<br>       CONCAT(CAST(SUM(Amount) * 100.0 / SUM(SUM(Amount)) OVER () AS DECIMAL(5,1)), '%') AS Share<br>FROM dbo.Sales<br>GROUP BY Region;</code></pre>



<p class="wp-block-paragraph">For more on rounding, see <a rel="noopener" target="_blank" href="https://sqlserverguides.com/format-number-to-2-decimal-places-in-sql-server/">formatting numbers to two decimal places</a>. Be aware that rounded values may not sum to exactly 100. Three shares of 33.33 add to 99.99. That is normal. If an exact 100 is required, adjust the largest item or round only at display time and explain that totals may differ slightly.</p>



<h3 class="wp-block-heading">Make It Fast and Reusable</h3>



<p class="wp-block-paragraph">A window over the whole result must see every row to compute the total, so these queries scan or aggregate the data they use. Three habits keep them fast:</p>



<ul class="wp-block-list">
<li><strong>Aggregate before windowing.</strong> The grouped version works on a few rows after <code>GROUP BY</code>, not thousands of detail rows.</li>



<li><strong>Index the columns involved.</strong> An index on <code>Region</code> that includes <code>Amount</code> lets SQL Server read a narrow structure. See <a href="https://sqlserverguides.com/how-to-create-index-in-sql-server/" target="_blank" rel="noopener">how to create an index in SQL Server</a>. Check the execution plan first, because every index slows inserts and updates.</li>



<li><strong>Pre-aggregate for dashboards.</strong> If a report reads hundreds of millions of rows, store daily or monthly totals in a summary table and calculate percentages from that.</li>
</ul>



<p class="wp-block-paragraph">For large analytic tables, a <strong>columnstore index</strong>, which stores data by column and compresses it, can speed aggregations. Test it against your workload first. For more tips, see <a rel="noopener" target="_blank" href="https://sqlserverguides.com/sql-query-optimization-tips/">SQL query optimization tips</a>.</p>



<p class="wp-block-paragraph">Package the logic in a <strong>view</strong> so every report uses the same definition of &#8220;percent of total.&#8221; See <a rel="noopener" target="_blank" href="https://sqlserverguides.com/sql-server-views/">SQL Server views</a>.</p>



<pre class="wp-block-preformatted"><code>CREATE OR ALTER VIEW dbo.vw_RegionShare<br>AS<br>SELECT<br>    Region,<br>    SUM(Amount) AS RegionSales,<br>    CAST(SUM(Amount) * 100.0 / NULLIF(SUM(SUM(Amount)) OVER (), 0) AS DECIMAL(5,2)) AS PctOfTotal<br>FROM dbo.Sales<br>GROUP BY Region;</code></pre>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph"><strong>Pro Tip:</strong> In my experience, definitions drift when ten reports each calculate their own percentage. A single view makes the denominator an agreed business rule.</p>
</blockquote>



<h3 class="wp-block-heading">Frequently Asked Questions</h3>



<h4 class="wp-block-heading">How do I calculate percentage of total in SQL Server?</h4>



<p class="wp-block-paragraph">Divide each value by the total and multiply by 100.0, for example <code>Amount * 100.0 / SUM(Amount) OVER ()</code>. The empty <code>OVER ()</code> makes the window cover the whole result, so every row gets the grand total.</p>



<h4 class="wp-block-heading">Why does my percentage of total return 0?</h4>



<p class="wp-block-paragraph">You are probably dividing two integers, and SQL Server drops the decimals. Multiply by <code>100.0</code> before dividing or cast one value to <code>DECIMAL</code>.</p>



<h4 class="wp-block-heading">How do I calculate percentage within each group?</h4>



<p class="wp-block-paragraph">Use <code>PARTITION BY</code> in the window, such as <code>SUM(Amount) OVER (PARTITION BY Region)</code>. The denominator then becomes each group&#8217;s total, and the percentages in each group add to 100.</p>



<h4 class="wp-block-heading">How do I avoid divide-by-zero errors?</h4>



<p class="wp-block-paragraph">Wrap the denominator in <code>NULLIF(total, 0)</code>. When the total is zero, the result becomes NULL instead of an error, and you can replace it with <code>COALESCE</code> if you prefer zero.</p>



<h4 class="wp-block-heading">Is a subquery or a window function better for percent of total?</h4>



<p class="wp-block-paragraph">Both give the same answer. The window function is shorter and calculates the total in the same pass, while a scalar subquery works on every version and is easy to read. For large tables, compare execution plans.</p>



<p class="wp-block-paragraph">You learned how to find percentage of total in SQL using subqueries, window functions, grouped totals, and <code>PARTITION BY</code>, and how to avoid integer division and divide-by-zero errors. Name your denominator clearly, verify results against a hand-calculated total, and give report users read-only access through a view. I hope you found this article helpful.</p>



<p class="wp-block-paragraph">You May Also Like</p>



<ul class="wp-block-list">
<li><a href="https://sqlserverguides.com/how-to-use-avg-function-in-sql-server/" target="_blank" rel="noopener">How to use the AVG function in SQL Server</a></li>



<li><a href="https://sqlserverguides.com/how-to-use-count-function-in-sql-server/" target="_blank" rel="noopener">How to use the COUNT function in SQL Server</a></li>



<li><a href="https://sqlserverguides.com/sql-rank-vs-dense-rank/" target="_blank" rel="noopener">RANK vs. DENSE_RANK in SQL</a></li>



<li><a href="https://sqlserverguides.com/sql-server-floor/" target="_blank" rel="noopener">SQL Server FLOOR function</a></li>



<li><a href="https://sqlserverguides.com/sql-server-group-by-date/" target="_blank" rel="noopener">How to group by date in SQL Server</a></li>
</ul>



<p class="wp-block-paragraph"></p>
]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>

<!--
Performance optimized by W3 Total Cache. Learn more: https://www.boldgrid.com/w3-total-cache/?utm_source=w3tc&utm_medium=footer_comment&utm_campaign=free_plugin

Page Caching using Disk: Enhanced 

Served from: sqlserverguides.com @ 2026-11-19 12:27:15 by W3 Total Cache
-->