V
V
Vitaly Rybchenko2016-11-25 14:44:36
SQL Server
Vitaly Rybchenko, 2016-11-25 14:44:36

How to properly organize indexes?

Good day everyone!
I read the documentation, but I don’t fully understand whether I did it right or not, and whether something else can be done.
There is a table:

CREATE TABLE [Application].[PA] (
  [Id] [int] IDENTITY(1,1) NOT NULL,
  [CRId] [int] NOT NULL,
  [AGId] [int] NOT NULL,
  [PPId] [int] NOT NULL,
 CONSTRAINT [PK_PA] PRIMARY KEY CLUSTERED 
([Id] ASC) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
ALTER TABLE [Application].[PA]  WITH CHECK ADD  CONSTRAINT [FK_PA_PAG] FOREIGN KEY([AGId])
REFERENCES [Application].[PAG] ([Id])
GO
ALTER TABLE [Application].[PA] CHECK CONSTRAINT [FK_PA_PAG]
GO
ALTER TABLE [Application].[PA]  WITH CHECK ADD  CONSTRAINT [FK_PA_PP] FOREIGN KEY([PPId])
REFERENCES [Application].[PP] ([Id])
GO
ALTER TABLE [Application].[PA] CHECK CONSTRAINT [FK_PA_PP]
GO

She has a non-clustered index
CREATE NONCLUSTERED INDEX [PA_NC_Index] ON [Application].[PA]
(
  [AGId] ASC,
  [PPId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO

[CRId] are the records that you eventually need to get in order to understand which rows to select from another table; [ AGId
] - main object, unique
[PPId] - additional object within the main one, but unique between main objects
select [CRId] from [Application].[PA] where [PA].[AGId]=1 and [PA].[PPId]=21

There are more than 1 million records in the table, and the question begins to worry - are storage and sampling organized correctly? Or can something be changed/improved?
If we make a connection to this table, then we immediately get strong brakes (2 sec, direct sampling - 0.02 sec), for example
select top(10) Id 
from [Application].T inner join
[Application].[PA] on T.id=PA.[CRId]
where [PA].[AGId]=1 and [PA].[PPId]=21

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Lebedev, 2016-11-25
@swanrnd

Try this:
Key on [PA].[AGId] + [PA].[PPId] (unique cluster)
Key [Application].id. (unique cluster)
Make 2 queries:
select [CRId] from [Application].[PA] where [PA].[AGId]=1 and [PA].[PPId]=21
select [CRId] from [Application].[ T] where id IN (received ids in the query before)
Sometimes JOIN should be abandoned.
But first you need to decide what exactly slows down.
It is possible still with the request plan, of course.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question