Вопрос

I would like to know if there are any performance related ups and downs for tables that has a primary key and those without primary key.

I have a schema with two tables.

Table Without ID

create_table "site_page_views", :id => false, :force => true do |t|
  t.integer "site_id"
  t.integer "page_id"
  t.integer "visit_count", :default => 0, :null => false
  t.date    "start_date"
  t.date    "end_date"
end

add_index "site_page_views", ["end_date"], :name => "index_site_page_views_on_end_date"
add_index "site_page_views", ["site_id"], :name => "index_site_page_views_on_site_id"
add_index "site_page_views", ["start_date", "end_date"], :name => "index_site_page_views_on_start_date_and_end_date"
add_index "site_page_views", ["start_date"], :name => "index_site_page_views_on_start_date"

Table With ID

create_table "content_views", :force => true do |t|
  t.integer "site_id"
  t.integer "page_id"
  t.integer "visit_count", :default => 0, :null => false
  t.string  "type"
  t.date    "start_date"
  t.date    "end_date"
end

add_index "content_views", ["page_id"], :name => "index_content_views_on_page_id"
add_index "content_views", ["site_id"], :name => "index_content_views_on_site_id"
add_index "content_views", ["start_date", "end_date"], :name => "index_content_views_on_start_date_and_end_date"
add_index "content_views", ["type"], :name => "index_content_views_on_type"

If you have a look at the second table it represents a STI(Single Table Inheritance)

I have similar data in both tables(this is just a curious testing), when I query for records to get records between date ranges. I get following benchmark results

puts 'No primary Key :' Benchmark.bm do |b|
  b.report {
    SitePageView.where(site_id: 123,
      start_date: start_date,
      end_date: end_date).includes(:page)
    .order('visit_count DESC').limit(100).all }.real * 1000
end

=> No primay key : 176 ms


puts 'With primary Key :' Benchmark.bm do |b|
  b.report {
    StiPageViews.where(site_id: 123,
      start_date: start_date,
      end_date: end_date).includes(:page)
    .order('visit_count DESC').limit(100).all }.real * 1000
end

=> With primay key : 101 ms

What would be the reason for the slowness of table without primary key ?

Это было полезно?

Решение

Primary key has auto index. You no need to manually index the primary key.

But, your Query doesn't use primary key column.

So, there should not be any differences in performance.

Better check the query execution time in postgres aswell.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top