                         {:as-arrays? true}))
      :columns columns}))
 
+(defn apply-empty-query [conn dataset filter-str]
+  (let [count (rest (jdbc/query conn
+                                [(format "SELECT count(rnum) FROM %s WHERE %s"
+                                         (:table-name dataset)
+                                         filter-str)]
+                                {:as-arrays? true}))]
+    {:columns [{"type" "number"
+                "title" "Total"}]
+     :rows count}))
+
+(defn apply-empty-category-query [conn dataset query filter-str]
+  {:rows []
+   :columns []})
+
+(defn apply-empty-row-query [conn dataset query filter-str]
+  {:rows []
+   :columns []})
+
+(defn apply-empty-value-query [conn dataset query filter-str]
+  {:rows []
+   :columns []})
+
+(defn apply-query [conn dataset query filter-str]
+  (cond
+    (and (nil? (:row-column query))
+         (nil? (:category-column query)))
+    (apply-empty-query conn dataset filter-str)
+    (nil? (:category-column query))
+    (apply-empty-category-query conn dataset query filter-str)
+    (nil? (:row-column query))
+    (apply-empty-row-query conn dataset query filter-str)
+    (nil? (:value-column query))
+    (apply-empty-value-query conn dataset query filter-str)
+    :else (apply-pivot conn dataset query filter-str)))
+
 (defn find-column [columns column-name]
-  (first (filter #(= column-name (get % "columnName"))
-                 columns)))
+  (first (filter #(= column-name (get % "columnName")) columns)))
 
 (defn build-query
   "Replace column names with proper column metadata from the dataset"

  (def q {"categoryColumn" "c16"
          "rowColumn" "c4"
          "valueColumn" "c19"
          "aggregation" "avg"})

  (run-query tenant-conn dataset {:category-column (second (:columns dataset))})

  (query tenant-conn dataset-id q)

  (unique-categories tenant-conn dataset-id)


                          (range categories-count)))
       ");"))

(defn apply-pivot [conn dataset query filter-str]
  (let [categories (unique-values conn
                                  (:table-name dataset)
                                  (:category-column query)
