Creating A Primary Key As A Non Clustered Index

Jul 18, 2007

Hi,



I have created a very simple table. Here is the script:

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[IndexTable]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[IndexTable]

GO

CREATE TABLE [dbo].[IndexTable] (
[Id] [int] NOT NULL ,
[Code] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
) ON [PRIMARY]

GO


CREATE CLUSTERED INDEX [CusteredOnCode] ON [dbo].[IndexTable]([Id]) ON [PRIMARY]

GO

ALTER TABLE [dbo].[IndexTable] ADD
CONSTRAINT [PrimaryKeyOnId] PRIMARY KEY NONCLUSTERED
(
[Id]
) ON [PRIMARY]
GO



The records that i added are:

Id Code

1 a
2 b
3 aa
4 bb

Now when i query like

Select * from IndexTable

I expect the results as:

Id Code

1 a
3 aa
2 b
4 bb

as i have the clustered index on column Code.

But i m getting the results as:

Id Code

1 a
2 b
3 aa
4 bb

as per the primary key order that is a non clustered index.

Can anyone explain why it is happening?


Thanks

Nitin

View 3 Replies


ADVERTISEMENT

DB Engine :: How To Convert Unique Clustered Index Into Clustered Primary Key To Use With Change Tracking

Sep 4, 2015

We are going to use SQL Sever change tracking. The problem is that some of our tables, which are to be tracked, have no primary keys. There are only unique clustered indexes. The question is what is the best way to turn on change tracking for these tables in our circumstances.

View 4 Replies View Related

DB Design :: Script To Create Table With Primary Key Non-clustered And Clustered Index

Aug 28, 2015

I desire to have a clustered index on a column other than the Primary Key. I have a few junction tables that I may want to alter, create table, or ...

I have practiced with an example table that is not really a junction table. It is just a table I decided to use for practice. When I execute the script, it seems to do everything I expect. For instance, there are not any constraints but there are indexes. The PK is the correct column.

