#sql
SQL queries, schema design, indexes and query plans across databases.
Posts tagged #sql
My grandson and I built a weather station on the terrace. He wrote the Python, I wrote the SQL, and the rain did the rest.
Dear friends, Some of you have read my long stories about the bank. This one is shorter, and happier, and I hope you will forgive an old man for being a little proud. My grandson Vignesh is fourteen. He lives with us in Chennai while his parents work in Bengaluru, and for most of last year our relationship consisted of me asking him to put his phone down and him explaining to me, very patiently, that Python is…
Daily sales report across timezones: which day does an order at 11:30pm Bangkok belong to?
We store created_at as timestamptz. Until now all markets were UTC+8 (Singapore, Malaysia) so we just did: select (created_at at time zone 'Asia/Singapore')::date as day, sum(amount) from orders group by 1; Now we add Thailand (UTC+7). Order at 23:30 Bangkok time is 00:30 next day in Singapore. Thai team want it in their day, regional report want one number per day. Options: convert each order using its market…
Teaching SQL joins to Class 12 with the attendance register and the fee register
Every year my Class 12 children memorise "INNER JOIN returns only matching rows" for the exam, write it perfectly, and understand nothing. This year I tried something different and it worked better than I expected, so I am sharing. I borrowed two real registers from the office: the attendance register (roll number, name) and the fee register (roll number, term, amount). I asked the children: "Who has paid fees, with…
Reconciliation without losing your mind: matching ledger, gateway and bank
If you move money, at some point finance will ask "does our ledger match the bank". The honest answer at most startups is "mostly". This post is how we went from "mostly" to a daily report that finance actually trusts. It took us around 4 months, so dont feel bad if yours is still a spreadsheet. Three sources, not two For card and UPI payments you have three views of the same money: Your ledger: what you think…
Pandera, Great Expectations or plain asserts for data validation in a small team?
Hola! Small data team (3 people), Python, pandas, some dbt, Airflow. We have zero data validation, and last month a supplier changed a column from euros to cents without telling anybody. Our revenue dashboard showed 100x for two days 🙃 Nobody noticed until the CFO was very happy, and then very angry. I want to add validation at the ingestion step. The options I see: pandera : schemas in Python, looks light. Great…
latest row per customer without a correlated subquery that takes 40 minutes?
doing a take-home for a data engineering role (job hunt day 187, grand, all grand). table is basically: customer_events ( id bigint primary key, customer_id bigint, event_type text, payload jsonb, created_at timestamptz ) about 120M rows in their description, i've a 5M sample locally. they want the latest event per customer. my first go: SELECT e.* FROM customer_events e WHERE e.created_at = ( SELECT MAX(created_at)…
the AI wrote me a running total that was 'almost right'. almost right is the worst kind
ok quick one because this bit me today and i want to save someone an afternoon. asked an ai assistant for a running total of revenue. it gave me this, which looks totally fine: SELECT order_date, amount, SUM(amount) OVER (ORDER BY order_date) AS running_total FROM orders; ran it, numbers looked plausible, almost shipped it to the dashboard. then i noticed the running total jumped by the same amount on every row with…
Postgres count(distinct) on 80M rows very slow, any trick?
Daily active customers query take ~40s, dashboard timeout: select date_trunc('day', created_at) as day, count(distinct customer_id) from orders where created_at >= now() - interval '90 days' group by 1 order by 1; Table ~80M rows, index on created_at. Postgres 15. EXPLAIN show big Sort spilling to disk. Tried increase work_mem to 256MB, bit faster but still 25s. Is count(distinct) just slow in Postgres? Thinking to…
dbt incremental model getting duplicate rows when late data arrive, how to fix?
Using dbt on BigQuery. Orders model is incremental, source table get updated when order status change (paid, shipped, refunded). Model look like this: {{ config(materialized='incremental') }} select order_id, status, amount, updated_at from {{ source('shop', 'orders') }} {% if is_incremental() %} where updated_at > (select max(updated_at) from {{ this }}) {% endif %} Problem 1: same order_id appear multiple times…
boss wants 'chat with your data' by Q4. anyone actually running LLM-to-SQL for business users?
hi all. data analyst kat a bank in KL. my boss went to a vendor event and now he wants "chat with your data" for the business users by Q4 lah. type a question in English or Malay, get the answer from our warehouse. sounds very nice on the slide. my worries, maybe I am overthinking: our schema has 600+ tables, column names like TXN_AMT_2 and CUST_FLG_X . even humans don't know what they mean. "revenue" means 3…
What is your main production database? No 'it depends', pick one.
The SELECT * that stopped month-end at our bank, and the change ticket that saved me
Friends, a story from month-end, because I am telling you, every bank sysadmin has one of these and mine finally has a happy ending. Last day of the month, 11.40 pm. Our core banking batch on Oracle runs interest, fees, GL postings, and at the end the ATM and card settlement files for the switch. The batch window is tight. At 11.52 pm the batch stopped moving. Monitoring showed the TEMP tablespace at 100% and the…
The index that made our query slower, and other things EXPLAIN ANALYZE told me
Short version: someone added an index "because we order by that column", and the dispatcher dashboard went from 40 ms to 9 seconds for our smallest depots. The someone was me. I found out on the bike home, which is 14 km, which is enough time to stop being angry at yourself. The query SELECT id, reference, created_at FROM shipments WHERE depot_id = 42 AND status = 'pending' ORDER BY created_at DESC LIMIT 50;…