<?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/"
	>

<channel>
	<title>Unique Index &#8211; Database Research &amp; Development</title>
	<atom:link href="https://www.dbrnd.com/tag/unique-index/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.dbrnd.com</link>
	<description>BIGData &#124; NoSQL &#124; MSSQL &#124; MySQL &#124; PostgreSQL</description>
	<lastBuildDate>Thu, 28 Sep 2017 12:28:16 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=7.0.6</generator>
	<item>
		<title>SQL Server Interview: What is the difference between Unique Constraint and Unique Index?</title>
		<link>https://www.dbrnd.com/2017/07/sql-server-interview-what-is-the-difference-between-unique-constraint-and-unique-index/</link>
					<comments>https://www.dbrnd.com/2017/07/sql-server-interview-what-is-the-difference-between-unique-constraint-and-unique-index/#comments</comments>
		
		<dc:creator><![CDATA[Anvesh Patel]]></dc:creator>
		<pubDate>Tue, 11 Jul 2017 16:16:14 +0000</pubDate>
				<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[SQL Server Interview]]></category>
		<category><![CDATA[Anvesh Patel]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[database research and development]]></category>
		<category><![CDATA[dbrnd]]></category>
		<category><![CDATA[SQL Query]]></category>
		<category><![CDATA[SQL Server Administrator]]></category>
		<category><![CDATA[SQL Server Error]]></category>
		<category><![CDATA[SQL Server Monitoring]]></category>
		<category><![CDATA[SQL Server Performance Tuning]]></category>
		<category><![CDATA[SQL Server Programming]]></category>
		<category><![CDATA[SQL Server Tips and Tricks]]></category>
		<category><![CDATA[TSQL]]></category>
		<category><![CDATA[UNIQUE CONSTRAINT]]></category>
		<category><![CDATA[Unique Index]]></category>
		<guid isPermaLink="false">https://www.dbrnd.com/?p=5650</guid>

					<description><![CDATA[I am sharing this interview question for Database Developer who has around 1 or 2 years of experience. Many times, I have asked the difference between Unique Constraint and Unique Index but most of the time people answers were like &#8220;No difference &#8211; Both are same&#8221;. This is a wrong answer. Which one is the [&#8230;]]]></description>
										<content:encoded><![CDATA[<p><a class="a2a_button_facebook" href="https://www.addtoany.com/add_to/facebook?linkurl=https%3A%2F%2Fwww.dbrnd.com%2F2017%2F07%2Fsql-server-interview-what-is-the-difference-between-unique-constraint-and-unique-index%2F&amp;linkname=SQL%20Server%20Interview%3A%20What%20is%20the%20difference%20between%20Unique%20Constraint%20and%20Unique%20Index%3F" title="Facebook" rel="nofollow noopener" target="_blank"></a><a class="a2a_button_twitter" href="https://www.addtoany.com/add_to/twitter?linkurl=https%3A%2F%2Fwww.dbrnd.com%2F2017%2F07%2Fsql-server-interview-what-is-the-difference-between-unique-constraint-and-unique-index%2F&amp;linkname=SQL%20Server%20Interview%3A%20What%20is%20the%20difference%20between%20Unique%20Constraint%20and%20Unique%20Index%3F" title="Twitter" rel="nofollow noopener" target="_blank"></a><a class="a2a_button_linkedin" href="https://www.addtoany.com/add_to/linkedin?linkurl=https%3A%2F%2Fwww.dbrnd.com%2F2017%2F07%2Fsql-server-interview-what-is-the-difference-between-unique-constraint-and-unique-index%2F&amp;linkname=SQL%20Server%20Interview%3A%20What%20is%20the%20difference%20between%20Unique%20Constraint%20and%20Unique%20Index%3F" title="LinkedIn" rel="nofollow noopener" target="_blank"></a><a class="a2a_button_pinterest" href="https://www.addtoany.com/add_to/pinterest?linkurl=https%3A%2F%2Fwww.dbrnd.com%2F2017%2F07%2Fsql-server-interview-what-is-the-difference-between-unique-constraint-and-unique-index%2F&amp;linkname=SQL%20Server%20Interview%3A%20What%20is%20the%20difference%20between%20Unique%20Constraint%20and%20Unique%20Index%3F" title="Pinterest" rel="nofollow noopener" target="_blank"></a><a class="a2a_button_reddit" href="https://www.addtoany.com/add_to/reddit?linkurl=https%3A%2F%2Fwww.dbrnd.com%2F2017%2F07%2Fsql-server-interview-what-is-the-difference-between-unique-constraint-and-unique-index%2F&amp;linkname=SQL%20Server%20Interview%3A%20What%20is%20the%20difference%20between%20Unique%20Constraint%20and%20Unique%20Index%3F" title="Reddit" rel="nofollow noopener" target="_blank"></a><a class="a2a_button_pocket" href="https://www.addtoany.com/add_to/pocket?linkurl=https%3A%2F%2Fwww.dbrnd.com%2F2017%2F07%2Fsql-server-interview-what-is-the-difference-between-unique-constraint-and-unique-index%2F&amp;linkname=SQL%20Server%20Interview%3A%20What%20is%20the%20difference%20between%20Unique%20Constraint%20and%20Unique%20Index%3F" title="Pocket" rel="nofollow noopener" target="_blank"></a><a class="a2a_dd addtoany_share_save addtoany_share" href="https://www.addtoany.com/share#url=https%3A%2F%2Fwww.dbrnd.com%2F2017%2F07%2Fsql-server-interview-what-is-the-difference-between-unique-constraint-and-unique-index%2F&#038;title=SQL%20Server%20Interview%3A%20What%20is%20the%20difference%20between%20Unique%20Constraint%20and%20Unique%20Index%3F" data-a2a-url="https://www.dbrnd.com/2017/07/sql-server-interview-what-is-the-difference-between-unique-constraint-and-unique-index/" data-a2a-title="SQL Server Interview: What is the difference between Unique Constraint and Unique Index?"></a></p><p>I am sharing this interview question for Database Developer who has around 1 or 2 years of experience. </p>
<p>Many times, I have asked the difference between Unique Constraint and Unique Index but most of the time people answers were like &#8220;No difference &#8211; Both are same&#8221;. <strong>This is a wrong answer</strong>.</p>
<p><strong>Which one is the better:</strong></p>
<blockquote><p>When you are creating a column using UNIQUE constraint or UNIQUE Index, in both the cases SQL Server by default creates a unique non-clustered index.<br />
There is no any performance difference between these two, so you can use any one of this.<br />
But still, there are few minor differences between Unique Constraint and Unique Index. </p></blockquote>
<p><strong>Disable:</strong></p>
<blockquote><p><strong>Unique Constraint:</strong> You cannot disable the Unique Constraint, you will get below error:<br />
Msg 4916, Level 16, State 0, Line 1<br />
Could not enable or disable the constraint. See previous errors.</p>
<p><strong>Unique Index:</strong> You can disable it</p>
<pre class="crayon-plain-tag">ALTER INDEX Index_name ON Table_name DISABLE</pre>
 </p></blockquote>
<p><strong>Errors:</strong> The error messages for both violations are also different</p>
<blockquote><p><strong>Unique Constraint violation error:</strong></p>
<pre class="crayon-plain-tag">Msg 2627, Level 14, State 1, Line 1
Violation of UNIQUE KEY constraint 'uk_tb'. Cannot insert duplicate key in object 'dbo.mytab'. The duplicate key value is (1).
The statement has been terminated.</pre> </p>
<p><strong>Unique Index violation error:</strong></p>
<pre class="crayon-plain-tag">Msg 2601, Level 14, State 1, Line 1
Cannot insert duplicate key row in object 'dbo.col1' with unique index 'id_tb'. The duplicate key value is (1).
The statement has been terminated.</pre>
</p></blockquote>
<p><strong>Filters:</strong></p>
<blockquote><p><strong>Unique Constraint:</strong> You cannot add filter in Unique Constraint.<br />
<strong>Unique Index:</strong> You can add filter in Unique Index:</p>
<pre class="crayon-plain-tag">CREATE UNIQUE NONCLUSTERED INDEX idx_name 
ON dbo.table_name(column_name) WHERE column_name ='M'</pre>
 </p></blockquote>
]]></content:encoded>
					
					<wfw:commentRss>https://www.dbrnd.com/2017/07/sql-server-interview-what-is-the-difference-between-unique-constraint-and-unique-index/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
		<item>
		<title>SQL Server: Database Indexes Interview Questions and Answers (Day-2)</title>
		<link>https://www.dbrnd.com/2016/06/sql-server-database-indexes-interview-questions-and-answers-column-store-index-fill-factor-pad-index-sort_in_tempdb-day-2/</link>
		
		<dc:creator><![CDATA[Anvesh Patel]]></dc:creator>
		<pubDate>Thu, 09 Jun 2016 17:47:29 +0000</pubDate>
				<category><![CDATA[SQL Server Interview]]></category>
		<category><![CDATA[answers]]></category>
		<category><![CDATA[Anvesh Patel]]></category>
		<category><![CDATA[column store index]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[database research and development]]></category>
		<category><![CDATA[dbrnd]]></category>
		<category><![CDATA[Fill Factor]]></category>
		<category><![CDATA[indexes]]></category>
		<category><![CDATA[interview]]></category>
		<category><![CDATA[questions]]></category>
		<category><![CDATA[SORT_IN_TEMPDB]]></category>
		<category><![CDATA[SQL Query]]></category>
		<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[SQL Server 2012]]></category>
		<category><![CDATA[SQL Server Administrator]]></category>
		<category><![CDATA[SQL Server Monitoring]]></category>
		<category><![CDATA[SQL Server Performance Tunning]]></category>
		<category><![CDATA[SQL Server Tips and Tricks]]></category>
		<category><![CDATA[TSQL]]></category>
		<category><![CDATA[Unique Index]]></category>
		<guid isPermaLink="false">https://www.dbrnd.com/?p=2947</guid>

					<description><![CDATA[What is a Columnstore index of SQL Server 2012? A columnstore index is a technology for storing, retrieving and managing data by using a columnar data format, called a columnstore. A columnstore is data that is logically organized as a table with rows and columns, and physically stored in a column-wise data format. Columnstore indexes [&#8230;]]]></description>
										<content:encoded><![CDATA[<p><a class="a2a_button_facebook" href="https://www.addtoany.com/add_to/facebook?linkurl=https%3A%2F%2Fwww.dbrnd.com%2F2016%2F06%2Fsql-server-database-indexes-interview-questions-and-answers-column-store-index-fill-factor-pad-index-sort_in_tempdb-day-2%2F&amp;linkname=SQL%20Server%3A%20Database%20Indexes%20Interview%20Questions%20and%20Answers%20%28Day-2%29" title="Facebook" rel="nofollow noopener" target="_blank"></a><a class="a2a_button_twitter" href="https://www.addtoany.com/add_to/twitter?linkurl=https%3A%2F%2Fwww.dbrnd.com%2F2016%2F06%2Fsql-server-database-indexes-interview-questions-and-answers-column-store-index-fill-factor-pad-index-sort_in_tempdb-day-2%2F&amp;linkname=SQL%20Server%3A%20Database%20Indexes%20Interview%20Questions%20and%20Answers%20%28Day-2%29" title="Twitter" rel="nofollow noopener" target="_blank"></a><a class="a2a_button_linkedin" href="https://www.addtoany.com/add_to/linkedin?linkurl=https%3A%2F%2Fwww.dbrnd.com%2F2016%2F06%2Fsql-server-database-indexes-interview-questions-and-answers-column-store-index-fill-factor-pad-index-sort_in_tempdb-day-2%2F&amp;linkname=SQL%20Server%3A%20Database%20Indexes%20Interview%20Questions%20and%20Answers%20%28Day-2%29" title="LinkedIn" rel="nofollow noopener" target="_blank"></a><a class="a2a_button_pinterest" href="https://www.addtoany.com/add_to/pinterest?linkurl=https%3A%2F%2Fwww.dbrnd.com%2F2016%2F06%2Fsql-server-database-indexes-interview-questions-and-answers-column-store-index-fill-factor-pad-index-sort_in_tempdb-day-2%2F&amp;linkname=SQL%20Server%3A%20Database%20Indexes%20Interview%20Questions%20and%20Answers%20%28Day-2%29" title="Pinterest" rel="nofollow noopener" target="_blank"></a><a class="a2a_button_reddit" href="https://www.addtoany.com/add_to/reddit?linkurl=https%3A%2F%2Fwww.dbrnd.com%2F2016%2F06%2Fsql-server-database-indexes-interview-questions-and-answers-column-store-index-fill-factor-pad-index-sort_in_tempdb-day-2%2F&amp;linkname=SQL%20Server%3A%20Database%20Indexes%20Interview%20Questions%20and%20Answers%20%28Day-2%29" title="Reddit" rel="nofollow noopener" target="_blank"></a><a class="a2a_button_pocket" href="https://www.addtoany.com/add_to/pocket?linkurl=https%3A%2F%2Fwww.dbrnd.com%2F2016%2F06%2Fsql-server-database-indexes-interview-questions-and-answers-column-store-index-fill-factor-pad-index-sort_in_tempdb-day-2%2F&amp;linkname=SQL%20Server%3A%20Database%20Indexes%20Interview%20Questions%20and%20Answers%20%28Day-2%29" title="Pocket" rel="nofollow noopener" target="_blank"></a><a class="a2a_dd addtoany_share_save addtoany_share" href="https://www.addtoany.com/share#url=https%3A%2F%2Fwww.dbrnd.com%2F2016%2F06%2Fsql-server-database-indexes-interview-questions-and-answers-column-store-index-fill-factor-pad-index-sort_in_tempdb-day-2%2F&#038;title=SQL%20Server%3A%20Database%20Indexes%20Interview%20Questions%20and%20Answers%20%28Day-2%29" data-a2a-url="https://www.dbrnd.com/2016/06/sql-server-database-indexes-interview-questions-and-answers-column-store-index-fill-factor-pad-index-sort_in_tempdb-day-2/" data-a2a-title="SQL Server: Database Indexes Interview Questions and Answers (Day-2)"></a></p><p><strong>What is a Columnstore index of SQL Server 2012?</strong></p>
<blockquote><p>A columnstore index is a technology for storing, retrieving and managing data by using a columnar data format, called a columnstore.</p>
<p>A columnstore is data that is logically organized as a table with rows and columns, and physically stored in a column-wise data format.</p>
<p>Columnstore indexes work well for data warehousing workloads that primarily perform bulk loads and read-only queries. Use the columnstore index to achieve up to 10x query performance gains over traditional row-oriented storage, and up to 7x data compression over the uncompressed data size.</p></blockquote>
<p><strong>What are the advantages of Columnstore index?</strong></p>
<blockquote><p>Columns store values from the same domain and commonly have similar values, which results in high compression rates. This minimizes or eliminates IO bottleneck in your system while reducing the memory footprint significantly.</p>
<p>High compression rates improve query performance by using a smaller in-memory footprint. In turn, query performance can improve because SQL Server can perform more query and data operations in-memory.</p>
<p>Batch execution improves query performance, typically 2-4x, by processing multiple rows together.</p>
<p>Queries often select only a few columns from a table, which reduces total I/O from the physical media.</p></blockquote>
<p><strong>When I should use clustered column stored index?</strong></p>
<blockquote><p>Use a clustered columnstore index to store fact tables and large dimension tables for data warehousing workloads. This improves query performance and data compression by up to 10x.</p></blockquote>
<p><strong>When I should use non-clustered column stored index?</strong></p>
<blockquote><p>Use a nonclustered columnstore index to perform analysis in real-time on an OLTP workload.</p></blockquote>
<p><strong>How do I choose between a rowstore index and a columnstore index?</strong></p>
<blockquote><p>Rowstore indexes perform best on queries that seek into the data, searching for a particular value, or for queries on a small range of values. Use rowstore indexes with transactional workloads since they tend to require mostly table seeks instead of table scans.</p>
<p>Columnstore indexes give high performance gains for analytic queries that scan large amounts of data, especially on large tables. Use columnstore indexes on data warehousing and analytics workloads, especially on fact tables, since they tend to require full table scans rather than table seeks.</p></blockquote>
<p><strong>What do you know about the Column store Data compression?</strong></p>
<blockquote><p>Columnstore indexes read compressed data from disk, which means fewer bytes of data need to be read into memory.</p>
<p>Columnstore indexes store data in compressed form in memory which reduces IO by reducing the number of times the same data is read into memory.</p>
<p>Columnstore indexes compress data by columns instead of by rows which achieves high compression rates and reduces the size of the data stored on disk. Each column is compressed and stored independently.</p></blockquote>
<p><strong>What is fill factor and pad index?</strong></p>
<blockquote><p>A fill factor is a specification done during the creation of indexes so that a particular amount of space can be left on a leaf level page to decrease the occurrence of page splits when the data has to be accommodated in the future.</p>
<p>A pad index specifies index padding. When it is set to ON, then the free space percentage per the fill factor specification is applied to the intermediate-level pages of the index. When it is set to OFF, the fill factor is not specified and enough space is left for a maximum size row.</p></blockquote>
<p><strong>What is it unwise to create wide clustered index keys?</strong></p>
<blockquote><p>A clustered index is a good choice for searching over a range of values. After an indexed row is found, the remaining rows being adjacent to it can be found easily. However, using wide keys with clustered indexes is not wise because these keys are also used by the non-clustered indexes for look ups and are also stored in every non-clustered index leaf entry.</p></blockquote>
<p><strong>Explain the &#8216;Fill factor&#8217; concept in Indexes.</strong></p>
<ul>
<li>The fill factor option is provided for smoothening index data storage and performance.</li>
<li>The percentage of space on each leaf level page to be filled with data is determined by the fill factor value when an index is created.</li>
<li>This reserves a percentage of free space for future growth.</li>
<li>This option is provided for fine tuning index data storage and performance.</li>
<li>The fill factor value is a percentage from 1 to 100 and the server-wide default is 0 which means that the leaf-level pages are filled to capacity.</li>
</ul>
<p><strong>How do you maintain a fill factor in existing indexes?</strong></p>
<ul>
<li>Usually the data keeps getting added, deleted, or updated in the table due to which the fill factor is implemented during the index creation itself. Fill factor is not maintained after an index is created.</li>
<li>The changes in the future can be determined only when a new index is created on a table that has an existing data. It is beneficial to set the fill factor then itself.</li>
<li>Maintaining extra space on the data pages obviates the purpose of using the fill factor. The SQL Server would then have to split pages to maintain an amount of free space per the fill factor, on each page.</li>
<li>Thus, when data is added filling up the empty space, an index can be created and the fill factor can be re-specified distribute the data again.</li>
</ul>
<p><strong>Difference between Unique Index vs Unique Constraint.</strong></p>
<blockquote><p>Unique Index and Unique Constraint are the same and achieve same goal. SQL performance is same for both.</p></blockquote>
<p><strong>What are the primary differences between an index reorganization and an index rebuild?</strong></p>
<ul>
<li>Reorganization is an “online” operation by default; a rebuild is an “offline” operation by default</li>
<li>Reorganization only affects the leaf level of an index.</li>
<li>Reorganization swaps data pages in-place by using only the pages already allocated to the index; a rebuild uses new pages/allocations</li>
<li>Reorganization is always a fully-logged operation; a rebuild can be a minimally-logged operation.</li>
<li>Reorganization can be stopped mid-process and all completed work is retained; a rebuild is transactional and must be completed in entirety to keep changes.</li>
</ul>
<p><strong>If you need to REBUILD a non-clustered index that is 10GB in size and have 5GB of free data-file space available with no room to grow the data file(s), how can you accomplish the task?</strong></p>
<blockquote><p>When rebuilding an existing non-clustered index, you typically require free space that is approximately equivalent to 2.2 times the size of the existing index, since during a rebuild operation, the existing index is kept until the rebuilt structure is complete and an additional approximately 20% free space for temporary sorting structures used during the rebuild operation.</p>
<p>In this case, you would require at least an additional 10+ GB of free space for the rebuild operation to succeed, since the index itself is 10GB in size.</p>
<p>Using SORT_IN_TEMPDB would not suffice in this case, since only the temporary sort tables are stored in tempdb in this case, and at least 10 GB of free space would still be required in the database data files.</p></blockquote>
<p><strong>Why most of the DBAs recommended Index Reorganizing instead of Index Rebuilding?</strong></p>
<blockquote><p>Reorganizing an index uses minimal system resources. It defragments the leaf level of clustered and nonclustered indexes on tables and views by physically reordering the leaf-level pages to match the logical, left to right, order of the leaf nodes. Reorganizing also compacts the index pages.</p>
<p>Compaction is based on the existing fill factor value.</p>
<p>Reorganize a index after one or more data loads to achieve query performance benefits as quickly as possible. Reorganizing will initially require additional CPU resources to compress the data, which could slow overall system performance. However, as soon as the data is compressed, query performance can improve.</p></blockquote>
<p><strong>What is SORT_IN_TEMPDB option for Indexes?</strong></p>
<blockquote><p>When you create or rebuild an index, by setting the SORT_IN_TEMPDB option to ON you can direct the SQL Server Database Engine to use tempdb to store the intermediate sort results that are used to build the index.</p>
<p>When SORT_IN_TEMPDB is set to OFF, the default, the sort runs are stored in the destination filegroup.</p></blockquote>
<p><strong>Do you think, INDEX REORGANIZE operation requires additional free disk space?</strong></p>
<blockquote><p>No, INDEX REORGANIZE does not require additional free disk space, but related transaction log is required free space to log the operation information.</p></blockquote>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>PostgreSQL: Composite UNIQUE Constraint does not consider NULL Values</title>
		<link>https://www.dbrnd.com/2016/01/postgresql-composite-unique-constraint-does-not-consider-null-values/</link>
					<comments>https://www.dbrnd.com/2016/01/postgresql-composite-unique-constraint-does-not-consider-null-values/#comments</comments>
		
		<dc:creator><![CDATA[Anvesh Patel]]></dc:creator>
		<pubDate>Mon, 18 Jan 2016 18:52:56 +0000</pubDate>
				<category><![CDATA[PostgreSQL]]></category>
		<category><![CDATA[Anvesh Patel]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[database research and development]]></category>
		<category><![CDATA[dbrnd]]></category>
		<category><![CDATA[Partial Index]]></category>
		<category><![CDATA[plpgsql]]></category>
		<category><![CDATA[Postgres Query]]></category>
		<category><![CDATA[postgresql]]></category>
		<category><![CDATA[PostgreSQL Administrator]]></category>
		<category><![CDATA[PostgreSQL Error]]></category>
		<category><![CDATA[PostgreSQL Programming]]></category>
		<category><![CDATA[PostgreSQL Tips and Tricks]]></category>
		<category><![CDATA[UNIQUE]]></category>
		<category><![CDATA[Unique Index]]></category>
		<guid isPermaLink="false">https://www.dbrnd.com/?p=1323</guid>

					<description><![CDATA[PostgreSQL UNIQUE Constraint does not consider a NULL values for uniqueness. I am surprised when I found few duplicate values in my database where Unique key constraint already defined for that columns. I know the thumb rule of UNIQUE Constraint is, UNIQUE Key column can be a NULL. In my Postgres database, I applied Composite [&#8230;]]]></description>
										<content:encoded><![CDATA[<p><a class="a2a_button_facebook" href="https://www.addtoany.com/add_to/facebook?linkurl=https%3A%2F%2Fwww.dbrnd.com%2F2016%2F01%2Fpostgresql-composite-unique-constraint-does-not-consider-null-values%2F&amp;linkname=PostgreSQL%3A%20Composite%20UNIQUE%20Constraint%20does%20not%20consider%20NULL%20Values" title="Facebook" rel="nofollow noopener" target="_blank"></a><a class="a2a_button_twitter" href="https://www.addtoany.com/add_to/twitter?linkurl=https%3A%2F%2Fwww.dbrnd.com%2F2016%2F01%2Fpostgresql-composite-unique-constraint-does-not-consider-null-values%2F&amp;linkname=PostgreSQL%3A%20Composite%20UNIQUE%20Constraint%20does%20not%20consider%20NULL%20Values" title="Twitter" rel="nofollow noopener" target="_blank"></a><a class="a2a_button_linkedin" href="https://www.addtoany.com/add_to/linkedin?linkurl=https%3A%2F%2Fwww.dbrnd.com%2F2016%2F01%2Fpostgresql-composite-unique-constraint-does-not-consider-null-values%2F&amp;linkname=PostgreSQL%3A%20Composite%20UNIQUE%20Constraint%20does%20not%20consider%20NULL%20Values" title="LinkedIn" rel="nofollow noopener" target="_blank"></a><a class="a2a_button_pinterest" href="https://www.addtoany.com/add_to/pinterest?linkurl=https%3A%2F%2Fwww.dbrnd.com%2F2016%2F01%2Fpostgresql-composite-unique-constraint-does-not-consider-null-values%2F&amp;linkname=PostgreSQL%3A%20Composite%20UNIQUE%20Constraint%20does%20not%20consider%20NULL%20Values" title="Pinterest" rel="nofollow noopener" target="_blank"></a><a class="a2a_button_reddit" href="https://www.addtoany.com/add_to/reddit?linkurl=https%3A%2F%2Fwww.dbrnd.com%2F2016%2F01%2Fpostgresql-composite-unique-constraint-does-not-consider-null-values%2F&amp;linkname=PostgreSQL%3A%20Composite%20UNIQUE%20Constraint%20does%20not%20consider%20NULL%20Values" title="Reddit" rel="nofollow noopener" target="_blank"></a><a class="a2a_button_pocket" href="https://www.addtoany.com/add_to/pocket?linkurl=https%3A%2F%2Fwww.dbrnd.com%2F2016%2F01%2Fpostgresql-composite-unique-constraint-does-not-consider-null-values%2F&amp;linkname=PostgreSQL%3A%20Composite%20UNIQUE%20Constraint%20does%20not%20consider%20NULL%20Values" title="Pocket" rel="nofollow noopener" target="_blank"></a><a class="a2a_dd addtoany_share_save addtoany_share" href="https://www.addtoany.com/share#url=https%3A%2F%2Fwww.dbrnd.com%2F2016%2F01%2Fpostgresql-composite-unique-constraint-does-not-consider-null-values%2F&#038;title=PostgreSQL%3A%20Composite%20UNIQUE%20Constraint%20does%20not%20consider%20NULL%20Values" data-a2a-url="https://www.dbrnd.com/2016/01/postgresql-composite-unique-constraint-does-not-consider-null-values/" data-a2a-title="PostgreSQL: Composite UNIQUE Constraint does not consider NULL Values"></a></p><p>PostgreSQL UNIQUE Constraint does not consider a NULL values for uniqueness.<br />
I am surprised when I found few duplicate values in my database where Unique key constraint already defined for that columns.</p>
<blockquote><p>I know the thumb rule of UNIQUE Constraint is, UNIQUE Key column can be a NULL.</p></blockquote>
<p>In my Postgres database, I applied Composite Unique Key in multiple columns, and this constraint failed when one of the value is NULL, and another value is NOT NULL.</p>
<p>Below is a full example on this:</p>
<p><strong>Create a sample table with composite Unique Key:</strong></p><pre class="crayon-plain-tag">CREATE TABLE tbl_TestUniqueNull
(
    ID INTEGER 
    ,NoA INTEGER 
    ,NoB INTEGER 
    ,NoC INTEGER 
    ,CONSTRAINT pk_tbl_TestUniqueNull_ID PRIMARY KEY(ID)
    ,CONSTRAINT uk_tbl_TestUniqueNull_NoA_NoB_NoC unique (NoA,NoB,NoC)
);</pre><p>
<p><strong>Now insert few records with the same combination:</strong></p><pre class="crayon-plain-tag">INSERT INTO tbl_TestUniqueNull VALUES (1,1,2,NULL);
INSERT INTO tbl_TestUniqueNull VALUES (2,1,2,NULL);
INSERT INTO tbl_TestUniqueNull VALUES (3,1,5,NULL);
INSERT INTO tbl_TestUniqueNull VALUES (4,3,NULL,1);
INSERT INTO tbl_TestUniqueNull VALUES (5,3,NULL,1);</pre><p>
<img decoding="async" class="alignnone wp-image-1327 size-full" title="Postgres Unique Key Null" src="https://www.dbrnd.com/wp-content/uploads/2016/01/PostgresUniqueKeyNull.png" alt="Postgres Unique Key Null" width="198" height="131" srcset="https://www.dbrnd.com/wp-content/uploads/2016/01/PostgresUniqueKeyNull.png 198w, https://www.dbrnd.com/wp-content/uploads/2016/01/PostgresUniqueKeyNull-150x99.png 150w" sizes="(max-width: 198px) 100vw, 198px" /></p>
<p>You can check above result, and we can easily find duplicate combination when one column has a NULL value. Which is wrong and if we have this kind of requirement when we need a composite Unique Key, it fails. </p>
<p><strong>The solution is Unique Index:</strong><br />
In the above situation, we have to use the Unique Index of PostgreSQL.</p>
<p><strong>Create a Unique Index for this example:</strong></p>
<pre class="crayon-plain-tag">CREATE UNIQUE INDEX UIdx_NoA_NoB_NoC 
	ON tbl_TestUniqueNull 
(coalesce(NoA,-1),coalesce(NoB,-1),coalesce(NoC,-1));</pre>
When you try to insert duplicate combination after applying this index, you will get a below error message. </p>
<pre class="crayon-plain-tag">ERROR:  duplicate key value violates unique constraint "uidx_noa_nob_noc"
DETAIL:  Key ((COALESCE(noa, (-1))), (COALESCE(nob, (-1))), (COALESCE(noc, (-1))))=(3, -1, 1) already exists.
********** Error **********

ERROR: duplicate key value violates unique constraint "uidx_noa_nob_noc"
SQL state: 23505
Detail: Key ((COALESCE(noa, (-1))), (COALESCE(nob, (-1))), (COALESCE(noc, (-1))))=(3, -1, 1) already exists.</pre> </p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.dbrnd.com/2016/01/postgresql-composite-unique-constraint-does-not-consider-null-values/feed/</wfw:commentRss>
			<slash:comments>10</slash:comments>
		
		
			</item>
	</channel>
</rss>
