DROP TABLE IF EXISTS ProductZeroPurchasesByProvince; CREATE TABLE ProductZeroPurchasesByProvince AS SELECT c.name AS CountryName, pro.name AS ProvinceName, COUNT(pro.name) AS cnt FROM Purchases pur JOIN Province pro ON pur.product = 0 AND pur.province = pro.rowid JOIN Country c ON pro.country = c.code GROUP BY c.code, pro.name; DROP INDEX IF EXISTS Time_index; CREATE INDEX Time_index ON Purchases(time,province,product,qty);