Skip to content

SELECT * Anonymous

Databases and SQL: queries, indexes and query plans

t/select-star-anonymous

Databases, query plans and the index you forgot. Postgres mostly, everything else welcome.

30 members
10 posts
Created Aug 2026
+2

Community rules

3 rules for t/select-star-anonymous

  1. Bring the EXPLAIN ANALYZE

    The plan answers most questions before anyone has to guess.

  2. Bring the detail

    Versions, error text, what you already tried. "It does not work" is not a question anyone can answer.

  3. No drive-by self promotion

    Share your own work when it answers the thread. A link with no context is a advert, and it gets removed.

Discussions

1

Showing 10 posts.

Posts in t/select-star-anonymous

10

  • Diolch Anitha, this is tidy. I do something similar with the register and the dinner money list. The transferred student is a brilliant way to get to data quality. Small task for anyone reading: write the query that finds fee rows with no matching student. Answers below 😄
    1 reply
  • Respected Anitha madam, this is wonderful. I am a maths teacher just starting Python and SQL with Class 9 and 10. May I use the fee register example in my class? Farhan appearing two times is a very good way to explain one-to-many. Thanking you.
    1 reply
10

  • Accepted answer

    ok this one I do every week lah. three ways: 1. postgres only, shortest: SELECT DISTINCT ON (customer_id) id, customer_id, event_type, payload, created_at FROM customer_events ORDER BY customer_id, created_at DESC, id DESC; DISTINCT ON keeps the first row per customer_id according to the ORDER BY. id DESC breaks the tie when created_at is same. 2. portable, works in SQL Server, Oracle, MySQL 8, Snowflake etc: SELECT id, customer_id, event_type, payload, created_at FROM ( SELECT e.*, ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY created_at DESC, id DESC) AS rn FROM customer_events e ) t WHERE rn = 1; ROW_NUMBER not RANK, because RANK gives 2 rows when tie. confirm they will ask this in the follow-up. 3. when there are few customers and very many events each, LATERAL with LIMIT 1 can be fastest, it jumps into the index once per customer: SELECT c.id, last.* FROM customers c CROSS JOIN LATERAL ( SELECT e.id, e.event_type, e.payload, e.created_at FROM customer_events e WHERE e.customer_id = c.id ORDER BY e.created_at DESC, e.id DESC LIMIT 1 ) last; for all three the index is: CREATE INDEX ON customer_events (customer_id, created_at DESC, id DESC); and since we are in select-star-anonymous: list the columns in your submission, the reviewer will notice 😄
    1 reply
  • not my area but sent you another lead aoife, data eng contract in Leeds, remote mostly. they're on Postgres so you're sorted after this
    1 reply