Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sql Data Type for Primary Key - SQL Server?

Which sql data type should we use for number bases primary key:

  1. int
  2. bigint
  3. numeric
  4. float
like image 523
Ramesh Soni Avatar asked Nov 01 '08 05:11

Ramesh Soni


People also ask

Can primary key be any data type?

A primary key (PK) is a specific type of database constraint. It guarantees that the column (or columns) that are part of it do not accept NULL values and that the value (or combination of values) entered for each row is unique. Tables may have multiple UNIQUE keys (which accept NULLs), but only one primary key.

How set varchar as primary key in SQL Server?

Use surrogate key ID INT IDENTITY(1,1) for Primary Key. Make the product_id column UNIQUE KEY or place a UNIQUE INDEX on it. key.

Which field will be suitable for primary key?

The customer ID field is the primary key. Access automatically creates an index for the primary key, which helps speed up queries and other operations. Access also ensures that every record has a value in the primary key field, and that it is always unique.


2 Answers

Generally, int.

bigint if you think you'll have more rows than there are atoms in the universe.

uniqueidentifier is useful if you need globally unique keys (keys that are guaranteed to be unique across all tables in your schema, maybe even universally unique (I don't remember))

The other two I wouldn't use they're not integral types (they have fractions, which just don't make a lot of sense as keys)

like image 65
Ken Gentle Avatar answered Sep 19 '22 17:09

Ken Gentle


You really need to keep two separate issues apart:

1) the primary key is a logical construct - one of the key candidates that uniquely and reliably identifies a row in your table. This can be anything, really - an INT, a GUID, a string - pick what makes most sense for your scenario.

2) 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 seems massive performance gains over time 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.

The index fragmentation was down to minimal levels, and thus the index seek performance was was up - highly recommended !

Marc

like image 24
marc_s Avatar answered Sep 22 '22 17:09

marc_s