简体   繁体   中英

SQL Server create clustered index on nvarchar column, enforce sorting

I want have a small table with two columns [Id] [bigint] and [Name] [nvarchar](63) . The column is used for tags and it will contain all tags that exist. I want to force an alphabetical sorting by the Name column so that a given tag is found more quickly.

Necessary points are:

  1. The Id is my primary key, I use it eg for foreign keys.
  2. The Name is unique as well.
  3. I want to sort by Name alphabetically.
  4. I need the SQL command for creating the constraints since I use scripts to create the table.

I know you can sort the table by using a clustered index, but I know that the table is not necessarily in that order.

My query looks like this but I don't understand how to create the clustered index on Name but still keep the Id as Primary Key:

IF NOT EXISTS (SELECT * FROM sys.objects 
               WHERE object_id = OBJECT_ID(N'[dbo].[Tags]') 
                 AND type in (N'U'))
BEGIN
    CREATE TABLE [dbo].[Tags] 
    (
        [Id] [bigint] IDENTITY(1,1) PRIMARY KEY NOT NULL,
        [Name]  [nvarchar](63) NOT NULL,

        CONSTRAINT AK_TagName UNIQUE(Name)
    )
END

Edit:

I decided to follow paparazzo's advice. So if you have the same problem make sure you read his answer as well.

You should NOT do what you want to do.

Let the Id identity be the clustered PK. It (under normal use) will not fragment.

A table has no natural order. You have to sort by to get an order. Yes data is typically presented in PK order but that is just a convenience the query optimizer may or may not use.

Just put a non clustered unique index on Name and sort by it in the select .

You really need bigint? That is a massive table.

You can specify that the Primary Key is NONCLUSTERED when declaring it as a constraint, you can then declare the Unique Key as being the CLUSTERED index.

CREATE TABLE [dbo].[Tags] (
    [Id]    [bigint] IDENTITY(1,1) NOT NULL,
    [Name]  [nvarchar](63) NOT NULL,
    CONSTRAINT PK_Tag PRIMARY KEY NONCLUSTERED (Id ASC),
    CONSTRAINT AK_TagName UNIQUE CLUSTERED (Name ASC)
);

Also specifying ASC or DESC after the Column name (within the key/index declaration) sets the index sort order. The default is usually ascending.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM