I have a doubt about correct indexing. I use rails 3.2.13, using Posgresql behind. BTW, Probably more a relational databases/indexing question...
I have this table:
# Table name: exams
#
# id :integer not null, primary key
# cognomenome :string(255)
# matricola :string(255)
# corsolaurea :string(255)
# annoaccademico :string(255)
# blablabla
#
# Indexes
#
# index_exams_on_annoaccademico (annoaccademico)
# index_exams_on_cognomenome (cognomenome)
# index_exams_on_corsolaurea (corsolaurea)
# index_exams_on_matricola (matricola)
I'd like to query the thousands record table (the nymber of records increase every year linearly, say by 500 items evey years, i.e. 5000-6000 in ten years);
I have to make these kind of queries:
SELECT "exams".* FROM "exams" WHERE (upper(cognomenome) like '%GIORGIO%') ORDER BY annoaccademico desc, corsolaurea, cognomenome LIMIT 50 OFFSET 0
or that:
SELECT "exams".* FROM "exams" WHERE (matricola like '%8327483274%') ORDER BY annoaccademico desc, corsolaurea, cognomenome LIMIT 50 OFFSET 0
or that:
SELECT "exams".* FROM "exams" WHERE (annoaccademico = '2013') AND (upper(cognomenome) like '%GIORGIO%') ORDER BY annoaccademico desc, corsolaurea, cognomenome LIMIT 50 OFFSET 0
or that:
SELECT "exams".* FROM "exams" WHERE (corsolaurea = 'Infermieristica') AND (upper(cognomenome) like
'%GIORGIO%') ORDER BY annoaccademico desc, corsolaurea, cognomenome LIMIT 50 OFFSET 0
or that:
SELECT "exams".* FROM "exams" WHERE (corsolaurea = 'Medicina-Anatomia I' and annoaccademico = '2013') AND (upper(cognomenome) like '%GIORGIO%') ORDER BY annoaccademico desc, corsolaurea, cognomenome LIMIT 50 OFFSET 0
In few words, I query the table using some AND combination of columns annoaccademico corsolaurea cognomenome matricola
always I have to order by columns: annoaccademico desc corsolaurea cognomenome
My questions:
1) considering the table size, do you suggest anyway to use indexes ? 2) As showed I already set indexes on single columns; that's correct ? 3) Probably I need to add two multicolumn index like:
add_index :exams, [:annoaccademico, :corsolaurea, :cognomenome]
add_index :exams, [:annoaccademico, :corsolaurea, :matricola]
that's right ?
What is not very clear to me is the point: Apart select conditions, Are indexes useful also for the order by clause ?
Thanks a lot for your patience / my db/sql ingnorance. giorgio solyaris.altervista.org
explain analyze select ...). Add inddexes you think might help, then check the execution plan again. For a good introduction on how indexes work see here: use-the-index-luke.com