SQL Query continues running for a very long time if search term not found

后端 未结 2 2137
挽巷
挽巷 2020-12-20 06:18

In my Azure hosted ASP.NET Core site I have a table of users and I implemented search as follows:

    var inner = from user in db.Users
             select           


        
相关标签:
2条回答
  • 2020-12-20 06:43

    Already you can simplify your query like this ;) :

    int start=page * recordsInPage;
    
    var inner = (from user in db.Users
                where user.Name.Contains(name) && !user.Deleted && user.AppearInSearch
                orderby user.Verified descending
                select  new
                       {
                         Name = user.Name,
                         Verified = user.Verified,
                         PhotoURL = user.PhotoURL,
                         UserID = user.Id,
                         Subdomain = user.Subdomain,
                         Deleted=user.Deleted,
                         AppearInSearch = user.AppearInSearch
                       }
                 ).Skip(start).Take(recordsInPage);
    
    return await inner.ToListAsync();
    

    If you have a performance problem, try to create a stored procedure with your SQL and use it with entity Framework.

    0 讨论(0)
  • 2020-12-20 07:02

    SQL Server has to use a scan to find rows matching the .Contains clause. There is no way around this.

    However, if we reduce the amount of data that SQL server has to scan, we will speed up the query.

    Covering filtered index

    An index is "covering" if it contains all the data needed to be returned in a query.

    CREATE INDEX IX_User_Name_filtered ON USER ([Verified], [Name]) 
    INCLUDE ( [PhotoURL], [Id], [Subdomain], [Deleted], [AppearInSearch]  ) 
    WHERE [AppearInSearch]=1 AND [Deleted]=0
    

    This index is likely substantially smaller than the original table, so even if a scan is required, it will be quicker.

    Depending on the plan that is generated, this index may be a better choice. it doesn't include the extra columns and will be smaller still. Testing will be required to determine the best choice.

    CREATE INDEX IX_User_Name_filtered ON USER ([Verified], [Name]) 
    WHERE [AppearInSearch]=1 AND [Deleted]=0
    
    0 讨论(0)
提交回复
热议问题