Drop Default Clustered Index Without Knowing it's Name - sql

I wrote a script that creates some tables (it previously drops them if they exist) and then tries to create two indexes on each table.
The first index uses the Primary Key column to create a non-clustered index, and the second uses another column to create the clustered indexed. This is because the primary key column is a GUID instead of an int.
How can I drop the default index if I don't know it's name? or how can I specify a name for the primary key column index so I can drop it? Or better yet, how can I specify the 2 index i need right in the Create Table statement?

SELECT * FROM sys.indexes
However, I'm not understanding where in your process you actually have to drop an index.
You said you are creating some tables and then creating two indexes on each table.
If you are DROPping existing tables at the beginning, any indexes are automatically dropped.
There is no such thing as a default index.
Tables can either be heaps or clustered indexes. If you drop the clustered index, the table will be converted to a heap and any non-clustered indexes will have to be updated to point to the data in the unordered heap.
You can create like this all at once:
CREATE TABLE dbo.tbl
(
Id int NOT NULL IDENTITY (1, 1) CONSTRAINT UK_ID UNIQUE CLUSTERED,
SomeUUID UNIQUEIDENTIFIER NOT NULL CONSTRAINT PK_SomeUUID PRIMARY KEY NONCLUSTERED
)
Here's a SQLFiddle: http://sqlfiddle.com/#!6/d759e/12

You can define the two indices right after you create the table:
CREATE TABLE dbo.YourTable ( ...... )
GO
ALTER TABLE dbo.YourTable
ADD CONSTRAINT PK_YourTable PRIMARY KEY NONCLUSTERED (YourGuidColumn)
****************
this is crucial ! Otherwise, your PK will be clustered!
CREATE CLUSTERED INDEX IX01_YourTable ON dbo.YourTable(YourOtherColumn)
or even better:
CREATE UNIQUE CLUSTERED INDEX IX01_YourTable ON dbo.YourTable(YourOtherColumn)
That should create a non-clustered primary key and a separate (preferably unique) clustered index on a separate column.

Related

Replace the default clustered index with a non-primary/non-key attribute

I have a request to replace the default clustered index with a non-primary attribute and I have an idea of how to simply drop an index and just make another one but I have no clue how to replace the default clustered index.
This is as far as I got.
CREATE INDEX newCustomerIndex ON CustomerInfo(fullname, homeAddress);
DROP INDEX CustomerInfo.PK__Customer__B611CB9D24135D51
However whenever I execute this piece of code I get this error
An explicit DROP INDEX is not allowed on index 'CustomerInfo.PK__Customer__B611CB9D24135D51'. It is being used for PRIMARY KEY constraint enforcement.
There are definitely times when you want the Clustered Index to be separate from the Primary Key - particularly when you search in 'ranges'.
For example, on log tables, I'll frequently have the primary key as an Identity (auto-incrementing) integer so each row is uniquely identified, but I'll put the clustered index on the date/time stamp field. This is because most of the reads etc will be within a date range and therefore the clustered index can be used directly. However, you cannot guarantee each date/time stamp is unique so you cannot use it as a primary key - and you can only have 1 clustered index on a table.
Note that the below is based on SQL Server - as per your tags. However, I'm not sure if the fields you are referring to are the current PK, or the ones you want to have as your clustered index. Therefore, I'll write this for a fictional table called 'dbo.Temp' with 'Auto_Id' and 'Log_datetime'.
I assume you already have the primary key which is also the clustered index. The typical process is as follows.
DROP and CREATE the current primary key, but as a non-clustered index rather than clustered
Create your new clustered index
However, you will also need a preceding and following step - identifying and managing the foreign key constraints. I'll get to this last.
To do step 1, I will usually open the table on the left (object explorer), open 'Indexes', then right-click on the index and script index -> 'DROP and CREATE to
This gives some code similar to the following
ALTER TABLE [dbo].[Temp] DROP CONSTRAINT [PK_Temp] WITH ( ONLINE = OFF )
GO
ALTER TABLE [dbo].[Temp] ADD CONSTRAINT [PK_Temp] PRIMARY KEY CLUSTERED
(
[Auto_ID] ASC
)
GO
I make one change to this before starting - change the new constraint to be NONCLUSTERED rather than clustered e.g.,
ALTER TABLE [dbo].[Temp] DROP CONSTRAINT [PK_Temp] WITH ( ONLINE = OFF )
GO
ALTER TABLE [dbo].[Temp] ADD CONSTRAINT [PK_Temp] PRIMARY KEY NONCLUSTERED -- modified here
(
[Auto_ID] ASC
)
GO
I then add my create index statement to create the index e.g.,
CREATE CLUSTERED INDEX CX_Temp ON dbo.Temp ([Log_Datetime], [Auto_ID])
GO
And then run.
Sometimes this won't work - especially when the index is being used for foreign key constraints (e.g., another table has a foreign link to this table/current PK) - therefore you cannot drop the PK, nor any of the following steps.
Therefore you need to find the relevant foreign key constraint. Once found (which can be annoying), I then usually do a similar thing to script the index deletion and re-creation (right-click on the foreign key, script it as 'DROP and CREATE to').
You then copy the first part (dropping the foreign key) before the script above, add the re-creating of the foreign key to the end. This therefore
disables the foreign key constraint
deletes/recreates the primary key as a non-clustered index
creates the new clustered index
recreates the foreign key constraint

Using Index versus Create Index in oracle

I am creating a table with following script (I used Using index).
CREATE TABLE TABLE1 (
C1 VARCHAR2(2 CHAR) NOT NULL ENABLE,
C2 VARCHAR2(1 CHAR) NOT NULL ENABLE,
CONSTRAINT TABLE_PK PRIMARY KEY (C1) USING INDEX TABLESPACE SFE_I1
)
TABLESPACE SFE_D1;
In the above query index will create for what column?
CREATE INDEX IDX_TABLE ON TABLE1 (C1) TABLESPACE SFE_I1;
If I am creating index with the above create index query, it will create index for C1 column. But what is the difference between to this two scripts.
As well if I run both this query, what should happen. And what is the suggested way to do this?
If my create table script contains composite primary key and i am using USING INDEX keyword then how index will be created (will it create a single index for all the composite columns)
The important part of the create table statement, for this question, is the CONSTRAINT TABLE_PK PRIMARY KEY (C1) USING INDEX TABLESPACE SFE_I1. Let's break it down and understand it:
CONSTRAINT TABLE_PK
You're creating a constraint named table_pk.
PRIMARY KEY
This constraint is a primary key
(C1)
On the column c1
USING INDEX TABLESPACE SFE_I1
A primary key, implicitly needs to create an index so it can efficiently search for duplicates that would violate the constraint. Like with explicitly created indexes (e.g., your second statement), the index would be created on the user's default tablespace, which isn't always the best idea. The using index tablespace syntax allows you do define which tablespace to use, in the same way you can use it when creating an index.
If you attempt to run both statements the second one should fail, since c1 is already indexed by the first one.

Set identity off in azure sql table

I have a table which includes an identity column but i cant remove the identity property.
Is there a way to disable it? Or a way to make a copy of the entire table without identity property?
Note that you may not be able to drop the column if it referenced by a clustered index, and you can't drop all clustered indexes for a table because SqlAzure tables must always have a clustered index.
This means that you may have to jump through the following hoops (for at least your last clustered index, which may well be your primary key):
rename your clustered index
create a temp version of the table (with a new clustered index)
copy the data from the current table
drop the current table
rename the temp table to the current name
This roughly looks like this:
-- Rename clustered index
EXECUTE sp_rename N'PK_My_Current_PK', N'PK_My_Current_PK_OLD', 'OBJECT'
-- If you have any FK constraints on the table, then drop them
ALTER TABLE dbo.MyTable DROP CONSTRAINT FK_My_Foreign_Key
-- Create the new version of your table - because this is SQLAzure it must have a clustered index
CREATE TABLE dbo.tmp_MyTable (
MyID int NOT NULL,
CONSTRAINT PK_My_Current_PK PRIMARY KEY CLUSTERED (MyID)
)
-- Copy the data into the temp table from the old table
INSERT INTO dbo.tmp_MyTable (MyID)
SELECT MyID FROM dbo.MyTable
-- Drop the old table
DROP TABLE dbo.MyTable
-- Rename the new table
EXECUTE sp_rename N'tmp_MyTable', N'MyTable', 'OBJECT'
-- Recreate any foreign key constraints
ALTER TABLE dbo.MyTable WITH CHECK ADD FK_My_Foreign_Key FOREIGN KEY (MyID)
REFERENCES dbo.MyForeignTable (MyID)
Hope that helps
A
Edit: As #PhilBolduc pointed out SqlAzure tables require a clustered index, not a primary key. I've amended the terminology above accordingly - the principle of the answer still remains.
You can not remove an Identity column without dropping it unfortunately. Alternetivly add a new column with a temp name, update the new column value and then drop the previous column.
ALTER TABLE dbo.tablename ADD newcolumnname INT
UPDATE dbo.tablename SET newcolumnname = oldcolumnname FROM dbo.tablename
ALTER TABLE dbo.tablename DROP COLUMN oldcolumnname
that should do it. unless i have misunderstood your questions?

Is the PK of a DB2 table a clustered index by default?

