- How do I do a COUNTIF or SUMIF in SQL?
- Ask in plain English — 'how many paid orders, and total revenue from them.' nlqdb compiles the conditional aggregate (`COUNT(*) FILTER (WHERE status = 'paid')`, `SUM(amount) FILTER (WHERE status = 'paid')`), runs it in Postgres, and returns the numbers plus the SQL it ran. You get the COUNTIF/SUMIF without hand-writing a CASE expression per metric. The honest limit: you have to name the condition.
- Why does COUNT(status = 'paid') count everything instead of just the paid rows?
- Because `COUNT(x)` counts non-null values, not true results — `status = 'paid'` is non-null (either true or false) on every row, so it counts them all. The fixes are `COUNT(*) FILTER (WHERE status = 'paid')` or `SUM(CASE WHEN status = 'paid' THEN 1 ELSE 0 END)`. nlqdb compiles the FILTER form and shows the SQL, so this over-counting trap can't slip through silently.
- What's the difference between COUNT(*) FILTER (WHERE ...) and SUM(CASE WHEN ...)?
- They compute the same conditional count. `COUNT(*) FILTER (WHERE cond)` is the SQL-standard, readable form (Postgres, SQLite 3.30+); `SUM(CASE WHEN cond THEN 1 ELSE 0 END)` is the portable fallback for engines without FILTER, like MySQL. nlqdb runs on Postgres and compiles the FILTER form, then shows the SQL — paste it, or swap in the CASE version for another engine.
- Can I get several conditional counts — paid, refunded, pending — in one query?
- Yes. Ask for 'counts of paid, refunded, and pending orders' and nlqdb writes one query with a filtered aggregate per bucket — `COUNT(*) FILTER (WHERE status = 'paid')` as one column, repeated per status — so the table is scanned once, not once per metric. It's the same conditional-aggregation pattern a pivot uses; the SQL shows under the trace toggle.
- Can I do a conditional sum (SUMIF) on a Postgres database I already run?
- Yes — connect it with the signed-in BYO connect verb (see /solve/query-existing-postgres-in-natural-language) and ask for the conditional total in place, no ETL into a separate store. The honest limits: BYO connect is signed-in only (not the public embed), and nlqdb returns the SUMIF with a read-only query — it doesn't persist a materialized conditional column for you.