Clustered indexes and deadlocks

Hi,
I have run into some problem with clustered indexes and deadlocks. I have found some breadcrumbs about this on the web but didn't really understand everything. I am an DBA by accident and mainly BI and DWH developer. The article most relevant to the problem
seems to be the following:
SQL Server Deadlocks Caused By Clustered Index Scan .
The database is running with READ COMMITTED SNAPSHOT Transaction Isolation Level. Problematic seems to be the second query. First a row is inserted into table SubjectRevisionEntity.  Second a row is inserted into table Partner which has a foreign key
on SubjectRevisionEntity. This foreign key is validated using a Clustered Index Seek.
Having done some research on the topic using the internet my hypothesis is as follows:
- Insert from Query 1 in Session 1 locks page in Table SubjectRevisionEntity
- Now a new session (Session 2) is started. Insert from Query 1 in Session 2 probably locks the same page in Table SubjectRevisionEntity.
- Insert from Query 2 in Session 1 locks page in Table Partner
   Lock on page in Table SubjectRevisionEntity is necessary to do the Clustered Index Seek. However this page is already locked by Session 2. However, Session 2 needs to lock page in Table Partner which is already locked by Session 1 --> deadlock
occurs
Does this make any sense? At the moment I am not having the means to test the hypothesis but I will look after that.
I am just thinking about countermeasures to undertake. What about configuring the index to avoid page locks? All other queries seem to be fine I suppose as they operate on only one table. My fellows from software engineering favour to replace clustered indexes
by nonclustered indexes as the already have done in the past. However, I think the disadvantages of nonclustered indexes aka heaps regarding storage (forwarded records) and query performance are much bigger than their use for problems like these.
Regarding the
article I did not understand the author's point, that two simultaneous table scans on one table by two sessions won't work. I thought that this is no problem as the sessions would use a shared lock on the table.
Thank you very much for sharing your expertise in advance!
Martin