This can be a silly question but I want to be sure 100%.
Is the PK of a DB2 table a clustered index by default?
From: DB2 docs - Clustering indexes
Although a table can have several indexes, only one index can be a clustering index. If you do not define a clustering index for a table, DB2 recognizes the first index that is created on the table as the implicit clustering index when it orders data rows.
So no, by default the Primary Key is NOT the clustered index of the table.
The first created index, unique or not, is the "implicit" clustering index and DB2 tries to insert the records as nearly as possible in the order of the values of this index.
If you later create another index and identify it as clustering, then DB2 identifies it as the clustering index but does not rearrange the data that is already in the table. This can be done with the REORG utility.
From the Publib (this assumes DB2 for z/OS, version 9)
When a table has a clustering index, an INSERT statement causes DB2 to
insert the records as nearly as possible in the order of their index
values. The first index that you define on the table serves implicitly
as the clustering index unless you explicitly specify CLUSTER when you
create or alter another index. For example, if you first define a
unique index on the EMPNO column of the EMP table, DB2 inserts rows
into the EMP table in the order of the employee identification number
unless you explicitly define another index to be the clustering index.
You can see which index is the clustering index for a table (in this example, TEST.TABLE1) using the following query, if you're on z/OS:
SELECT NAME
FROM SYSIBM.SYSINDEXES
WHERE TBCREATOR = 'TEST'
AND TBNAME = 'TABLE1'
AND CLUSTERING = 'Y'
And this one for Linux/Unix/Windows (LUW):
SELECT *
FROM SYSCAT.INDEXES
WHERE TABSCHEMA = 'TEST'
AND TABNAME = 'TABLE1'
AND INDEXTYPE = 'CLUS'
DB2 doesn't create clustered index for a PK by default.
Primary keys
A primary key is a special type of unique key and cannot contain null values. For example, the DEPTNO column in the DEPT table is a primary key.
A table can have no more than one primary key. Primary keys are optional and can be defined in CREATE TABLE or ALTER TABLE statements.
The unique index on a primary key is called a primary index. When a primary key is defined in a CREATE TABLE statement or ALTER TABLE statement, DB2 automatically creates the primary index if one of the following conditions is true:
DB2 is operating in new-function mode, and the table space is implicitly created.
DB2 is operating in new-function mode, the table space is explicitly created, and the schema processor is running.
DB2 is operating in conversion mode, and the schema processor is running.
If a unique index already exists on the columns of the primary key when it is defined in the ALTER TABLE statement, this unique index is designated as the primary index when DB2 is operating in new-function mode and implicitly created the table space.
See at: Keys DB2

Does making a column unique force an index to be created?

In SQL Server 2005+ (I use both), does adding the UNIQUE constraint to a column automatically create an index, or should I still CREATE INDEX?
See this MSDN article:
The Database Engine automatically
creates a UNIQUE index to enforce the
uniqueness requirement of the UNIQUE
constraint.
If you do create an index, you'll end up with two indexes, as this example demonstrates:
create table TestTable (id int)
alter table TestTable add constraint unique_id unique (id)
create unique index ix_TestTable_id on TestTable (id)
select * from sys.indexes where [object_id] = object_id('TestTable')
This will display two unique indexes on TestTable; and the HEAP that represents the table itself.
Yes, it does.
In fact, you can even create a CLUSTERED UNIQUE CONSTRAINT:
ALTER TABLE mytable ADD CONSTRAINT UX_mytable_col1 UNIQUE CLUSTERED (col1)
, which will make the table to be clustered on col1.
Almost all databases create an index for UNIQUE CONSTRAINT, otherwise it would be very hard to maintain it.
Oracle doesn't even distinguish between UNIQUE CONSTRAINT and UNIQUE INDEX: one command is just a synonym for another.
The only difference in Oracle is that a UNIQUE INDEX should have a user-supplied name, while a UNIQUE CONSTRAINT may be created with a system-generated name:
ALTER TABLE mytable MODIFY col1 UNIQUE
This will create an index called SYS_CXXXXXX.
An index is created when you add a unique constraint:
Reference -- see the second paragraph.
When a UNIQUE constraint is added to
an existing column or columns in the
table, by default, the Database Engine
examines the existing data in the
columns to make sure all values are
unique. If a UNIQUE constraint is
added to a column that has duplicated
values, the Database Engine returns an
error and does not add the constraint.
The Database Engine automatically
creates a UNIQUE index to enforce the
uniqueness requirement of the UNIQUE
constraint. Therefore, if an attempt
to insert a duplicate row is made, the
Database Engine returns an error
message that states the UNIQUE
constraint has been violated and does
not add the row to the table. Unless a
clustered index is explicitly
specified, a unique, nonclustered
index is created by default to enforce
the UNIQUE constraint.