CREATE TABLE [dbo].[tblNotificationMgr](
[NotificationMgrKey] [int] IDENTITY(1,1) NOT NULL,
[ContactKey] [int] NOT NULL,
[EventTypeEnum] [tinyint] NOT NULL,

[code]....

View 20 Replies View Related

Data Warehousing :: Difference Between Primary Key With Clustered And Non-clustered Index

Jul 19, 2013

I have created two tables. table one has the following fields,

                      Id -> unique clustered index.
         table two has the following fields,
                      Tid -> unique clustered index
                      Id -> foreign key of table one(id).

Now I have created primary key for the table one column 'id'. It's created as "nonclustered, unique, primary key located on PRIMARY". Primary key create clustered index default. since unique clustered index existed in table one, it has created "Nonclustered primary key".

My Question is, What is the difference between "clustered, unique, primary key" and "nonclustered, unique, primary key"? Is there any performance impact between these?

View 5 Replies View Related

Primary Key Without Clustered Index

Jan 28, 2008

Dear All,
i've read one article that with some option, we can avoid creating clustered index on the primary key column. is ti possible?

how can we create a primary key without allowing sql server to create automaticaly a clustered index?

Vinod
Even you learn 1%, Learn it with 100% confidence.

View 1 Replies View Related

Primary Key With Non-clustered Index

Dec 11, 2007

Dear all,


I want to keep certain archive data in certain tables. One such table is currently about 190 GB in size. It has a primary key with clustered index and three non-clustered indexes. The type of queries fired are strictly selects (daily) and inserts (only monthly).

Question: Is it advisable to have a non-clustered index on the primary key column?.....I am finding that the insert performance is getting hurt due to presence of clustered index on such a large table (190 GB).

Let me know your views.


Regards,

Chetan

View 3 Replies View Related

Clustered Index On Composite Primary Key

Jul 23, 2005

Is that possible on SQL Server 2000 and onwards?

View 1 Replies View Related

Dropping Clustered Index Associated With Primary Key.

Aug 24, 2007

Hi all,


I have a huge table with million of rows, which has ONE Clustered index associated with the PRIMARY KEY, and there are some NON_Clustered indexes.


So,now i decided that, i dont need any more indexes ( not even one) on that table, but i need to maintain primary key on that table.


(a) So, how can i accomplish this (i.e.) having primay key but not having indexes on the table.


Thanks.

View 6 Replies View Related

Transact SQL :: Dropping Clustered Index On Primary Key Which Is In Replication?

Oct 2, 2015

I am trying to drop a primary key on column LID and then create a clustered index on a new identity column ID and then add the primary key back on the LID. I am not able to do so due the table being in replication. here is the error:

Cannot alter the table '' because it is being published for replication.

How do I get past the error and create the Clustered Index on ID column in both publisher and subscriber?

View 2 Replies View Related

Creating And Moving Clustered Index

Dec 20, 2006

have a 3rd party app (can't change) which has some bad sql. I have a table that is used in the sql which if I put a clustered (I had an index on the fields in the sql but it would ignore and table scan) will use and stop doing table scan. this is a million row table that is growing. the data going in is pretty mich insert only. I have a separate array and file group which I have moved indexes to last year. 2 questions

1. If I would make a clustered index on the separate RAID and file group, doesn't the table need to go with it. I thought the clustered index and table had to be on same File Group

2. If I do this anyone see any issues with moving this table and index on this file group

View 2 Replies View Related

Performance Creating Clustered Index

Sep 29, 2005

Hi Guys,

I have a SQL 2000 sp3a server on Windows 2000 sp4. Running dual proc server with hyper threading enabled, 3gb memory attached to a HP EVA 5000 SAN.

One of the tables is 67gb and contains 140,000,000 rows. Recently someone dropped the clustered indexe so i`m trying to put it back (i've dropped the non clustered indexes as no point leaving them there whilst clustered builds).

The problem i am having is the rebuild is taking forever!! It ran for 23 hours before someone rebooted the server (!). The database is currently recovering from the reboot but i need to work out what is causing the appalling performance so i can get the index rebuilt. There are no reported hardware problems.....

There are multiple file groups involved and i found i was getting an extent allocation rate of 1.5 extents a second and same for deallocation.

Any advice on how to trouble shoot this?

View 12 Replies View Related

Access Violation Creating Clustered Index

Oct 26, 2000

Hi, Folks!

I'm receiving Access Violation Error when I'm trying to create a clustered index on a datetime field on a table that have around 4 million records, if I create the index nonclustered, no problem, but clustered the system raise this error!

Any help will be appreciate a lot!

Thanks in advance!

Armando Marrero
Cti. Miami

View 1 Replies View Related

Creating Non Clustered Index On DateTime Column

Dec 24, 2014

I have 5 million rows of table, and going to create Non Clustered Index for Datetime values column. Creating Non clustered Index on Datetime value column will affect performance or not.

View 4 Replies View Related

Update Statement Performing Table Lock Even Though Where Condition On Clustered Primary Index?

Jul 20, 2005

Hi All,I have a database that is serving a web site with reasonably hightraffiic.We're getting errors at certain points where processes are beinglocked. In particular, one of our people has suggested that an updatestatement contained within a stored procedure that uses a wherecondition that only touches on a column that has a clustered primaryindex on it will still cause a table lock.So, for example:UPDATE ORDERS SETprod = @product,val = @valWHERE ordid = @ordidIn this case ordid has a clustered primary index on it.Can anyone tell me if this would be the case, and if there's a way ofensuring that we are only doing a row lock on the record specified inthe where condition?Many, many thanks in advance!Much warmth,Murray

View 1 Replies View Related

Simple Query Chooses Clustered Index Scan Instead Of Clustered Index Seek

Nov 14, 2006

the query:

SELECT a.AssetGuid, a.Name, a.LocationGuid
FROM Asset a WHERE a.AssociationGuid IN (
SELECT ada.DataAssociationGuid FROM AssociationDataAssociation ada
WHERE ada.AssociationGuid = '568B40AD-5133-4237-9F3C-F8EA9D472662')

takes 30-60 seconds to run on my machine, due to a clustered index scan on our an index on asset [about half a million rows].  For this particular association less than 50 rows are returned. 

expanding the inner select into a list of guids the query runs instantly:

SELECT a.AssetGuid, a.Name, a.LocationGuid
FROM Asset a WHERE a.AssociationGuid IN (
'0F9C1654-9FAC-45FC-9997-5EBDAD21A4B4',
'52C616C0-C4C5-45F4-B691-7FA83462CA34',
'C95A6669-D6D1-460A-BC2F-C0F6756A234D')

It runs instantly because of doing a clustered index seek [on the same index as the previous query] instead of a scan.  The index in question IX_Asset_AssociationGuid is a nonclustered index on Asset.AssociationGuid.

The tables involved:

Asset, represents an asset.  Primary key is AssetGuid, there is an index/FK on Asset.AssociationGuid.  The asset table has 28 columns or so...
Association, kind of like a place, associations exist in a tree where one association can contain any number of child associations.  Each association has a ParentAssociationGuid pointing to its parent.  Only leaf associations contain assets. 
AssociationDataAssociation, a table consisting of two columns, AssociationGuid, DataAssociationGuid.  This is a table used to quickly find leaf associations [DataAssociationGuid] beneath a particular association [AssociationGuid].  In the above case the inner select () returns 3 rows. 

I'd include .sqlplan files or screenshots, but I don't see a way to attach them. 

I understand I can specify to use the index manually [and this also runs instantly], but for such a simple query it is peculiar it is necesscary.  This is the query with the index specified manually:

SELECT a.AssetGuid, a.Name, a.LocationGuid
FROM Asset a WITH (INDEX (IX_Asset_AssociationGuid)) WHERE
a.AssociationGuid IN (
SELECT ada.DataAssociationGuid FROM AssociationDataAssociation ada
WHERE ada.AssociationGuid = '568B40AD-5133-4237-9F3C-F8EA9D472662')

To repeat/clarify my question, why might this not be doing a clustered index seek with the first query?

View 15 Replies View Related

SQL Server 2008 :: Change Primary Key Non-clustered To Primary Key Clustered

Feb 4, 2015

We have a table, which has one clustered index and one non clustered index(primary key). I want to drop the existing clustered index and make the primary key as clustered. Is there any easy way to do that. Will Drop_Existing support on this matter?

View 2 Replies View Related

Creating Primary INDEX Problem

May 30, 2000

I created table and also I define the primary key its okay

but when I generate the SQL script for that table its not
creating the primary key

CREATE TABLE [dbo].[table1] (
[emp_id] [int] NOT NULL ,
[emp_name] [char] (25) NULL ,
[emp_address] [nvarchar] (50) NULL
) ON [PRIMARY]
GO


PS: I want to use emp_id as primary key but its not defined in the sql script

Thankx a lot

View 3 Replies View Related

Creating Clustered Index On View With Table Containing XML Data Types Takes Forever And Causes Timeouts

Apr 21, 2007

I am trying to create a clustered index on a View of a table that has an xml datatype. This indexing ran for two days and still did not complete. I tried to leave it running while continuing to use the database, but the SELECT statements where executing too slowly and the DML statements where Timing out. I there a way to control the server/cpu resources used by an indexing process. How can I determine the completion percentage or the indexing process. How can I make indexing the view with the xml data type take less time?



The table definition is displayed below.



CREATE TABLE [dbo].[AuditLogDetails](

[ID] [int] IDENTITY(1,1) NOT NULL,

[RecordID] [int] NOT NULL,

[TableName] [varchar](64) NOT NULL,

[Modifications] [xml] NOT NULL,

CONSTRAINT [PK_AuditLogDetails] 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]



The view definition is displayed below.



ALTER VIEW [dbo].[vwAuditLogDetails] WITH SCHEMABINDING

AS

SELECT P.ID,D.RecordID, dbo.f_GetModification(D.Modifications,P.ID) AS Modifications

FROM dbo.AuditLogParent P

INNER JOIN dbo.AuditLogDetails AS D ON dbo.f_GetIfModificationExist(D.Modifications,P.ID)=1



The definition for UDF f_GetModification



ALTER function [dbo].[f_GetModification]( @Modifications xml,@PID uniqueidentifier )

returns xml

with schemabinding

as

begin

declare @pidstr varchar(100)

SET @pidstr = LOWER(CONVERT(varchar(100), @PID))

return @Modifications.query('/Modifications/modification[@ID eq sql:variable("@pidstr")]')

end





The definition for UDF f_GetIfModificationExist



ALTER function [dbo].[f_GetIfModificationExist]( @Modifications xml,@PID uniqueidentifier )

returns Bit

with schemabinding

as

begin

declare @pidstr varchar(100)

SET @pidstr = LOWER(CONVERT(varchar(100), @PID))

return @Modifications.exist('/Modifications/modification[@ID eq sql:variable("@pidstr")]')

end



The Statement to create the index is below.



CREATE UNIQUE CLUSTERED INDEX [IX_ID_RecordID] ON [dbo].[vwAuditLogDetails]

(

[ID] ASC,

[RecordID] ASC

)WITH (STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]

View 1 Replies View Related

Data Warehousing :: Primary Key Has Both A Clustered And Non-clustered Constraint

Sep 30, 2015

I have a really super slow stored proc that does something simple. it updates a table if certain values are received.

In looking at this the matching is done on the Primary Key, which is set as a Clustered index, looking further I have another constraint, that sets the same column to a Unique, Non-Clustered.

I am not sure why this was done, but it seems to be counter productive.  I have read only references to Which one is better on a primary key, but not can their be both and if it is "Smart".

View 4 Replies View Related

Create Clustered Or Non-clustered Index On Large Table ( SQL Server 7 )

Jan 4, 2008

I have large table with 10million records. I would like to create clustered or non-clustered index.

What is the quick way to create? I have tried once and it took more than 10 min.

please help.

View 1 Replies View Related

How To Alter A Non Clustered Primary Key Constraint To Clustered

Feb 26, 2008

Hello,


I've a table with primary key defined as non-clusterd, now without dropping it can I modify the existing index to clustered through tsql as I had to write some migration script and in that script I wanna do this.


Thanks in Advance,


Rohit

View 5 Replies View Related

Converting A Clustered Index On A PK Identity Field To Non-clustered

Sep 8, 2006

Hi there, I have a table that has an IDENTITY column and it is the PK of this table. By default SQL Server creates a unique clustered index on the PK, but this isn't what I wanted. I want to make a regular unique index on the column so I can make a clustered index on a different column.

If I try to uncheck the Clustered index option in EM I get a dialog that says "Cannot convert a clustered index to a nonclustered index using the DROP_EXISTING option.". If I simply try to delete the index I get the following "An explicit DROP INDEX is not allowed on index 'index name'. It is being used for PRIMARY KEY constraint enforcement.

So do I have to drop the PK constraint now? How does that affect all the tables that have FK relationships to this table?

Thanks

View 3 Replies View Related

Include Clustered Index In Non-clustered Index?

Oct 15, 2007

Hi everybody!

I just ran the Database Engine Tuning Advisor on a relative complex query to find out if a new index might help, and in fact it found a combination that should give a performance gain of 94%. Fair enough to try that.

What I wonder about: The index I should create contains 4 columns, the last of them being the Primary Key column of the table, which is also my clustered index for the table. It is an identity integer btw.

I think I remember that ANY index does include the clustered one as lookup into the data, so having it listed to the list of columns will not help. It might at worst add another duplicate 4 bytes to each index entry.

Right? Wrong? Keep the column in the index, or remove it since it is included implicit anyway?

Thanks for suggestions!
Ralf

View 3 Replies View Related

Clustered Index On Client_ID+ORderNO+OrdersubNo, If I Create 3 Noncluster Index On Said Column Will It Imporve Performance

Dec 5, 2007



Dear All.

We had Teradata 4700 SMP. We have moved data from TD to MS_SQL SERVER 2003. records are 19.65 Millions.

table is >> Order_Dtl

Columns are:-

Client_ID varchar 10
Order_ID varchar 50
Order_Sub_ID decimal
.....
...
..
.
Pk is (ClientID+OrderId+OrderSubID)

Web Base application or PDA devices use to initiate the order from all over the country. The issue is this table is not Partioned but good HP with 30 GB RAM is installed. this is main table that receive 18,0000 hits or more. All brokers and users are using this table to see the status of their order.

The always search by OrderID, or ClientID or order_SubNo, or enter any two like (Client_ID+Order_Sub_ID) or any combination.

Query takes to much time when ever server receive more querys. some orther indexes are also created on the same table like (OrderDate, OrdCreate Date and Status)

My Question are:-


Q1. IF Person "A" query to DB on Client_ID, then what Index will use ? (If any one do Query on any two combination like Client_ID+Order_ID, So what index will be uesd.? How does MS-SQL SERVER deal with these kind of issues.?

Q2. If i create 3 more indexes on ClientID, ORderID and OrdersubID. will this improve the performance of query.if person "A" search record on orderNo so what index will be used. (Mind it their would be 3 seprate indexes for Each PK columns) and composite-Clustered index is also available.?

Q3. I want to check what indexes has been used? on what search?

Q4. How can i check what table was populated when, or last date of update (DML)?

My Limitation is i Dont Create a Partioned table. I dont have permission to do it.



In Teradata we had more than 4 tb record of CRM data with no issue. i am not new baby in db line but not expert in sql server 2003.


I am thank u to all who read or reply.

Arshad

Manager Database
Esoulconsultancy.com

(Teradata Master)
10g OCP










View 3 Replies View Related

Clustered And Non Clustered Index On Same Columns

Nov 1, 2007

I have a table<table1> with 804668 records primary on table1(col1,col2,col3,col4)

Have created non-clustered index on <table1>(col2,col3,col4),to solve a performance issue.(which is a join involving another table with 1.2 million records).Seems to be working great.

I want to know whether this will slow down,insert and update on the <table1>?

View 2 Replies View Related

Advantages Of Using Nonclustered Index After Using Clustered Index On One Table

Jul 3, 2006

Hi everyone,
When we create a clustered index firstly, and then is it advantageous to create another index which is nonclustered ??
In my opinion, yes it is. Because, since we use clustered index first, our rows are sorted and so while using nonclustered index on this data file, finding adress of the record on this sorted data is really easier than finding adress of the record on unsorted data, is not it ??

Thanks

View 4 Replies View Related

SQL 2012 :: Clustered Index Key Order In NC Index

Mar 5, 2015

I have a clustered index that consists of 3 int columns in this order: DateKey, LocationKey, ItemKey (there are many other columns in this data warehouse table such as quantities, prices, etc.).

Now I want to add a non-clustered index on just one of the other columns, say LocationKey, like this:
CREATE INDEX IX_test on TableName (LocationKey)

I understand that the clustered index keys will also be added as key columns to any NC indexes. So, in this case the NC index will also get the other two columns from the clustered index added as key columns. But, in what order will they be added?

Will the resulting index keys on this new NC index effectively be:

LocationKey, DateKey, ItemKey
OR
LocationKey, ItemKey, DateKey

Do the clustering keys get added to a NC index in the same order as they are defined in the clustered index?

View 1 Replies View Related

Clustered Index Vs. Full Text Index

Jun 18, 2008

Quick question about the primary purpose of Full Text Index vs. Clustered Index.

The Full Text Index has the purpose of being accessible outside of the database so users can query the tables and columns it needs while being linked to other databases and tables within the SQL Server instance.
Is the Full Text Index similar to the global variable in programming where the scope lies outside of the tables and database itself?

I understand the clustered index is created for each table and most likely accessed within the user schema who have access to the database.

Is this correct?

I am kind of confused on why you would use full text index as opposed to clustered index.

Thank you
Goldmember

View 2 Replies View Related

Clustered Index Or NonClustered Index

Apr 1, 2006

Hello I want to learn disparity clustered index or nonclustered index and in queries which one run better.

example

select * from orders where orderID=5

to this query clustered or nonclustered

thanks



View 3 Replies View Related

Clustered/non-Clustered Index

Dec 6, 2005

What does an index add to the performance?
Why do we use Clustered Index and Non-clustered Index?
 
thanks

View 3 Replies View Related

Clustered Primary Key And Foreign Key: T-SQL

Jun 10, 2005

I am having a little trouble getting this to work right, but have come a ways since I started this.......other tables created first and with no problems..... then these two with the last table being the problemI need to set one foreign key in the second table referencing the first table.But, the primary key is clustered with the two foreign keys and I get the error....There are no primary or candidate keys in the referenced table 'courseScores' that match the referencing column list in the foreign key 'FK_course'.CREATE TABLE dbo.courseScores   (     courseId varchar(20) NOT NULL    CONSTRAINT FK_courseId_courseStructure2 FOREIGN KEY (courseId)    REFERENCES courseStructure (courseId), 
    studentId varchar(20) NOT NULL    CONSTRAINT FK_studentId_students2 FOREIGN KEY (studentId)    REFERENCES students (studentId), 
    CONSTRAINT PK_courseScore PRIMARY KEY CLUSTERED (courseId, studentId)
          )CREATE TABLE dbo.objScores  (  tmp int IDENTITY(1,1) PRIMARY KEY,    objective varchar(50) NOT NULL,        courseId varchar(20) NOT NULL    CONSTRAINT FK_course FOREIGN KEY (courseId)    REFERENCES courseScores  (courseId)                  )
Once I get it working, then the tmp will be gone and then set 3 foreign keys as the clustered primary, fyi.Not sure how to reference half a primary key?Any help is greatly appreciated.....Thanks all,Zath

View 4 Replies View Related

Dropping Primary, Clustered Key Via T-SQL

Apr 9, 2003

I'm changing the collation sequence of a field which is a primary, clustered key field via:

ALTER TABLE [dbo].[clusterAlgorithm] WITH NOCHECK ADD
PRIMARY KEY CLUSTERED
(
[ClusterAlgorithmClassName]
) ON [PRIMARY]
GO

Is there a way to drop the primary key designation before doing an alter table/alter column statement and then recreating the key, or must I drop and recreate the table?

Thanks,

Al

View 1 Replies View Related

Clustered Indexes On Primary Keys

Aug 18, 2006

All of the 3 books I've read say it is not a good idea to create a clustered index on the primary key but it is created as the default. My question is has this changed in 2005? My understanding is to create the clustered index on columns used first in join clauses and then in where clauses, what is the answer?

View 14 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved