INDEX NAME on PRIMARY KEY - sql-server

I would like create a table and add to it a Primary Key.
As for my understanding MS SQL add a clustered Index on the Primary Key and will name it with a default name.
I would like to know if is possible create a table and ASSIGN a custom name for the index created by default or how can i change the default name after the table as been created.
Thanks!

Sure - you can define the PRIMARY KEY constraint in your CREATE TABLE statement.
This will generate the default PRIMARY KEY
CREATE TABLE dbo.Table
(ID INT IDENTITY PRIMARY KEY,
.......)
but you can totally define the name of the constraint, too:
CREATE TABLE dbo.Table2
(ID INT IDENTITY CONSTRAINT PK_Table2 PRIMARY KEY,
......)

When you create a Clustered Primary Key, you do´nt create a index, but a Table organized as index.
Clustered Primary key is default option when you create a table with primary key on SqlServer.
http://msdn.microsoft.com/en-us/library/aa933131(SQL.80).aspx

Related

Add primary key to the table coulmn(please see the attached image for more clarity)

Creating table without using SQL table feature:
I'm trying to create table going to "Tables","Create Table" feature. How do I add primary and unique keys using this feature.
Right click on the selected column and set the option primary key from the context menu.
It has been shown below.
The documentation covers this nicely: From Create Primary Keys
Using SQL Server Management Studio
To create a primary key
In Object Explorer, right-click the table to which you want to add a unique constraint, and click Design.
In Table Designer, click the row selector for the database column you want to define as the primary key. If you want to select multiple
columns, hold down the CTRL key while you click the row selectors for
the other columns.
Right-click the row selector for the column and select Set Primary Key.
Or, if you want to use Transact-sQL
Using Transact-SQL
To create a primary key in an existing table
The following example creates a primary key on the column
TransactionID in the AdventureWorks database.
ALTER TABLE Production.TransactionHistoryArchive
ADD CONSTRAINT PK_TransactionHistoryArchive_TransactionID PRIMARY KEY CLUSTERED (TransactionID);
It also goes on to explain how you can use T-SQL to create a NONCLUSTERED Primary key, and then add a further CLUSTERED INDEX on the table:
To create a primary key with clustered index in a new table
The following example creates a table and defines a primary key on the
column CustomerID and a clustered index on TransactionID in the
AdventureWorks database.
-- Create table to add the clustered index
CREATE TABLE Production.TransactionHistoryArchive1
(
CustomerID uniqueidentifier DEFAULT NEWSEQUENTIALID()
, TransactionID int IDENTITY (1,1) NOT NULL
, CONSTRAINT PK_TransactionHistoryArchive1_CustomerID PRIMARY KEY NONCLUSTERED (CustomerID)
)
;
-- Now add the clustered index
CREATE CLUSTERED INDEX CIX_TransactionID ON Production.TransactionHistoryArchive1 (TransactionID);

Can I make Primary Key non clustered while another index is clustered?

In my table I have ID as primary key, it is just a meaningless unique code
as it is a primary key SQL Server 2017 made it clustered.
I have another column in my table called myTime this is a timestamp with non uinique non clustered index
Can I make the PK a non clustered and the index is clustered and how?
Yes you can. If you already have an existing table then you need to:
Drop the current clustered PRIMARY KEY
Create your CLUSTERED INDEX
Create a PRIMARY KEY NONCLUSTERED
For example:
IF OBJECT_ID('tempdb..#Test') IS NOT NULL
DROP TABLE #Test
CREATE TABLE #Test (
ID INT,
TimeStamp DATETIME,
CONSTRAINT PK_Test PRIMARY KEY (ID)) -- Clustered by default
ALTER TABLE #Test DROP PK_Test
CREATE CLUSTERED INDEX CI_Test_TimeStamp ON #Test (TimeStamp)
ALTER TABLE #Test ADD CONSTRAINT PK_Test PRIMARY KEY NONCLUSTERED (ID)
The only thing that will enforce uniqueness is the PRIMARY KEY constraint, you can still have a clustered index on repeated values, although it might raise an eyebrow for performance. See Eric's link for details.
Yes you can, by specifying the primary key be nonclustered.
ALTER TABLE TableName
ADD CONSTRAINT PK_name PRIMARY KEY NONCLUSTERED (ID);
You make another index clustered by specifying a clustered index.
CREATE CLUSTERED INDEX IX_Name
ON dbo.TableName (ColumnName);

SQL Server foreign relationship on two-column primary key

I have the following three sample tables (simplified demo for purpose of question):
CREATE TABLE Teams
(
Id int IDENTITY(1,1) NOT NULL,
Name varchar(50) NOT NULL,
PRIMARY KEY (Id)
)
CREATE TABLE TeamGroups
(
Id int NOT NULL,
TeamId int NOT NULL,
PRIMARY KEY (Id,TeamId)
)
CREATE TABLE RoomBookings
(
Id int NOT NULL,
TeamGroupId int NOT NULL,
RoomId int NOT NULL,
PRIMARY KEY (Id)
)
and I have the following foreign key already set up:
ALTER TABLE TeamGroups WITH CHECK
ADD CONSTRAINT [FK_TeamGroups_Teams]
FOREIGN KEY (TeamId) REFERENCES Teams(Id)
The idea is that each Team can be in zero or more TeamGroups, and each TeamGroup can have zero or more RoomBookings
To reflect that, I want to add a foreign key from the RoomBookings table into the TeamGroups table.
I tried using the Relationships GUI in Management Studio to create the foreign key (primary key table: TeamGroups.ID, foreign key table: RoomBookings.TeamGroupId) but I get an error:
The columns in table 'TeamGroups' do not match an existing primary key
or UNIQUE constraint
I'm assuming it's because the TeamGroups table has a two-column primary key?
I don't really want to make a foreign key constraint from the TeamGroups table (eg, the key is present in the TeamGroups table), as the table will eventually be used by other tables (such as EquipmentBookings, GroupManagers, etc).
Any help?
If your primary key is made up from more than one columns, then all foregin keys also must have all those columns - there's no way around this.
But I don't understand why you'd get this error trying to link TeamGroups to Team based on the Team.Id column.... that should work just fine.
Try using this:
ALTER TABLE TeamGroups WITH CHECK
ADD CONSTRAINT [FK_TeamGroups_Teams]
FOREIGN KEY (TeamId) REFERENCES Teams(Id);
You had Teams (which is not a valid column in TeamGroups at all), and you had REFERENCES Teams.id which is wrong - it needs to be REFERNCES Teams(Id); (column in parenthesis - not the "dot" notation)
Update: from TeamGroups to RoomBookings - yes.... either use both columns from TeamGroups in your RoomBookings table - or what would stop you from making the TeamGroups.Id column an INT IDENTITY and then have the PK on just this one column?? Any good reason for that??
CREATE TABLE TeamGroups
(
TeamGroupId int NOT NULL,
TeamId int NOT NULL,
PRIMARY KEY (TeamGroupId)
)
ALTER TABLE dbo.RoomBookings
ADD CONSTRAINT FK_RoomBookings_TeamGroup
FOREIGN KEY TeamGroupId REFERENCES TeamGroups(TeamGroupId)

How to create database schema with shared primary foreign key?

My goal is to have a subtable whose primary key and foreign key both are the same column, and reference to an ID of the main table.
CREATE TABLE main_table(
id integer NOT NULL,
//some fields
)
CREATE TABLE test(
id integer NOT NULL,
name varchar,
CONSTRAINT test_pk PRIMARAY KEY (id),
CONSTRAINT test_fk FOREIGN KEY (fk_id)
REFERENCES main_table (id) MATCH SIMPLE
)
But this will create a table mapping with two columns: id[PK] and test_fk as foreign key column. How can I combine them?
You have misunderstood how the foreign key clause works. You list the names of existing columns in there. And listing the column names will create any new column. Any FK column must have already be defined in the "columns part" of the create table statement.
So your statement wouldn't work at all because the table test does not have a column named fk_id. You need to supply the name of the already defined column id there:
CREATE TABLE test(
id integer NOT NULL,
name varchar,
CONSTRAINT test_pk PRIMARAY KEY (id),
CONSTRAINT test_fk FOREIGN KEY (id) --- <<< this was wrong
REFERENCES main_table (id) MATCH SIMPLE
)

two primary key fields for a column in ms-sql

I have a table with the following fields:
searchID ( I have set this as a primary key )
SearchText nvarchar(MAX)
.......
and so on
I want to make SearchText also as an additional primary field. How should this be done? Is that a good procedure to make two primary columns for a table?
It's impossible to have more than one primary key on one table and store unique values.
Your primary key must be as short as possible.
If you need to keep unique data in other column, you can create unique key on this column:
CREATE TABLE dbo.Table
(
SearchText nvarchar(MAX)NOT NULL,
CONSTRAINT AK_SearchText UNIQUE(SearchText)
);
Or with management studio:
You can create composite key as below
create table myTable
(
SearchId int not null,
SearchText nvharchar not null
)
GO
-- Add Constraint
ALTER TABLE myTable
ADD CONSTRAINT pk_myConstraint PRIMARY KEY (SearchId ,SearchText)
GO

Resources