I have this table on Microsoft SQL Server 2012:
CREATE TABLE [dbo].[Addresses_line_format]
(
address_id UNIQUEIDENTIFIER NOT NULL
CONSTRAINT pk_addresses_line_format PRIMARY KEY NONCLUSTERED,
country_id UNIQUEIDENTIFIER NOT NULL
CONSTRAINT fk_address_single_line_country FOREIGN KEY REFERENCES Countries (country_id)
ON UPDATE NO ACTION
ON DELETE NO ACTION,
address_line NVARCHAR(255) NOT NULL,
district_line NVARCHAR(255) NOT NULL
)
With 3.362.817 records in it.
Our application consumes messages from a queue, with 10 concurrent consumers. Each consumer inserts a line into this table, using the following statement:
INSERT [dbo].[Addresses_line_format] ([address_id], [country_id], [address_line], [district_line])
VALUES (#0, #1, #2, #3)
Looking at statistics, the average elapsed time for this query is 16 seconds, which is obviously way too much.
I'm wondering if this is because of how heap tables are handling inserts like described here, or do you have any ideas what is causing this?
I tried changing the PK to be clustered, but without any noticeable performance improvements.
Queries against the table are always performed using the following:
SELECT country_id, address_line, district_line
FROM Addresses_line_format
WHERE address_id = #1
Well, if that GUID isn't the clustered key - what IS the clustered key on that table? It should have one - a well chosen clustered key speeds up operations - even inserts and deletes! See Kimberly Tripp's blog post The Clustered Index Debate Continues... for a great explanation and more background.
When you read Kim Tripp's blog post and all her other articles on the subject, it's clear that a good clustering key is narrow, unique, static and ever-increasing - perfect fits for an INT or BIGINT identity column.
Earlier versions of SQL Server (before 2000 or 2005) did in fact have insert hotspots if all the inserts were happening in a single spot - those negative impacts have since been removed, those are no longer a problem, and therefore, using an INT IDENTITY column as your clustering key is a nearly optimal choice for the most part.
16 seconds for one row is too much. Judging by the order of magnitude of this problem this is not an issue of bad index keys or too many indexes. All of that is in the millisecond range. Investigate the actual execution plan. You also can use SQL Profiler to trace what's being executed and how long it takes. Waiting and blocking might also be a reason it takes so long.
Related
Which one is the best choice for primary key in SQL Server?
There are some example code:
Uniqueidentifiers
e.g.
CREATE TABLE new_employees
(employeeId UNIQUEIDENTIFIER DEFAULT NEWID(),
fname VARCHAR(20) )
GO
INSERT INTO new_employees(fname) VALUES ('Karin')
GO
Identity columns
e.g.
CREATE TABLE new_employees
(
employeeId int IDENTITY(1,1),
fname varchar (20)
);
INSERT new_employees
(fname)
VALUES
('Karin');
[Material Code](or Business Code,which identity of a material. e.g. customer identifier)
e.g.
CREATE TABLE new_employees(
[ClientId] [varchar](20) NOT NULL,
[fName] [varchar](20) NULL
)
INSERT new_employees
(ClientID, fname)
VALUES
('C0101000001',--customer identifier,e.g.'C0101000001' a user-defined code.
'Karin');
Please give me some advices for choosing the primary key from the three type identity columns,or other choices.
Thanks!
GUID may seem to be a natural choice for your primary key - and if you really must, you could probably argue to use it for the PRIMARY KEY of the table. What I'd strongly recommend not to do is use the GUID column as the clustering key, which SQL Server does by default, unless you specifically tell it not to.
You really need to keep two issues apart:
the primary key is a logical construct - one of the candidate keys that uniquely and reliably identifies every row in your table. This can be anything, really - an INT, a GUID, a string - pick what makes most sense for your scenario.
the clustering key (the column or columns that define the "clustered index" on the table) - this is a physical storage-related thing, and here, a small, stable, ever-increasing data type is your best pick - INT or BIGINT as your default option.
By default, the primary key on a SQL Server table is also used as the clustering key - but that doesn't need to be that way! I've personally seen massive performance gains when breaking up the previous GUID-based primary / clustered key into two separate keys - the primary (logical) key on the GUID, and the clustering (ordering) key on a separate INT IDENTITY(1,1) column.
As Kimberly Tripp - the Queen of Indexing - and others have stated a great many times - a GUID as the clustering key isn't optimal, since due to its randomness, it will lead to massive page and index fragmentation and to generally bad performance.
Yes, I know - there's newsequentialid() in SQL Server 2005 and up - but even that is not truly and fully sequential and thus also suffers from the same problems as the GUID - just a bit less prominently so.
Then there's another issue to consider: the clustering key on a table will be added to each and every entry on each and every non-clustered index on your table as well - thus you really want to make sure it's as small as possible. Typically, an INT with 2+ billion rows should be sufficient for the vast majority of tables - and compared to a GUID as the clustering key, you can save yourself hundreds of megabytes of storage on disk and in server memory.
Quick calculation - using INT vs. GUID as primary and clustering key:
Base Table with 1'000'000 rows (3.8 MB vs. 15.26 MB)
6 nonclustered indexes (22.89 MB vs. 91.55 MB)
TOTAL: 25 MB vs. 106 MB - and that's just on a single table!
Some more food for thought - excellent stuff by Kimberly Tripp - read it, read it again, digest it! It's the SQL Server indexing gospel, really.
GUIDs as PRIMARY KEY and/or clustered key
The clustered index debate continues
Ever-increasing clustering key - the Clustered Index Debate..........again!
Disk space is cheap - that's not the point!
Unless you have a very good reason, I would argue to use a INT IDENTITY for almost every "real" data table as the default for their primary key - it's unique, it's stable (never changes), it's narrow, it's ever increasing - all the good properties that you want to have in a clustering key for fast and reliable performance of your SQL Server tables!
If you have some "natural" key value that also has all those properties, then you might also use that instead of a surrogate key. But two variable-length strings of max. 20 chars each do not meet those requirements in my opinion.
IDENTITY
PROS
small storage footprint;
optimal join / index performance (e.g. for time range queries, most rows recently inserted will be on a limited number of pages);
highly useful for data warehousing;
native data type of the OS, and easy to work with in all languages;
easy to debug;
generated automatically (retrieved through SCOPE_IDENTITY() rather than assigned);
not updateable (though some consider this a disadvantage, strangely enough).
CONS
cannot be reliably "predicted" by applications — can only be retrieved after the INSERT;
need a complex scheme in multi-server environments, since IDENTITY is not allowed in some forms of replication;
can be duplicated, if not explicitly set to PRIMARY KEY.
if part of the clustered index on the table, this can create an insert hot-spot;
proprietary and not directly portable;
only unique within a single table;
gaps can occur (e.g. with a rolled back transaction), and this can cause chicken little-style alarms.
GUID
PROS
since they are {more or less} guaranteed to be unique, multiple tables/databases/instances/servers/networks/data centers can generate them independently, then merged without clashes;
required for some forms of replication;
can be generated outside the database (e.g. by an application);
distributed values prevent hot-spot (as long as you don't cluster this column, which can lead to abnormally high fragmentation).
CONS
the wider datatype leads to a drop in index performance (if clustered, each insert almost guaranteed to 'dirty' a different page), and an increase in storage requirements;
cumbersome to debug (where userid = {BAE7DF4-DDF-3RG-5TY3E3RF456AS10});
updateable (need to propogate changes, or prevent the activity altogether);
sensitive to time rollbacks in certain environments (e.g. daylight savings time rollbacks);
GROUP BY and other set operations often require CAST/CONVERT;
not all languages and environments directly support GUIDs;
there is no statement like SCOPE_GUID() to determine the value that was generated, e.g. by NEWID();
One thing you'll need to consider in designing your tables is if you'll need to replicate, shard, or otherwise move your data from one place to another. Maybe the data is being generated by other applications and which will need to be kept in sync with yours. An example of that would be a mobile app that creates data and then syncs it with a server. If anything like that is or might be true then UNIQUEIDENTIFIER would the good choice use to use for your primary key.
The UNIQUEIDENTIFIER data type is terrible for performance when used as a clustered index. Yes, you could use newsequentialid(), but that doesn't help you if the values are generated on other devices. The consensus seems to be that clustered indexes are best used with a sequential and narrow data type like an INT or BIGINT.
If you're not concerned with storage space issues then you might try using a combination of both an IDENTITY cluster key and UNIQUEIDENTIFIER primary key. Create a cluster key IDENTITY column and use it for your clustered index (but not as a primary key). Inserts will still be made sequentially and it satisfies the desire for it to be a narrow data type. Now you can use a UNIQUEIDENTIFIER as your primary key. This will allow you to move, replicate, and/or shard your data when you need to.
The cluster key has no other purpose other than to keep your inserts sequential and to be what all the other non-clustered indexes point to when looking up data for a given query. The cluster key is completely throw away and can be regenerated when data is moved, replicated, and/or sharded since uniqueness is handled by the UNIQUEIDENTIFIER primary key.
Here is a great article that demonstrates what happens internally when using an IDENTITY vs a UNIQUEIDENTIFIER for your clustered index.
Effective Clustered Indexes
GUIDs are large but have the advantage of being unique everywhere: this table or that, this server or that, if you have the GUID then everything else is knowable. If that is useful to you, then great, but you will pay for it in overhead, and continue to pay, and pay, and pay....
Material codes only really work for smaller immutable keys, like colors or classification codes and the like. R will always be red, G will be green, it is one byte, etc.
Identity columns come into their own when there may not be a material code, or the natural key is composed of several material codes together, or the natural key is already composed of other identity columns and/or GUIDs, or the natural key is mutable. Yes you could use a GUID but an integer column is much more efficient in all regards.
Another option available in SQL 2012 are sequences, kind of like a database-level identity column. This is a nice halfway house between GUIDs and identity columns, in the sense that a sequence can be used across many tables, so that from a given value, not just the row is knowable, but the table too--but you can still use an INT or BIGINT (or SMALLINT!) if you think that will be enough for your data. That's kind of nifty for certain purposes, kind of like an object id in the OO world.
Be aware that many or the light-weight ORMs expect tables to have a single column primary key, preferably an integer column, and may not play well with anything but an INT IDENTITY PK.
I'm developing a database-intensive application which maintains about 5 tables. These tables contain many thousands of records each. All the tables use GUID clustered primary keys. To make it efficient, I've dropped foreign-keys between the tables.
I am running a script 65000 lines long which creates a whole bunch of tables (including my tables) and stored procedures (about half the time spent there) then proceeds to insert into my tables about 40000 records and then updates about 20000 of those records.
It takes 1:15 on my AMD 3.5 Ghz 8-core machine.
Amazingly, if I change those 5 tables such that
- Add a BIGINT identity surrogate primary key (the queries still join using GUID)
- Demote the prior clustered GUID primary key to a unique column
then it runs in 3:00 minutes!
Changing it from BIGINT to INT gets to about 1:30!
How is it possible that a clustered GUID PK runs significantly faster than an autoincremented INT and much faster than an autoincremented BIGINT clustered PK?
NOTE: the GUID values themselves are generated in code, not by DB.
Check out this simplified benchmark script demonstrating what i mean.
http://pastebin.com/ux5wUJgC
Using your test cases, this is expected. The first test only grows a table with one field. The other two build two columns and two indexes.
Here is a more appropriate test. All three tests have a GUID field and an INT (or BIGINT) field. All fields are indexed. The test table with a PK on an INT with a nonclustered index on the UID is faster by 2 seconds on my server.
Here is my test code: http://pastebin.com/MFTA3Da1
After much testing, it turns out that using guid pk is faster than int surrogate key and a guid natural key.
The talk about avoiding GUID primary keys due to clustering and fragmentation is of little utility since if you're talking about GUID identifiers in the first place, then it's likely that the GUID is intrinsic to the data model and must be stored in the data model anyway, so clearly a single GUID primary key is the simplest and fastest option (by far).
In a nutshell - if you need to identify records with guids then their key should be the guid!
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
The community reviewed whether to reopen this question 2 months ago and left it closed:
Original close reason(s) were not resolved
Improve this question
I have an application that uses GUID as the Primary Key in almost all tables and I have read that there are issues about performance when using GUID as Primary Key. Honestly, I haven't seen any problem, but I'm about to start a new application and I still want to use the GUIDs as the Primary Keys, but I was thinking of using a Composite Primary Key (The GUID and maybe another field.)
I'm using a GUID because they are nice and easy to manage when you have different environments such as "production", "test" and "dev" databases, and also for migration data between databases.
I will use Entity Framework 4.3 and I want to assign the Guid in the application code, before inserting it in the database. (i.e. I don't want to let SQL generate the Guid).
What is the best practice for creating GUID-based Primary Keys, in order to avoid the supposed performance hits associated with this approach?
GUIDs may seem to be a natural choice for your primary key - and if you really must, you could probably argue to use it for the PRIMARY KEY of the table. What I'd strongly recommend not to do is use the GUID column as the clustering key, which SQL Server does by default, unless you specifically tell it not to.
You really need to keep two issues apart:
the primary key is a logical construct - one of the candidate keys that uniquely and reliably identifies every row in your table. This can be anything, really - an INT, a GUID, a string - pick what makes most sense for your scenario.
the clustering key (the column or columns that define the "clustered index" on the table) - this is a physical storage-related thing, and here, a small, stable, ever-increasing data type is your best pick - INT or BIGINT as your default option.
By default, the primary key on a SQL Server table is also used as the clustering key - but that doesn't need to be that way! I've personally seen massive performance gains when breaking up the previous GUID-based Primary / Clustered Key into two separate key - the primary (logical) key on the GUID, and the clustering (ordering) key on a separate INT IDENTITY(1,1) column.
As Kimberly Tripp - the Queen of Indexing - and others have stated a great many times - a GUID as the clustering key isn't optimal, since due to its randomness, it will lead to massive page and index fragmentation and to generally bad performance.
Yes, I know - there's newsequentialid() in SQL Server 2005 and up - but even that is not truly and fully sequential and thus also suffers from the same problems as the GUID - just a bit less prominently so.
Then there's another issue to consider: the clustering key on a table will be added to each and every entry on each and every non-clustered index on your table as well - thus you really want to make sure it's as small as possible. Typically, an INT with 2+ billion rows should be sufficient for the vast majority of tables - and compared to a GUID as the clustering key, you can save yourself hundreds of megabytes of storage on disk and in server memory.
Quick calculation - using INT vs. GUID as Primary and Clustering Key:
Base Table with 1'000'000 rows (3.8 MB vs. 15.26 MB)
6 nonclustered indexes (22.89 MB vs. 91.55 MB)
TOTAL: 25 MB vs. 106 MB - and that's just on a single table!
Some more food for thought - excellent stuff by Kimberly Tripp - read it, read it again, digest it! It's the SQL Server indexing gospel, really.
GUIDs as PRIMARY KEY and/or clustered key
The clustered index debate continues
Ever-increasing clustering key - the Clustered Index Debate..........again!
Disk space is cheap - that's not the point!
PS: of course, if you're dealing with just a few hundred or a few thousand rows - most of these arguments won't really have much of an impact on you. However: if you get into the tens or hundreds of thousands of rows, or you start counting in millions - then those points become very crucial and very important to understand.
Update: if you want to have your PKGUID column as your primary key (but not your clustering key), and another column MYINT (INT IDENTITY) as your clustering key - use this:
CREATE TABLE dbo.MyTable
(PKGUID UNIQUEIDENTIFIER NOT NULL,
MyINT INT IDENTITY(1,1) NOT NULL,
.... add more columns as needed ...... )
ALTER TABLE dbo.MyTable
ADD CONSTRAINT PK_MyTable
PRIMARY KEY NONCLUSTERED (PKGUID)
CREATE UNIQUE CLUSTERED INDEX CIX_MyTable ON dbo.MyTable(MyINT)
Basically: you just have to explicitly tell the PRIMARY KEY constraint that it's NONCLUSTERED (otherwise it's created as your clustered index, by default) - and then you create a second index that's defined as CLUSTERED
This will work - and it's a valid option if you have an existing system that needs to be "re-engineered" for performance. For a new system, if you start from scratch, and you're not in a replication scenario, then I'd always pick ID INT IDENTITY(1,1) as my clustered primary key - much more efficient than anything else!
I've been using GUIDs as PKs since 2005. In this distributed database world, it is absolutely the best way to merge distributed data. You can fire and forget merge tables without all the worry of ints matching across joined tables. GUIDs joins can be copied without any worry.
This is my setup for using GUIDs:
PK = GUID. GUIDs are indexed similar to strings, so high row tables (over 50 million records) may need table partitioning or other performance techniques. SQL Server is getting extremely efficient, so performance concerns are less and less applicable.
PK Guid is NON-Clustered index. Never cluster index a GUID unless it is NewSequentialID. But even then, a server reboot will cause major breaks in ordering.
Add ClusterID Int to every table. This is your CLUSTERED Index... that orders your table.
Joining on ClusterIDs (int) is more efficient, but I work with 20-30 million record tables, so joining on GUIDs doesn't visibly affect performance. If you want max performance, use the ClusterID concept as your primary key & join on ClusterID.
Here is my Email table...
CREATE TABLE [Core].[Email] (
[EmailID] UNIQUEIDENTIFIER CONSTRAINT [DF_Email_EmailID] DEFAULT (newsequentialid()) NOT NULL,
[EmailAddress] NVARCHAR (50) CONSTRAINT [DF_Email_EmailAddress] DEFAULT ('') NOT NULL,
[CreatedDate] DATETIME CONSTRAINT [DF_Email_CreatedDate] DEFAULT (getutcdate()) NOT NULL,
[ClusterID] INT NOT NULL IDENTITY,
CONSTRAINT [PK_Email] PRIMARY KEY NonCLUSTERED ([EmailID] ASC)
);
GO
CREATE UNIQUE CLUSTERED INDEX [IX_Email_ClusterID] ON [Core].[Email] ([ClusterID])
GO
CREATE UNIQUE NONCLUSTERED INDEX [IX_Email_EmailAddress] ON [Core].[Email] ([EmailAddress] Asc)
I am currently developing an web application with EF Core and here is the pattern I use:
All my classes (tables) have an int PK and FK.
I then have an additional column of type Guid (generated by the C# constructor) with a non clustered index on it.
All the joins of tables within EF are managed through the int keys while all the access from outside (controllers) are done with the Guids.
This solution allows to not show the int keys on URLs but keep the model tidy and fast.
This link says it better than I could and helped in my decision making. I usually opt for an int as a primary key, unless I have a specific need not to and I also let SQL server auto-generate/maintain this field unless I have some specific reason not to. In reality, performance concerns need to be determined based on your specific app. There are many factors at play here including but not limited to expected db size, proper indexing, efficient querying, and more. Although people may disagree, I think in many scenarios you will not notice a difference with either option and you should choose what is more appropriate for your app and what allows you to develop easier, quicker, and more effectively (If you never complete the app what difference does the rest make :).
https://web.archive.org/web/20120812080710/http://databases.aspfaq.com/database/what-should-i-choose-for-my-primary-key.html
P.S. I'm not sure why you would use a Composite PK or what benefit you believe that would give you.
Well, if your data never reach millions of rows, you are good. If you ask me, i never use GUID as database identity column of any type, including PK even if you force me to design with a shotgun at the head.
Using GUID as primary key is a definitive scaling stopper, and a critical one.
I recommend you check database identity and sequence option. Sequence is table independent and may provide a solution for your needs(MS SQL has sequences).
If your tables start reaching some dozens of millions of rows the most, e.g. 50 million you will not be able read/write information at acceptable timings and even standard database index maintenance would turn impossible.
Then you need to use partitioning, and be scalable up to half a billion or even 1-2 billion rows. Adding partitioning on the way is not the easiest thing, all read/write statements must include partition column (full app changes!).
These number of course (50 million and 500 million) are for a light selecting useage. If you need to select information in a complex way and/or have lots of inserts/updates/deletes, those could even be 1-2 millions and 50 millions instead, for a very demanding system. If you also add factors like full recovery model, high availability and no maintenance window, common for modern systems, things become extremely ugly.
Note at this point that 2 billion is int limit that looks bad, but int is 4 times smaller and is a sequential type of data, small size and sequential type are the #1 factor for database scalability. And you can use big int which is just twice smaller but still sequential, sequential is what is really deadly important - even more important than size - when to comes to many millions or few billions of rows.
If GUID is also clustered, things are much worst. Just inserting a new row will be actually stored randomly everywhere in physical position.
Even been just a column, not PK or PK part, just indexing it is trouble. From fragmentation perspective.
Having a guid column is perfectly ok like any varchar column as long as you do not use it as PK part and in general as a key column to join tables. Your database must have its own PK elements, filtering and joining data using them - filtering also by a GUID afterwards is perfectly ok.
Having sequential ID's makes it a LOT easier for a hacker or data miner to compromise your site and data. Keep that in mind when choosing a PK for a website.
If you use GUID as primary key and create clustered index then I suggest use the default of NEWSEQUENTIALID() value for it.
Another reason not to expose an Id in the user interface is that a competitor can see your Id incrementing over a day or other period and so deduce the volume of business you are doing.
Most of the times it should not be used as the primary key for a table because it really hit the performance of the database.
useful links regarding GUID impact on performance and as a primary key.
https://www.sqlskills.com/blogs/kimberly/disk-space-is-cheap/
https://www.sqlskills.com/blogs/kimberly/guids-as-primary-keys-andor-the-clustering-key/
Summary: I have a table populated via the following:
insert into the_table (...) select ... from some_other_table
Running the above query with no primary key on the_table is ~15x faster than running it with a primary key, and I don't understand why.
The details: I think this is best explained through code examples.
I have a table:
create table the_table (
a int not null,
b smallint not null,
c tinyint not null
);
If I add a primary key, this insert query is terribly slow:
alter table the_table
add constraint PK_the_table primary key(a, b);
-- Inserting ~880,000 rows
insert into the_table (a,b,c)
select a,b,c from some_view;
Without the primary key, the same insert query is about 15x faster. However, after populating the_table without a primary key, I can add the primary key constraint and that only takes a few seconds. This one really makes no sense to me.
More info:
The estimated execution plan shows 0% total query time spent on the clustered index insert
SQL Server 2008 R2 Developer edition, 10.50.1600
Any ideas?
Actually its not as clear cut as Ryk suggests.
It can actually be faster to add data to a table with an index then in a heap.
Read this arctle - and as far as i am aware its quite well regarded:
http://www.sqlskills.com/blogs/kimberly/post/The-Clustered-Index-Debate-Continues.aspx
Bear in mind its written by SQL Server MVP and a Microsoft Regional Director.
Inserts are faster in a clustered table (but only in the "right" clustered table) than compared to a heap. The primary problem here is that lookups in the IAM/PFS to determine the insert location in a heap are slower than in a clustered table (where insert location is known, defined by the clustered key). Inserts are faster when inserted into a table where order is defined (CL) and where that order is ever-increasing. I have some simple numbers but I'm thinking about creating a much larger/complex scenario and publishing those. Simple/quick tests on a laptop are not always as "exciting".
I think if you create a simple primary key that is clustered and made up of a single auto-incrementing column, then inserts into such a table might be faster. Most likely, a primary key made up of multiple columns may be the cause of slowdown in inserts. When you use a composite key for primary key, then rows inserted may not get added to the end of table but may need to be added somewhere in the middle of existing physical order of rows in table, which adds to the insert time and hence makes the INSERTS slower. So use a single auto-incrementing column as the the primary key value in your case to speed up inserts.
This is a good question, but a pretty crappy question too. Before you ask why an index slows down inserts, do you know what an index is?
If not, I suggest you read up on it. A clustered index is a B-tree, (Balanced tree), so every insert has to .... wait for it.... balance the tree. Hence clustered inserts are slower than inserting on heaps. If you don't know what a heap is, then I suggest stop using SQL Server until you understand basics. Else you are attempting to use a product of which you have no idea what you are doing, and basically driving a truck on the highway, blindfolded, thinking you are riding a bike. Unexpected results...
So when you create a clustered Index after a table is populated, your 'heap' has some statistics to use, and SQL can basically optimise a few things. This process is much more complicated than this, but in some cases you will find that creating a clustered index after the fact could be a lot slower than simply to insert to it. This has all to do with key types, number of columns, types of columns etc. This is unfortunately not a topic that is fit for an answer, this is more a whole course and few books by itself. Looking at your table above, it is a VERY simple table with ~7byte rows. In this instance a create-index after the insert will be faster, but chuck in a few varchar(250)'s etc, and the ballgame changes.
If you didn't know, a clustered index, (if your table has one), IS your table.
Hope this helps.
Defining a column to be a primary in table on SQL Server - will this make inserts slower?
I ask because I understand this is the case for indexes.
The table has millions of records.
No, not necessarily! Sounds counter-intuitive, but read this quote from Kim Tripp's blog post:
Inserts are faster in a clustered
table (but only in the "right"
clustered table) than compared to a
heap. The primary problem here is that
lookups in the IAM/PFS to determine
the insert location in a heap are
slower than in a clustered table
(where insert location is known,
defined by the clustered key). Inserts
are faster when inserted into a table
where order is defined (CL) and where
that order is ever-increasing.
So actually, having a good clustered index (e.g. on a INT IDENTITY column, if ever possible) does speed things up - even insert, updates and deletes!
Primary keys are automatically indexed, clustered if possible and failing that non-clustered.
So in that sense inserts are slightly affected, but of course having no primary key would usually be much much worse, assuming the table needs a primary key.
First measure, identify a problem and then try to optimize. Optimizing away primary keys is a very bad idea in general.
Not enough to create a perceptual performance hit, and the benefits far outweigh the very minor perforamnce issues. There are very very few scenarios where you should not put a primary key on a table.
The really quick answer is:
Yes.
Primary keys are always indexed (and SQL will attempt a clustered index). Indexes make inserts slower, clustered indexes even more so.
Depending on what your table is used for, you may have a couple of options.
If you do a lot of bulk inserts then reads, you can remove the primary key, insert into a heap (if you have SQL 2008 this can be minimally logged to run even faster) then reassign the key and wait for the index to run.
As an addendum to that, you can also insert using an ORDER BY clause which will keep the inserted rows in correct order for the clustered index. This will really only help if you are inserting millions of rows at once from a source that is already ordered, though.
Yes, adding a primary key to a table will slow inserts (which is OK, because not adding a primary key to your table will speed up your application's eventual catastrophic failure).
If what you're doing is creating a new table and then inserting millions of records into it, there is nothing wrong with initially creating the table without a primary key, inserting all the records, and then creating the primary key. Or use an alternative tool to perform a bulk insert.
Yes, inserts are slowed, especially with several clients doing inserts simultaneously, and more so if your key is sequentially increasing (all inserts occur at the right-most nodes of the index tree, in most database implementations, or at the last page of the table for e.g. clustered SQL Server indices -- both of which scenarios cause resource contention).
That said, SELECTs using the primary key are speeded up quite a bit, and the integrity of your key is guaranteed. Do the right thing first (define primary keys everywhere). Second, measure to see if you cannot meet your performance targets, and whether this is caused by your data integrity constraints. Only then consider workarounds.
No, not necessarily
Regardless, that is not why you would define a primary key on a table.
You define a primary key when it is REQUIRED by the domain model.