Skip to content

Instantly share code, notes, and snippets.

@gabidavila
Last active August 7, 2016 21:35
Show Gist options
  • Select an option

  • Save gabidavila/c97916fad037ae742344a79eec17a0ba to your computer and use it in GitHub Desktop.

Select an option

Save gabidavila/c97916fad037ae742344a79eec17a0ba to your computer and use it in GitHub Desktop.
-- POSTGRES --
select count(*) from ad;
-- 445000
-- EXPLAIN
-- "Aggregate (cost=11887.50..11887.51 rows=1 width=0)"
-- " -> Seq Scan on ad (cost=0.00..10775.00 rows=445000 width=0)"
select count(*) from ad where region_id_fk = 1988;
-- 30
-- 220ms
-- EXPLAIN
-- "Aggregate (cost=11887.58..11887.59 rows=1 width=0)"
-- " -> Seq Scan on ad (cost=0.00..11887.50 rows=32 width=0)"
-- " Filter: (region_id_fk = 1988)"
select count(*) from (select * from ad where region_id_fk = 1988) ads
-- 30
-- 264ms
-- EXPLAIN
-- "Aggregate (cost=11887.58..11887.59 rows=1 width=0)"
-- " -> Seq Scan on ad (cost=0.00..11887.50 rows=32 width=0)"
-- " Filter: (region_id_fk = 1988)"
-- MySQL --
use teste;
select * from ad limit 100;
select count(*) from ad;
-- 445000
-- 0.336s
-- EXPLAIN
-- id, select_type, table, type, possible_keys, key, key_len, ref, rows, Extra
-- 1, SIMPLE, ad, index, , PRIMARY, 4, , 443311, Using index
select count(*) from ad where region_id_fk = 1988;
-- 30
-- 0.351
-- EXPLAIN
-- # id, select_type, table, type, possible_keys, key, key_len, ref, rows, Extra
-- 1, SIMPLE, ad, ALL, , , , , 443311, Using where
select count(*) from (select * from ad where region_id_fk = 1988) ads;
-- 30
-- 0.971sec
-- EXPLAIN
-- id, select_type, table, type, possible_keys, key, key_len, ref, rows, Extra
-- 1, PRIMARY, <derived2>, ALL, , , , , 443311,
-- 2, DERIVED, ad, ALL, , , , , 443311, Using where
@gabidavila

Copy link
Copy Markdown
Author

What happens is the second option generates a materialised view:
screenshot 2016-08-07 18 13 22

While the first:
screenshot 2016-08-07 18 14 41

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment