Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding index to a table

I have a table Person: id, name

I often have queries like:

select * from Person where name Like "%abc%".

I have 2 questions:

  1. How do I implement this query using code-first 5 (CTP5)
  2. How do I add an index on the name column to make data retrieval faster based on name like in the query?
like image 571
Ryan Avatar asked Feb 18 '11 11:02

Ryan


People also ask

How do I add an index to an existing table?

The following code block is an example to add index in an existing table. mysql> ALTER TABLE testalter_tbl ADD INDEX (c); You can drop any INDEX by using the DROP clause along with the ALTER command. Try out the following example to drop the above-created index.

What does adding an index to a table do?

What is indexing? Indexing is a way of sorting a number of records on multiple fields. Creating an index on a field in a table creates another data structure which holds the field value, and a pointer to the record it relates to. This index structure is then sorted, allowing Binary Searches to be performed on it.

Can we CREATE INDEX on table?

The CREATE INDEX statement is used to create indexes in tables. Indexes are used to retrieve data from the database more quickly than otherwise. The users cannot see the indexes, they are just used to speed up searches/queries.

How do you add indexes?

Click where you want to add the index. On the References tab, in the Index group, click Insert Index. In the Index dialog box, you can choose the format for text entries, page numbers, tabs, and leader characters.


2 Answers

in EF 6 you can create indexes like this

   Property(t => t.TotalValue)
            .HasColumnAnnotation(
                IndexAnnotation.AnnotationName,
                new IndexAnnotation(new IndexAttribute("IX_inventory_import_total_value", 1))
            );
like image 188
Serghei Avatar answered Oct 13 '22 09:10

Serghei


Like operator can be performed with Contains function:

var query = from p in context.Persons
            where p.Name.Contains("abc")
            select p;

Index must be added by SQL - there is no special construction in EF to create index. You can execute this SQL from DB initialization.

First you must implement custom initializer:

public class MyInitializer : CreateDatabaseIfNotExists<MyContext>
{
  protected override void Seed(MyContext context)
  {
    context.Database.SqlCommand("CREATE INDEX IX_Person_Name ON Person (Name)");
  }
}

Then you must register new initializer:

DbDatabase.SetInitializer<MyContext>(new MyInitializer());
like image 36
Ladislav Mrnka Avatar answered Oct 13 '22 11:10

Ladislav Mrnka