As you describe this that cannot be the cause of your deadlock.
After session 1 executes query 1, it will have an IX (Intent Exclusive) lock on the clustered index of table SubjectRevisionEntity (note that a lock on a clustered index is a lock on the table since the table is contained in the clustered index), also an
IX lock on the page in the index where the new row will be inserted and an X (exclusive) lock on the key that you just inserted.
When session 2 executes it also needs an IX lock on the clustered index of table SubjectRevisionEntity, this is allowed because multiple sessions can have IX locks on the same resource at the same time, also an IX lock on the page in the index where the
new row will be inserted (also allowed even if this entry is in the same page as the row inserted by session 1), and an X lock on the key that session 2 inserted.  This is also allowed UNLESS session 2 and session 1 are trying to insert a row with the
SAME primary key value.  From your description, I gather that session 1 and session 2 are trying to insert different keys.
Then session 1 attempts to insert a row in Partner which has a foreign key reference to the row in SubjectRevisionEntity.  That means it must check for the existence of the row that session 1 inserted.  But it can do this because all it needs is
a S (shared) lock on the SubjectRevisionEntity table, and an S lock on the page.  It that get those even though session 2 has an IX lock on those resources because S locks and IX locks are compatible.  It also needs an S lock on the row in SubjectRevisionEntity. 
That is no problem unless it is trying to reference the row which session 2 just entered.  (Once again, I assume this is not the case in your situation?)  It then inserts the row in Partner getting an IX lock on the Partner table, an IX lock on the
page and an X lock on the new key in Partner.
Then session 2 attempts to insert a row in Partner.  That will work unless either it is inserting a row in Partner with the same primary key as the row inserted by session 1 or it is trying to reference the same row in SubjectRevisionEntity that session
1 inserted.
So this cannot be the cause of your deadlock unless both sessions are entering the same key values.  The fact that they may both be entering keys on the same page should not be causing you deadlock problems.
Regarding your question about why 2 table scans of the entire table (or entire clustered index scan if the table has a clustered index), you are correct, the scans do get shared locks and there is no deadlock problem UNLESS both sessions are holding locks
that are incompatible with S locks.  For example, if you were in read committed mode and session 1 had inserted a row with clustered index key = 47 and session 2 had inserted a row with clustered index key = 23 and and both sessions attempt to do a complete
clustered index scan (by, for example, by doing something like SELECT <blah blah> FROM <table> WHERE <some nonindexed column> = 0, then both sessions will try to get S locks on every row so session 1 will be stopped at key = 23 and session
2 will be stopped at key = 47 and that is a deadlock.  BUT
You are using READ COMMITTED SNAPSHOT, not READ COMMITTED.  In READ COMMITTED SNAPSHOT, writes do not block reads.  So the situation above does not apply to you since neither of the sessions would be blocked because it was attempting to read a
row which was locked by an update from another session.
Tom

Similar Messages

  • What is RID in non clustered index and its use

    Hi All,
    I need help regarding following articles on sql server
    1) what is RID in non clustered index and its use.
    2) What is Physical and virtual address space. Difference in 32 bit vs 64 bit Virtual address space
    Regards
    Rahul

    Next time Please ask single question in a thread you will get better response.
    1. RID is location of heap. When you create Non clustered index on heap and
    lookup happens to get extra records RID is used to locate the records. RID is basically Row ID. This is basic definition for you. Please read
    this Thread for more details
    2. I have not heard of Physical address space. I Know Virtual address space( VAS)
    VAS is simple terms is amount of memory( virtual )  'visible' to a process, a process can be SQL Server process or windows process. It theoretically depends on architecture of Operating System. 32 bit OS will have maximum range of 4 G VAS, it's calculated
    like a process ruining on 32 bit system can address max up to 2^32 locations ( which is equivalent to 4 G). Similarly for 64 bit max VAS will be 2^64 which is theoretically infinite. To make things feasible maximum VAS for 64 bit system is kept to 8 TB. Now
    VAS acts as layer of abstraction an intermediate .Instead of all request directly mapping to physical memory it first maps to VAS and then mapped to physical memory so that it can manage request for memory in more coordinated fashion than allowing process
    to do it ,if not it will  soon cause memory crunch.Any process when created on windows will see virtual memory according to its VAS limit.
    Please read
    This Article for detailed information
    Please mark this reply as answer if it solved your issue or vote as helpful if it helped so that other forum members can benefit from it
    My Technet Wiki Article
    MVP

  • Indexing and Deadlock in SQL Server 2008?

    All,
    I am running into a deadlock in SQL Server 2008. Using a profiler I was able to determine that the deadlock happens as I am trying to select and update row(S) in table in 2 different sessions.
    The select query from the profiler is shown below
    select
    nodeinstan0_.id as id35_,
    nodeinstan0_.BPMN_ELEMENT_ID as BPMN2_35_,
    nodeinstan0_.END_DATE as END3_35_,
    nodeinstan0_.NODE_ID as NODE4_35_,
    nodeinstan0_.NODE_INSTANCE_ID as NODE5_35_,
    nodeinstan0_.NODE_NAME as NODE6_35_,
    nodeinstan0_.PROCESS_INSTANCE_ID as PROCESS7_35_,
    nodeinstan0_.START_DATE as START8_35_
    from
    NODE_INSTANCE_LOG nodeinstan0_ where
    nodeinstan0_.NODE_INSTANCE_ID= @P0 and
    nodeinstan0_.PROCESS_INSTANCE_ID= @P1 and
    (nodeinstan0_.END_DATE is null)
    My SQL Scripts for creating the table and index is show below
    CREATE TABLE [dbo].[NODE_INSTANCE_LOG](
    [id] [numeric](19, 0) IDENTITY(1,1) NOT NULL,
    [BPMN_ELEMENT_ID] [varchar](255) NULL,
    [END_DATE] [datetime] NULL,
    [NODE_ID] [varchar](255) NOT NULL,
    [NODE_INSTANCE_ID] [varchar](255) NOT NULL,
    [NODE_NAME] [varchar](2000) NULL,
    [PROCESS_INSTANCE_ID] [numeric](19, 0) NOT NULL,
    [START_DATE] [datetime] NULL,
    PRIMARY KEY CLUSTERED
    [id] ASC
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
    IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,
    ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
    ) ON [PRIMARY]
    GO
    CREATE NONCLUSTERED INDEX IX_NODE_INSTANCE_LOG_Index1
    ON NODE_INSTANCE_LOG(NODE_INSTANCE_ID, PROCESS_INSTANCE_ID, END_DATE)
    INCLUDE
    ( ID, BPMN_ELEMENT_ID, NODE_ID, NODE_NAME, START_DATE);
    As I understood from number of other forums and blogs - I have included the columns under the where clause in the "COVERING index" and the rest of the columns from the select query under non clustered Index. But I am still facing a deadlock.
    Would appreciate if some once can point me in the right direction.
    regards D

    Correction to my earlier observation. Its not a select/update that's causing the deadlock but its a select/select
    I am pasting an extract from the Tracer
    <deadlock victim="process6a9048">
    <process-list>
    <process id="process6a9048" taskpriority="0" logused="15888" waitresource="KEY: 6:72057594142588928 (fbd2e857cffa)" waittime="812" ownerId="1927048" transactionname="implicit_transaction" lasttranstarted="2014-01-03T17:01:35.453" XDES="0x91cd7960" lockMode="S" schedulerid="2" kpid="3640" status="suspended" spid="56" sbid="0" ecid="0" priority="0" trancount="1" lastbatchstarted="2014-01-03T17:01:35.723" lastbatchcompleted="2014-01-03T17:01:35.723" clientapp="jTDS" hostname="LDN-LRM-PC-189" hostpid="123" loginname="username" isolationlevel="read committed (2)" xactid="1927048" currentdb="6" lockTimeout="4294967295" clientoption1="671088672" clientoption2="128058">
    <executionStack>
    <frame procname="adhoc" line="1" stmtstart="62" sqlhandle="0x02000000e82b4000ebf38fb66978d5f9f2314a6046f957b3">
    select nodeinstan0_.id as id35_, nodeinstan0_.BPMN_ELEMENT_ID as BPMN2_35_, nodeinstan0_.END_DATE as END3_35_, nodeinstan0_.NODE_ID as NODE4_35_, nodeinstan0_.NODE_INSTANCE_ID as NODE5_35_, nodeinstan0_.NODE_NAME as NODE6_35_, nodeinstan0_.PROCESS_INSTANCE_ID as PROCESS7_35_, nodeinstan0_.START_DATE as START8_35_ from NODE_INSTANCE_LOG nodeinstan0_ where nodeinstan0_.NODE_INSTANCE_ID= @P0 and nodeinstan0_.PROCESS_INSTANCE_ID= @P1 and (nodeinstan0_.END_DATE is null) </frame>
    </executionStack>
    <inputbuf>
    (@P0 nvarchar(4000),@P1 bigint)select nodeinstan0_.id as id35_, nodeinstan0_.BPMN_ELEMENT_ID as BPMN2_35_, nodeinstan0_.END_DATE as END3_35_, nodeinstan0_.NODE_ID as NODE4_35_, nodeinstan0_.NODE_INSTANCE_ID as NODE5_35_, nodeinstan0_.NODE_NAME as NODE6_35_, nodeinstan0_.PROCESS_INSTANCE_ID as PROCESS7_35_, nodeinstan0_.START_DATE as START8_35_ from NODE_INSTANCE_LOG nodeinstan0_ where nodeinstan0_.NODE_INSTANCE_ID= @P0 and nodeinstan0_.PROCESS_INSTANCE_ID= @P1 and (nodeinstan0_.END_DATE is null) </inputbuf>
    </process>
    <process id="process6dddc8" taskpriority="0" logused="114316" waitresource="KEY: 6:72057594142588928 (44ec7e8e62c7)" waittime="602" ownerId="1927022" transactionname="implicit_transaction" lasttranstarted="2014-01-03T17:01:35.227" XDES="0x91d25950" lockMode="S" schedulerid="4" kpid="17412" status="suspended" spid="60" sbid="0" ecid="0" priority="0" trancount="1" lastbatchstarted="2014-01-03T17:01:35.937" lastbatchcompleted="2014-01-03T17:01:35.937" clientapp="jTDS" hostname="LDN-LRM-PC-189" hostpid="123" loginname="username" isolationlevel="read committed (2)" xactid="1927022" currentdb="6" lockTimeout="4294967295" clientoption1="671088672" clientoption2="128058">
    <executionStack>
    <frame procname="adhoc" line="1" stmtstart="62" sqlhandle="0x02000000e82b4000ebf38fb66978d5f9f2314a6046f957b3">
    select nodeinstan0_.id as id35_, nodeinstan0_.BPMN_ELEMENT_ID as BPMN2_35_, nodeinstan0_.END_DATE as END3_35_, nodeinstan0_.NODE_ID as NODE4_35_, nodeinstan0_.NODE_INSTANCE_ID as NODE5_35_, nodeinstan0_.NODE_NAME as NODE6_35_, nodeinstan0_.PROCESS_INSTANCE_ID as PROCESS7_35_, nodeinstan0_.START_DATE as START8_35_ from NODE_INSTANCE_LOG nodeinstan0_ where nodeinstan0_.NODE_INSTANCE_ID= @P0 and nodeinstan0_.PROCESS_INSTANCE_ID= @P1 and (nodeinstan0_.END_DATE is null) </frame>
    </executionStack>
    <inputbuf>
    (@P0 nvarchar(4000),@P1 bigint)select nodeinstan0_.id as id35_, nodeinstan0_.BPMN_ELEMENT_ID as BPMN2_35_, nodeinstan0_.END_DATE as END3_35_, nodeinstan0_.NODE_ID as NODE4_35_, nodeinstan0_.NODE_INSTANCE_ID as NODE5_35_, nodeinstan0_.NODE_NAME as NODE6_35_, nodeinstan0_.PROCESS_INSTANCE_ID as PROCESS7_35_, nodeinstan0_.START_DATE as START8_35_ from NODE_INSTANCE_LOG nodeinstan0_ where nodeinstan0_.NODE_INSTANCE_ID= @P0 and nodeinstan0_.PROCESS_INSTANCE_ID= @P1 and (nodeinstan0_.END_DATE is null) </inputbuf>
    </process>
    </process-list>
    <resource-list>
    <keylock hobtid="72057594142588928" dbid="6" objectname="reform.dbo.NODE_INSTANCE_LOG" indexname="IX_NODE_INSTANCE_LOG_Index1" id="lock89f43000" mode="X" associatedObjectId="72057594142588928">
    <owner-list>
    <owner id="process6dddc8" mode="X"/>
    </owner-list>
    <waiter-list>
    <waiter id="process6a9048" mode="S" requestType="wait"/>
    </waiter-list>
    </keylock>
    <keylock hobtid="72057594142588928" dbid="6" objectname="reform.dbo.NODE_INSTANCE_LOG" indexname="IX_NODE_INSTANCE_LOG_Index1" id="lock81b22a80" mode="X" associatedObjectId="72057594142588928">
    <owner-list>
    <owner id="process6a9048" mode="X"/>
    </owner-list>
    <waiter-list>
    <waiter id="process6dddc8" mode="S" requestType="wait"/>
    </waiter-list>
    </keylock>
    </resource-list>
    </deadlock>
    Would appreciate if some one can point out where the issue is.

  • Deadlock when updating different rows on a single table with one clustered index

    Deadlock when updating different rows on a single table with one clustered index. Can anyone explain why?
    <event name="xml_deadlock_report" package="sqlserver" timestamp="2014-07-30T06:12:17.839Z">
      <data name="xml_report">
        <value>
          <deadlock>
            <victim-list>
              <victimProcess id="process1209f498" />
            </victim-list>
            <process-list>
              <process id="process1209f498" taskpriority="0" logused="1260" waitresource="KEY: 8:72057654588604416 (8ceb12026762)" waittime="1396" ownerId="1145783115" transactionname="implicit_transaction"
    lasttranstarted="2014-07-30T02:12:16.430" XDES="0x3a2daa538" lockMode="X" schedulerid="46" kpid="7868" status="suspended" spid="262" sbid="0" ecid="0" priority="0"
    trancount="2" lastbatchstarted="2014-07-30T02:12:16.440" lastbatchcompleted="2014-07-30T02:12:16.437" lastattention="1900-01-01T00:00:00.437" clientapp="Internet Information Services" hostname="CHTWEB-CH2-11P"
    hostpid="12776" loginname="chatuser" isolationlevel="read uncommitted (1)" xactid="1145783115" currentdb="8" lockTimeout="4294967295" clientoption1="671088672" clientoption2="128058">
               <inputbuf>
    UPDATE analyst_monitor SET cam_status = N'4', cam_event_data = N'sales1', cam_event_time = current_timestamp , cam_modified_time = current_timestamp , cam_room = '' WHERE cam_analyst_name=N'ABCD' AND cam_window= 2   </inputbuf>
              </process>
              <process id="process9cba188" taskpriority="0" logused="2084" waitresource="KEY: 8:72057654588604416 (2280b457674a)" waittime="1397" ownerId="1145783104" transactionname="implicit_transaction"
    lasttranstarted="2014-07-30T02:12:16.427" XDES="0x909616d28" lockMode="X" schedulerid="23" kpid="8704" status="suspended" spid="155" sbid="0" ecid="0" priority="0"
    trancount="2" lastbatchstarted="2014-07-30T02:12:16.440" lastbatchcompleted="2014-07-30T02:12:16.437" lastattention="1900-01-01T00:00:00.437" clientapp="Internet Information Services" hostname="CHTWEB-CH2-11P"
    hostpid="12776" loginname="chatuser" isolationlevel="read uncommitted (1)" xactid="1145783104" currentdb="8" lockTimeout="4294967295" clientoption1="671088672" clientoption2="128058">
                <inputbuf>
    UPDATE analyst_monitor SET cam_status = N'4', cam_event_data = N'sales2', cam_event_time = current_timestamp , cam_modified_time = current_timestamp , cam_room = '' WHERE cam_analyst_name=N'12345' AND cam_window= 1   </inputbuf>
              </process>
            </process-list>
            <resource-list>
              <keylock hobtid="72057654588604416" dbid="8" objectname="CHAT.dbo.analyst_monitor" indexname="IX_Clust_scam_an_name_window" id="lock4befe1100" mode="X" associatedObjectId="72057654588604416">
                <owner-list>
                  <owner id="process9cba188" mode="X" />
                </owner-list>
                <waiter-list>
                  <waiter id="process1209f498" mode="X" requestType="wait" />
                </waiter-list>
              </keylock>
              <keylock hobtid="72057654588604416" dbid="8" objectname="CHAT.dbo.analyst_monitor" indexname="IX_Clust_scam_an_name_window" id="lock18ee1ab00" mode="X" associatedObjectId="72057654588604416">
                <owner-list>
                  <owner id="process1209f498" mode="X" />
                </owner-list>
                <waiter-list>
                  <waiter id="process9cba188" mode="X" requestType="wait" />
                </waiter-list>
              </keylock>
            </resource-list>
          </deadlock>
        </value>
      </data>
    </event>

    To be honest, I don't think the transaction is necessary, but the developers put it there anyway. The select statement will put the result cam_status
    into a variable, and then depends on its value, it will decide whether to execute the second update statement or not. I still can't upload the screen-shot, because it says it needs to verify my account at first. No clue at all. But it is very simple, just
    like:
    Clustered Index Update
    [analyst_monitor].[IX_Clust_scam_an_name_window]
    cost: 100%
    By the way, for some reason, I can't find the object based on the associatedObjectId listed in the XML
    <keylock hobtid="72057654588604416" dbid="8" objectname="CHAT.dbo.analyst_monitor"
    indexname="IX_Clust_scam_an_name_window" id="lock4befe1100" mode="X" associatedObjectId="72057654588604416">
    For example: 
    SELECT * FROM sys.partition WHERE hobt_id = 72057654588604416
    This return nothing. Not sure why.

  • Compression on table and on clustered index

    Hi all,
    if I had a table with a clustered index on it, is it the same to rebuild the table with compression and rebuild the clustered index with compression?
    Is this
    ALTER TABLE dbo.TABLE_001 REBUILD PARTITION = ALL WITH (DATA_COMPRESSION = ROW, ONLINE=ON)
    Equivalent to this?
    ALTER INDEX PK_TABLE_001 ON dbo.TABLE_001 REBUILD WITH (DATA_COMPRESSION=ROW, ONLINE=ON)
    where PK_TABLE_001 is the clustered index of the table TABLE_001

    Andrea,
    Cluster index is table itself organized according to clustering key value. So if you apply compression on CI means internally table would be compressed and because cluster index includes all columsn of the table so complete table would be compressed.
    Please mark this reply as answer if it solved your issue or vote as helpful if it helped so that other forum members can benefit from it
    My Technet Wiki Article
    MVP

  • Clustering MSG 7.0 u3 + Indexing and Search Service

    Messaging Server 7 Update 3
    Indexing and Search Service 1
    Indexing and Search service requires IMQ broker configured.
    In clustered msg srv deployments with ISS enabled, what is the correct way to deploy IMQ:
    - as a clustered service with affinity configured between msg and imq
    or
    - imq instance running on each node of the cluster
    Thanks,
    D.

    JMQ should be installed on each cluster node with something like this:
    Grab mq4_1-installer-SunOS.zip (SPARC) or mq4_1-installer-SunOS_X86.zip (x86)
    Slap JMQ installer somewhere like /usr/local/src and unzip it
    mq4_1-installer/installer or mq4_1-installer/installer -nodisplay
    Hammer through the install and you should be ready to go
    Now the actual setup of JMQ:
    vi /etc/imq/imqborkerd.conf
    Change {color:#0000ff}*AUTOSTART=NO*{color} to {color:#0000ff}*AUTOSTART=YES*{color}
    If your host has Sun Java Application Server (SJAS) or GlassFish on it (or will) set {color:#0000ff}*ARGS=port 7777*{color}
    Note: SJAS 9.x and GlassFish come with their own install of JMQ and if you are mixing Messaging Server with SJAS/GlassFish you will want the Messaging Server JMQ to have its own port
    Start JMQ -*{color:#0000ff} /etc/init.d/imq start{color}*
    Reset the admin password:*{color:#0000ff} imqusermgr update -u{color}* {color:#0000ff}*admin*{color} *{color:#0000ff}-p{color}* *{color:#ff0000}<password>{color}*
    Disable the guest account: *{color:#0000ff}imqusermgr update -u guest -a false{color}*
    Setup a user account (jesuser in this example) to use for Messaging Server integration: {color:#0000ff}*imqusermgr add -u*{color} *{color:#ff0000}jesuser{color}{color:#0000ff}{color:#ff0000} {color}-g user -p* {color:#ff0000}*jesuser*
    {color:#000000}cd /opt/sun/coms/messaging/sbin (or messaging64 if rolling 64-bit Messaging Server)
    ./configutil -o local.store.notifyplugin.jmqnotify.NewMsg.enable -v 1
    ./configutil -o local.store.notifyplugin.jmqnotify.UpdateMsg.enable -v 1
    ./configutil -o local.store.notifyplugin.jmqnotify.DeleteMsg.enable -v 1
    ./configutil -o local.store.notifyplugin.jmqnotify.maxHeaderSize -v 1024
    ./configutil -o local.store.notifyplugin.jmqnotify.jmqHost -v *"*127.0.0.1*"*{color}
    {color}{color:#000000} (this could also be the IP address of your cluster node, not the service address but the actual IP address of the node)
    ./configutil -o local.store.notifyplugin.jmqnotify.jmqPort -v "7777"{color:#ff0000} {color}(if you have changed from the default port of 7676 enter it here)
    {color}./configutil -o local.store.notifyplugin.jmqnotify.jmqUser -v
    "jesuser" (substitute the JMQ user that you created earlier)
    {color:#000000}./configutil -o local.store.notifyplugin.jmqnotify.jmqPwd -v "jesuser" (substitute the password for the JMQ user that you specified earlier)
    ./configutil -o local.store.notifyplugin.jmqnotify.DestinationType -v "queue"
    ./configutil -o local.store.notifyplugin.jmqnotify.jmqQueue -v "jesms"
    ./configutil -o local.store.notifyplugin.jmqnotify.Priority -v 3
    ./configutil -o local.store.notifyplugin.jmqnotify.ttl -v 1000
    ./configutil -o local.store.notifyplugin.jmqnotify.Persistent -v 1
    ./configutil -o local.store.notifyplugin.jmqnotify -v '/opt/sun/comms/messaging/lib/libjmqnotify$jmqnotify'{color}
    Repeat on each node that will master HA Messaging Server.
    Edited by: nate_keegan on Feb 17, 2010 1:42 PM - the rich text editor is acting strangely, reverting to text for configutil section

  • Space occupied by clustered index Vs non-clustered index

    I am trying to understand the indexes. Does clustered index occupy more space than a non-clustered index because it carries the information about rest of the other columns also. Could you guys please help me understand this. Thanks in advance.
    svk

    Hi czarvk,
    Clustered index in SQL Server takes up more space than non-clustered indexes.
    Clustered index arranges the way records are stored in a table putting them in order (key, value), all the data are sorted on the values of the index.
    A non-clustered index is a completely different object in a table, containing only a subset of columns and a row locator to the table’s rows or to the clustered index’s key.
    So clustered index in SQL Server takes up more space than non-clustered indexes.
    If you have any question, please feel free to let me know.
    Regards,
    Donghui Li

  • UNIQUE INDEX and PRIMARY KEYS

    Hi Friends,
    I am confused about primary keys.
    What is the purpose of this key again? I know it is used for unique constraints.
    Supposing I have a table with two (2) columns which are each indexed as unique.
    Then they can me both candidate at primary key right?
    So why do I need a primary key again? when I have 2 columns which are uniquely index?
    Thanks a lot

    A UNIQUE index creates a constraint such that all values in the index must be distinct. An error occurs if you try to add a new row with a key value that matches an existing row. This constraint does not apply to NULL values except for the BDB storage engine. For other engines, a UNIQUE index allows multiple NULL values for columns that can contain NULL
    The differences between the two are:
    1. Column(s) that make the Primary Key of a table cannot be NULL since by definition; the Primary Key cannot be NULL since it helps uniquely identify the record in the table. The column(s) that make up the unique index can be nullable. A note worth mentioning over here is that different RDBMS treat this differently –> while SQL Server and DB2 do not allow more than one NULL value in a unique index column, Oracle allows multiple NULL values. That is one of the things to look out for when designing/developing/porting applications across RDBMS.
    2. There can be only one Primary Key defined on the table where as you can have many unique indexes defined on the table (if needed).
    3. Also, in the case of SQL Server, if you go with the default options then a Primary Key is created as a clustered index while the unique index (constraint) is created as a non-clustered index. This is just the default behavior though and can be changed at creation time, if needed.
    So, if the unique index is defined on not null column(s), then it is essentially the same as the Primary Key and can be treated as an alternate key meaning it can also serve the purpose of identifying a record uniquely in the table.

  • Non Clustered Indexing not working for SQL server 2005

    I have create two non clustered index on two particular tables. Now the problem is its working fine..but after restarting my server its working stop and then again I have to delete that index and recreate it.

    try these links 
    http://blog.sqlauthority.com/2009/02/07/sql-server-introduction-to-force-index-query-hints-index-hint/
    http://blog.sqlauthority.com/2009/02/08/sql-server-introduction-to-force-index-query-hints-index-hint-part2/
    http://www.brentozar.com/archive/2013/10/index-hints-helpful-or-harmful/
    Hope it Helps!!

  • How to create clustered index in Oracle ?

    I need to Create unique clustered index idx_col1 on table1(col1) in Oracle 9i.
    Should I declare it at creation of table as index-organized ? My table is created with the code like Create table table1 as select ..... from ....
    Can anybody post an example ?
    Thanks

    Oracle does not have the concept of a clustered index from SQL Server. You may get something similar if you create your table as an index organized table, i.e.
    CREATE TABLE my_iot (
      col1 number primary key,
      col2 number
    organization index;or you may get similar benefits by creating a cluster. It really depends on what functionality you're trying to replicate and what problem your trying to solve. Either way, though, you'll have to have separate steps to create the table and then to insert the data.
    Justin

  • SQL Server 2014 Bug - with Clustered Index On Temp Table with Identity Column

    Hi,
    Here's a stored procedure.  (It could be shorter, but this will show the problem.)
              CREATE PROCEDURE dbo.SGTEST_TBD_20141030 AS
              IF OBJECT_ID('TempDB..#Temp') IS NOT NULL
                 DROP TABLE #Temp
              CREATE TABLE #Temp
               Col1        INT NULL
              ,Col2        INT IDENTITY NOT NULL
              ,Col3        INT NOT NULL
              CREATE CLUSTERED INDEX ix_cl ON #Temp(Col2)
              SET IDENTITY_INSERT #Temp ON;
              RAISERROR('Preparing to INSERT INTO #Temp...',0,1) WITH NOWAIT;
              INSERT INTO #Temp (Col1, Col2, Col3)
              SELECT 1,2,3
              RAISERROR('Insert Success!!!',0,1) WITH NOWAIT;
              SET IDENTITY_INSERT #Temp OFF;
    In SQL Server 2014, If I execute this (EXEC dbo.SGTEST_TBD_20141030)   It works.   If I execute it a second time - It fails hard with: 
            Msg 0, Level 11, State 0, Line 0
            A severe error occurred on the current command.  The results, if any, should be discarded.
            Msg 0, Level 20, State 0, Line 0
            A severe error occurred on the current command.  The results, if any, should be discarded.
    In SQL Server 2012, I can execute it over and over, with no problem.  I've discovered two work-a-rounds:   
    1) Add "WITH RECOMPILE" to the SP CREATE/ALTER statement, or 
    2) Declare the cluster index in the TABLE CREATE statement, e.g. ",UNIQUE CLUSTERED (COL2)" 
    This second option only works though, if the column is unique.    I've opted for the "WITH RECOMPILE" for now.  But, thought I should share.

    Hi,
    I did not get any error Message:
             CREATE TABLE #Temp
               Col1        INT NULL
              ,Col2        INT IDENTITY NOT NULL
              ,Col3        INT NOT NULL
              CREATE CLUSTERED INDEX ix_cl ON #Temp(Col2)
              SET IDENTITY_INSERT #Temp ON;
              RAISERROR('Preparing to INSERT INTO #Temp...',0,1) WITH NOWAIT;
              INSERT INTO #Temp (Col1, Col2, Col3)
              SELECT 1,2,3
              RAISERROR('Insert Success!!!',0,1) WITH NOWAIT;
              SET IDENTITY_INSERT #Temp OFF;
    SELECT * FROM #Temp
    OUTPUT:
    Col1 Col2
    Col3
    1 2 3
    1 2 3
    1 2 3
    Select @@version
    --Microsoft SQL Server 2012 (SP1) - 11.0.3000.0 (X64) 
    Oct 19 2012 13:38:57 
    Copyright (c) Microsoft Corporation
    Enterprise Edition (64-bit) on Windows NT 6.1 <X64> (Build 7601: Service Pack 1)
    Thanks Shiven:) If Answer is Helpful, Please Vote

  • Transactional Replication: Non-Clustered Indexes not copying.

    Hello,
    I set up replication on our servers at work to streamline some procedures we run daily/weekly on them.
    This copies around 15 articles from two databases on the "Master" server to another server used for execution purposes. For the most part it was a pretty straight forward task and it seemed to work nicely; but I realised after some investigation that the
    non-clustered indexes weren't copying over to the child server.
    I set the non-clustered indexes property in the properties of the publishing articles to "True" and generated a new snapshot, this seemed to work, but I've come into work this morning to find the property has reset to "False" and I have no indexes on the
    table again. Why is this happening and is there any way I can resolve the matter so the indexes are copied over concurrently?
    Thanks in advance for your advice.
    JB

    I actually solved this.
    You can use a post-replication SQL script to create the indexes. Whatever articles you're publishing open up the indexes drop down list of the article in object explorer, right-click on an index and hover over Script Index as, then Create-to, then click
    New Query Window editor.
    Up will pop up a new query window with the resulting index. Work your way through all the indexes on all the articles of the publication, copy and pasting just the create index line and below of each script, pull them all together into one query window.
    Once you're done find a safe folder somewhere on your harddrive and save the SQL query as an .sql file with a sensible name.
    Right click on the publication and goto properties. Click on the "Snapshot" tab, in there; there should be a section saying "Run additional scripts". Choose the browse button next to "After applying the Snapshot; execute this script:"
    Navigate to your script file and choose it. Once done click ok and it'll prompt you that something has changed and if you'd like to generate a new snapshot, make sure you do or it won't work.
    That's it, you'll find once the publication has bulk copied over the the subscriptions successfully there are non clustered indexes on the tables. Pretty simple!

  • Transactional Replication Not replicating non-clustered Indexes

    Hi
    I have created a transactional replication.I am sure that I have configured it to replicate Non-Clustered indexes,
    but It does not do so.
    I tried several times to reinitialize the subscription,but still no luck.
    Regards

    It is True for sure.
    But the problem is solved.I had to wait until the Initialize process get completed.
    But I am sure that this problem happened before.Sometimes it works fine but sometimes not.
    Hi ArashMasroor,
    According to your description, it seems that you encounter the issue that non-clustered indexes property is reset to “False” sometimes.
    To work around this issue, you can use a post-replication SQL script to create the indexes. Whatever articles you’re publishing open up the indexes drop down list of the article in object explorer, right-click on an index and levitate over Script Index as,
    then Create-to, then click New Query Window editor.
    Up will pop up a new query window with the resulting index. Work your way through all the indexes on all the articles of the publication, copy and pasting just the create index line and below of each script, pull them all together into one query window.
    Once you’re done find a safe folder somewhere on your hard drive and  save the SQL query as an .sql file with a sensible name. Then you can execute this script after applying the Snapshot. For more details, please review this
    blog.
    There is also a similar thread for your reference.
    https://social.msdn.microsoft.com/Forums/sqlserver/en-US/b0f3870d-1a65-4384-a17b-96825ec5f098/transactional-replication-nonclustered-indexes-not-copying?forum=sqlreplication
    Thanks,
    Lydia Zhang
    Lydia Zhang
    TechNet Community Support

  • Creating a Primary Key in SSMS without Also Creating a Clustered Index

    In the course of development (SQL Server Express 2012) I’m creating various tables which should not have a clustered index on the primary key. However, it seems as if SSMS is obsessed with always doing so. I cannot seem to find a way through the simple
    “right click on column and select "Set Primary Key" method to stop the creation of an associated clustered index. 
    I can work around it fairly easily by having SSMS generate the necessary script and then changing CLUSTERED to NONCLUSTERED, but I’m curious if there is a way to do it purely using the UI that I’m overlooking…

    To be honest, though, until I get much closer to production and have loaded a lot more data I won't know for sure one way or the other - this was more of an awareness question from my part and something that I could not find anyone ever asking on
    the web.
    To add to what David said, the performance impact in the end depends much on the size of the table size and amount of memory available to SQL Server.  All things being equal, performance will be roughly the same with both sequential and random keys
    as long as data are memory resident. But a random key greatly reduces the likelihood need data will be in memory.
    The worst case scenario for single-row selects is an even distribution of random key values, a very large table, and little SQL Server memory.  Nearly every select query will require a physical I/O in this case.  Since each spinning-media disk
    spindle is capable of only 150-200 IOPS so your throughput will be constrained accordingly.
    A big advantage of sequential key values for single-row selects is improved temporal reference locality.  In practice, the most recently inserted/accessed rows are most likely to be subsequently queried.  A single-row query will not only
    read the requested row, but the adjacent rows on the same page as well, thus avoiding costly I/O for a select of those rows.
    See http://www.dbdelta.com/improving-uniqueidentifier-performance/ for an example of how to generate sequential GUIDs from C# code.
    Dan Guzman, SQL Server MVP, http://www.dbdelta.com

  • How do I set access 2002 Upsizing Wizard to create clustered-index on SQL 2005

    Here is an extract from the Acc2Sql2.doc  >>
    By default, the Upsizing Wizard
    transfers all indexes as nonclustered indexes. You can modify the Upsizing
    Wizard to transfer the primary key index to a clustered index. To make this
    change, start Microsoft Access and open the upsizing wizard library database.
    For Microsoft Access 95, the filename is Wzcs.mda. For Microsoft Access 97, the
    filename is Wzcs97.mda. When the database is open, click the Modules tab and open the
    UT_ModUserConstants module. Search down to the UT_CLUSTERED constant. Change
    the default value from False to True.
    <<< end quote
    Question: I am using ACCESS 2002 upsize wizard, I searched my computer for *.mda and could not find any wzcs*.mda.  How do I set it so that it creates clustered-index instead of non-clustered-index?

    Hi,
    This question is not related to the forum. This is a question regarding MS-ACCESS.
    [Personal Site] [Blog] [Facebook]

Maybe you are looking for