#separator:tab
#html:true
#columns:Front	Back	Tags	GUID
#tags column:3
#guid column:4
#notetype:Basic
#deck:Live Coding Map
"How do you filter one calendar month on a timestamp column?"	"<p>A half-open interval: <code>ts &gt;= TIMESTAMP '2026-08-01' AND ts &lt; TIMESTAMP '2026-09-01'</code>. The start is included, the end is not.</p><p>Not <code>BETWEEN '2026-08-01' AND '2026-08-31'</code>: it ends at 00:00 on 31 August and loses the rest of that day.</p><p><a href=""https://butyavk.github.io/live-coding/sql/filters-and-dates/"">Read more on the site</a></p>"	"live-coding lcm::sql"	"lcm-en-sql-half-open-month"
"How do you show the month of a timestamp as a column?"	"<p><code>CAST(date_trunc('month', ts) AS DATE)</code>: the first day of the month, as a date.</p><p><code>date_trunc</code> always returns a timestamp; from a <code>DATE</code> it even returns <code>timestamp with time zone</code>. <code>EXTRACT(MONTH FROM ts)</code> gives only the number 1–12 and merges the same month of different years.</p><p><a href=""https://butyavk.github.io/live-coding/sql/filters-and-dates/"">Read more on the site</a></p>"	"live-coding lcm::sql"	"lcm-en-sql-month-column"
"The task says &quot;the last 30 days&quot;. How do you write &quot;today&quot;?"	"<p>Ask first: interview data is usually frozen. Then write a fixed, typed literal, never <code>NOW()</code>:</p><p><code>start_time &gt;= TIMESTAMP '2026-09-30' - INTERVAL '30 days' AND start_time &lt; TIMESTAMP '2026-09-30'</code></p><p>With <code>NOW()</code> the window slides into days with no data, and the answer changes every day.</p><p><a href=""https://butyavk.github.io/live-coding/sql/filters-and-dates/"">Read more on the site</a></p>"	"live-coding lcm::sql"	"lcm-en-sql-today-literal"
"In what order does SQL process the clauses of a query, and what follows from it?"	"<p><strong>FROM → JOIN → WHERE → GROUP BY → HAVING → SELECT → ORDER BY → LIMIT</strong></p><ul><li><code>WHERE</code> cannot see a <code>SELECT</code> alias; in PostgreSQL <code>HAVING</code> cannot either. Repeat the expression or use a CTE.</li><li>Window functions are computed in <code>SELECT</code>, so they cannot go in <code>WHERE</code>: filter them outside a CTE.</li><li><code>ORDER BY</code> runs last, so it can use an alias.</li></ul><p><a href=""https://butyavk.github.io/live-coding/sql/grouping-and-counting/"">Read more on the site</a></p>"	"live-coding lcm::sql"	"lcm-en-sql-order-of-execution"
"<code>COUNT(*)</code>, <code>COUNT(col)</code>, <code>COUNT(DISTINCT col)</code>: what does each count?"	"<ul><li><code>COUNT(*)</code>: rows.</li><li><code>COUNT(col)</code>: rows where <code>col</code> is not <code>NULL</code>.</li><li><code>COUNT(DISTINCT col)</code>: different values.</li></ul><p>Transactions without test purchases: 8032 rows, 180 with <code>refunded_at</code>, 4 channels. After a <code>LEFT JOIN</code>, count a column of the right table, or every X without a match counts as 1.</p><p><a href=""https://butyavk.github.io/live-coding/sql/grouping-and-counting/"">Read more on the site</a></p>"	"live-coding lcm::sql"	"lcm-en-sql-count-forms"
"<code>WHERE</code> or <code>HAVING</code>: which filters what?"	"<p><code>WHERE</code> filters rows before grouping. <code>HAVING</code> filters groups after it, by an aggregate: <code>HAVING COUNT(*) &gt; 300</code>.</p><p>A condition on a plain column belongs in <code>WHERE</code>: fewer rows reach the grouping.</p><p><a href=""https://butyavk.github.io/live-coding/sql/grouping-and-counting/"">Read more on the site</a></p>"	"live-coding lcm::sql"	"lcm-en-sql-where-vs-having"
"What do <code>NULL = NULL</code> and <code>NULL &lt;&gt; 1</code> return? How do you test for NULL?"	"<p>Both return <code>NULL</code>, &quot;unknown&quot;, and <code>WHERE</code> keeps only rows where the condition is true.</p><p>Test with <code>IS NULL</code> / <code>IS NOT NULL</code>. For &quot;not equal, counting NULL as a value&quot; use <code>IS DISTINCT FROM</code>.</p><p><a href=""https://butyavk.github.io/live-coding/sql/null-logic/"">Read more on the site</a></p>"	"live-coding lcm::sql"	"lcm-en-sql-null-compare"
"What does <code>SUM</code> return when there are no rows to add?"	"<p><code>NULL</code>, not 0. The same for <code>SUM(x) FILTER (WHERE …)</code> in a group without matches, and after a <code>LEFT JOIN</code> without a match. <code>COUNT</code> returns 0.</p><p>For money, wrap it: <code>COALESCE(SUM(amount_usd), 0)</code>.</p><p><a href=""https://butyavk.github.io/live-coding/sql/null-logic/"">Read more on the site</a></p>"	"live-coding lcm::sql"	"lcm-en-sql-sum-empty"
"How do you get several counts per group in one pass?"	"<p>One <code>GROUP BY</code> with a conditional aggregate per counter: <code>COUNT(*) FILTER (WHERE is_trial) AS trials</code>.</p><p>The portable form is <code>SUM(CASE WHEN … THEN 1 ELSE 0 END)</code>. A sum with <code>FILTER</code> can be <code>NULL</code>, so wrap money in <code>COALESCE</code>.</p><p><a href=""https://butyavk.github.io/live-coding/sql/conditional-aggregation/"">Read more on the site</a></p>"	"live-coding lcm::sql"	"lcm-en-sql-filter-counters"
"How do you compute a rate without integer division and without division by zero?"	"<p><code>1.0 * a / NULLIF(b, 0)</code>, or <code>a::numeric / b</code>.</p><p>In PostgreSQL an integer divided by an integer is an integer: <code>7 / 2 = 3</code>, and <code>COUNT(…) / COUNT(*)</code> is usually 0. <code>ROUND</code> at the very end; <code>ROUND(x, 2)</code> needs a <code>numeric</code>.</p><p><a href=""https://butyavk.github.io/live-coding/sql/conditional-aggregation/"">Read more on the site</a></p>"	"live-coding lcm::sql"	"lcm-en-sql-rate"
"&quot;Every product, including products with zero sales&quot;: what are the rules?"	"<ol><li>Start from the table of all products: <code>FROM products p LEFT JOIN transactions t ON …</code>.</li><li>Every condition on <code>t</code> goes in <code>ON</code>. In <code>WHERE</code> it drops the unmatched products, and the join becomes inner.</li><li>Count a column of <code>t</code>: <code>COUNT(t.product_id)</code>; <code>COUNT(*)</code> gives 1 instead of 0.</li><li>Sums get <code>COALESCE(…, 0)</code>.</li></ol><p><a href=""https://butyavk.github.io/live-coding/sql/left-join-and-zeros/"">Read more on the site</a></p>"	"live-coding lcm::sql"	"lcm-en-sql-left-join-zeros"
"&quot;Merchants who never received an advance&quot;: how, and why not <code>NOT IN</code>?"	"<p><code>FROM merchants m WHERE NOT EXISTS (SELECT 1 FROM advances v WHERE v.merchant_id = m.id)</code>, or <code>LEFT JOIN advances v … WHERE v.advance_id IS NULL</code>.</p><p><code>NOT IN</code> breaks on one <code>NULL</code> in the list: <code>1 NOT IN (2, NULL)</code> is <code>1 &lt;&gt; 2 AND 1 &lt;&gt; NULL</code>, which is <code>NULL</code>, so no row passes.</p><p><a href=""https://butyavk.github.io/live-coding/sql/subqueries-and-cte/"">Read more on the site</a></p>"	"live-coding lcm::sql"	"lcm-en-sql-anti-join"
"A <code>TIMESTAMP</code> column stores UTC. How do you get the day in New York?"	"<p>Two steps: <code>(ts AT TIME ZONE 'UTC' AT TIME ZONE 'America/New_York')::date</code>. A <code>timestamptz</code> column needs only the second step.</p><p>One step on a <code>TIMESTAMP</code> shifts the wrong way: 02:00 UTC on 1 September becomes 06:00, not 22:00 on 31 August.</p><p>Ask which time zone defines &quot;a day&quot; for the people who read the report.</p><p><a href=""https://butyavk.github.io/live-coding/sql/filters-and-dates/"">Read more on the site</a></p>"	"live-coding lcm::sql"	"lcm-en-sql-time-zone"
"Two tables each have many rows per merchant. How do you combine them?"	"<p>Reduce each table to one row per merchant in its own CTE, then <code>FROM merchants m LEFT JOIN</code> both CTEs, with <code>COALESCE</code>.</p><p>Joining the raw rows pairs every row of one table with every row of the other, and every sum is multiplied. Check one merchant with a separate simple query.</p><p><a href=""https://butyavk.github.io/live-coding/sql-patterns/row-multiplication/"">Read more on the site</a></p>"	"live-coding lcm::patterns"	"lcm-en-pat-aggregate-then-join"
"The best (or the latest) row in each group: what is the pattern?"	"<ol><li>Reduce to one row per (group, item) if needed.</li><li>In a CTE: <code>ROW_NUMBER() OVER (PARTITION BY group ORDER BY x DESC, id) AS rn</code>.</li><li>Outside: <code>WHERE rn = 1</code>.</li></ol><p>The <code>id</code> breaks ties, so the result is stable. A window cannot go in the <code>WHERE</code> of the same <code>SELECT</code>.</p><p><a href=""https://butyavk.github.io/live-coding/sql-patterns/top-n-per-group/"">Read more on the site</a></p>"	"live-coding lcm::patterns"	"lcm-en-pat-top1-per-group"
"Values 300, 300, 200: what do <code>ROW_NUMBER</code>, <code>RANK</code> and <code>DENSE_RANK</code> give?"	"<ul><li><code>ROW_NUMBER</code>: 1, 2, 3. Always unique, so <code>rn = 1</code> keeps one of the tied rows.</li><li><code>RANK</code>: 1, 1, 3. <code>rank = 1</code> keeps both.</li><li><code>DENSE_RANK</code>: 1, 1, 2. No gap after a tie.</li></ul><p>&quot;Keep ties&quot; means <code>RANK</code>.</p><p><a href=""https://butyavk.github.io/live-coding/sql-patterns/top-n-per-group/"">Read more on the site</a></p>"	"live-coding lcm::patterns"	"lcm-en-pat-ties"
"Share of the total and share within a group: how do you write each?"	"<p>Of the total: <code>100.0 * x / SUM(x) OVER ()</code>. Within a group: <code>100.0 * x / SUM(x) OVER (PARTITION BY merchant_id)</code>.</p><p>A window sees the rows left after <code>GROUP BY</code>. If you partition by the key that already has one row per group, every row gets 100%.</p><p><a href=""https://butyavk.github.io/live-coding/sql-patterns/running-totals-and-shares/"">Read more on the site</a></p>"	"live-coding lcm::patterns"	"lcm-en-pat-share"
"A running total per merchant by day: the window, and the frame trap?"	"<p><code>SUM(revenue) OVER (PARTITION BY merchant_id ORDER BY day)</code>.</p><p>With <code>ORDER BY</code>, the default frame is <code>RANGE … CURRENT ROW</code>: rows with the same <code>day</code> are added together. For an exact number of rows use <code>ROWS</code>.</p><p>A moving &quot;last 7 days&quot; with <code>ROWS</code> is right only if every day is one row: build the calendar first.</p><p><a href=""https://butyavk.github.io/live-coding/sql-patterns/running-totals-and-shares/"">Read more on the site</a></p>"	"live-coding lcm::patterns"	"lcm-en-pat-running-total"
"Every day of a period, including days with zero: how?"	"<ol><li>A calendar: <code>generate_series(TIMESTAMP '2026-09-01', TIMESTAMP '2026-09-10', INTERVAL '1 day') AS g(d)</code>.</li><li><code>LEFT JOIN</code> the data on the day.</li><li><code>COALESCE(…, 0)</code>.</li></ol><p>With <code>TIMESTAMP</code> literals the series is a plain <code>timestamp</code>, like the columns; with plain strings it is <code>timestamp with time zone</code>.</p><p><a href=""https://butyavk.github.io/live-coding/sql-patterns/calendars-and-active-periods/"">Read more on the site</a></p>"	"live-coding lcm::patterns"	"lcm-en-pat-calendar"
"When is a subscription active at moment m?"	"<p><code>start_time &lt;= m AND end_time &gt; m AND (refunded_at IS NULL OR refunded_at &gt; m)</code></p><p>The period is half-open, <code>[start_time, end_time)</code>, and a refund ends the subscription. The brackets around <code>OR</code> are required: <code>AND</code> binds tighter than <code>OR</code>.</p><p><a href=""https://butyavk.github.io/live-coding/sql-patterns/calendars-and-active-periods/"">Read more on the site</a></p>"	"live-coding lcm::patterns"	"lcm-en-pat-active-at"
"Duplicate webhooks: how do you count deliveries, events and duplicates?"	"<p>Deliveries are <code>COUNT(*)</code>, events are <code>COUNT(DISTINCT event_id)</code>, duplicates are the difference.</p><p><code>COUNT(DISTINCT)</code> removes repeats only inside its own group. If a copy can fall into another group (another day by <code>received_at</code>), first number the copies with <code>ROW_NUMBER() OVER (PARTITION BY event_id ORDER BY received_at)</code> and keep <code>rn = 1</code>.</p><p><a href=""https://butyavk.github.io/live-coding/sql-patterns/duplicates-and-idempotency/"">Read more on the site</a></p>"	"live-coding lcm::patterns"	"lcm-en-pat-dupes"
"How do you make sure each event is stored exactly once?"	"<p>A <code>PRIMARY KEY</code> or <code>UNIQUE</code> constraint on <code>event_id</code>, and <code>INSERT … ON CONFLICT (event_id) DO NOTHING</code>.</p><p>To add to a stored value instead: <code>ON CONFLICT (key) DO UPDATE SET v = t.v + EXCLUDED.v</code>.</p><p>The database enforces it even when two workers insert at the same time.</p><p><a href=""https://butyavk.github.io/live-coding/sql-patterns/duplicates-and-idempotency/"">Read more on the site</a></p>"	"live-coding lcm::patterns"	"lcm-en-pat-on-conflict"
"Sales and refunds as one stream of money per month: how?"	"<p><code>UNION ALL</code> of two branches: sales with <code>+amount</code> by <code>start_time</code>, refunds with <code>−amount</code> by <code>refunded_at</code>. Each branch has its own date column. Then one <code>GROUP BY</code> month.</p><p>Not <code>UNION</code>: it removes equal rows, so two payments of 9.99 on the same day become one. Columns match by position.</p><p><a href=""https://butyavk.github.io/live-coding/sql-patterns/union-and-reconciliation/"">Read more on the site</a></p>"	"live-coding lcm::patterns"	"lcm-en-pat-union-all"
"Reconcile two sources (expected and actual payouts): what is the shape of the query?"	"<ol><li>Each side reduced to one row per key in its own CTE, with its filters inside.</li><li><code>FULL OUTER JOIN</code> on the key, so rows missing on either side stay.</li><li><code>COALESCE(a.key, b.key)</code> for the key columns.</li><li>A <code>CASE</code> for the status: missing, unexpected, mismatch, ok.</li></ol><p><a href=""https://butyavk.github.io/live-coding/sql-patterns/union-and-reconciliation/"">Read more on the site</a></p>"	"live-coding lcm::patterns"	"lcm-en-pat-reconcile"
"Flow or balance: which one gets a date filter?"	"<p>A <strong>flow</strong> is a sum over a period (revenue in the last 30 days): it has a date window.</p><p>A <strong>balance</strong> is a state at a moment (what a merchant owes today): a sum over all time up to that moment. The ledger only adds signed entries (advance +, fee +, repayment −), so the debt is <code>SUM(amount_usd)</code> of every entry before today.</p><p>With a 30-day window on the ledger, <code>mer_03</code> &quot;owes&quot; −45.96; over all time it owes 116.39.</p><p><a href=""https://butyavk.github.io/live-coding/sql-patterns/money-and-ledgers/"">Read more on the site</a></p>"	"live-coding lcm::patterns"	"lcm-en-pat-flow-balance"
"Retention: &quot;customers whose first paid purchase was in July — how many bought again in August?&quot; The two rules?"	"<ol><li>The cohort comes from each customer's first paid purchase over all time: <code>MIN(start_time)</code> with no date window, then keep July.</li><li>&quot;Also bought in August&quot; is <code>EXISTS (…)</code>: it checks presence and does not multiply rows like a <code>JOIN</code>.</li></ol><p>The rate is <code>1.0 * retained / cohort_size</code>.</p><p><a href=""https://butyavk.github.io/live-coding/sql-patterns/cohorts-and-retention/"">Read more on the site</a></p>"	"live-coding lcm::patterns"	"lcm-en-pat-cohort"
"Does <code>SELECT 'found' WHERE 1 NOT IN (2, NULL)</code> return a row?"	"<p>No rows. It expands to <code>1 &lt;&gt; 2 AND 1 &lt;&gt; NULL</code>, that is <code>TRUE AND NULL</code>, which is <code>NULL</code>.</p><p>One <code>NULL</code> in a <code>NOT IN</code> list or subquery, and the result is empty. For &quot;not in the list&quot;, use <code>NOT EXISTS</code>.</p><p><a href=""https://butyavk.github.io/live-coding/sql/null-logic/"">Read more on the site</a></p>"	"live-coding lcm::traps"	"lcm-en-trap-not-in-null"
"The average price of paid web checkout purchases (no trials) as <code>AVG(CASE WHEN channel = 'web' THEN charged_usd ELSE 0 END)</code>: what goes wrong?"	"<p><code>ELSE 0</code> adds a zero for every row from another channel: 1.18 instead of 13.19.</p><p>For <code>AVG</code>, use <code>FILTER (WHERE channel = 'web')</code> or <code>CASE</code> without <code>ELSE</code>: <code>NULL</code> does not count. For a rate, <code>ELSE 0</code> is right: <code>AVG(CASE WHEN … THEN 1.0 ELSE 0 END)</code>.</p><p><a href=""https://butyavk.github.io/live-coding/sql/conditional-aggregation/"">Read more on the site</a></p>"	"live-coding lcm::traps"	"lcm-en-trap-avg-else0"
"The share of trials as <code>COUNT(…) FILTER (WHERE is_trial) / COUNT(*)</code>: what comes out?"	"<p>The result is 0. Both counts are integers, and an integer divided by an integer is an integer.</p><p>With <code>100.0 * …</code> in front, the same expression gives 11.3 (%). Write <code>1.0 * a / b</code> or <code>a::numeric / b</code>, and <code>NULLIF(b, 0)</code> against division by zero.</p><p><a href=""https://butyavk.github.io/live-coding/sql/conditional-aggregation/"">Read more on the site</a></p>"	"live-coding lcm::traps"	"lcm-en-trap-int-div"
"Purchases on 1 September with <code>WHERE start_time = '2026-09-01'</code>: how many?"	"<p>0: it matches midnight exactly.</p><p><code>start_time::date = '2026-09-01'</code> gives the right 20, but an index on <code>start_time</code> cannot be used. The range <code>start_time &gt;= '2026-09-01' AND start_time &lt; '2026-09-02'</code> gives 20 and can use the index.</p><p><a href=""https://butyavk.github.io/live-coding/sql/filters-and-dates/"">Read more on the site</a></p>"	"live-coding lcm::traps"	"lcm-en-trap-ts-eq-date"
"Does <code>WHERE start_time &gt;= '2026-09-30' - INTERVAL '30 days'</code> run?"	"<p>No: <code>invalid input syntax for type interval: &quot;2026-09-30&quot;</code>. A quoted string has no type at first and takes the type of its neighbour, here an interval.</p><p>Fix: <code>TIMESTAMP '2026-09-30' - INTERVAL '30 days'</code>, which is 2026-08-31 00:00. The last 30 days then have 483 transactions. Habit: always type the date literal.</p><p><a href=""https://butyavk.github.io/live-coding/sql/filters-and-dates/"">Read more on the site</a></p>"	"live-coding lcm::traps"	"lcm-en-trap-literal-interval"
"<code>products LEFT JOIN transactions</code>, then <code>WHERE t.country = 'JP'</code>, &quot;including zeros&quot;. How many of the 20 products come out?"	"<p>19: <code>prd_06</code> disappears. For a product without a match, <code>t.country</code> is <code>NULL</code>, and <code>WHERE</code> drops the row. The <code>LEFT JOIN</code> has become an inner join.</p><p>Move every condition on the right table into <code>ON</code>.</p><p><a href=""https://butyavk.github.io/live-coding/sql/left-join-and-zeros/"">Read more on the site</a></p>"	"live-coding lcm::traps"	"lcm-en-trap-left-where"
"<code>mer_09</code> has 2 products and 7 advances worth 1122.81. Join merchants → products → advances and sum the advances: what do you get?"	"<p>14 rows and 2245.62, exactly double. Products and advances are not related to each other, so every product is paired with every advance: 2 × 7.</p><p>Reduce each table to one row per merchant first, then join.</p><p><a href=""https://butyavk.github.io/live-coding/sql-patterns/row-multiplication/"">Read more on the site</a></p>"	"live-coding lcm::traps"	"lcm-en-trap-fanout"
"<code>WHERE channel = 'web' OR channel = 'north_market' AND NOT is_test</code>: what does it select?"	"<p><code>AND</code> binds tighter than <code>OR</code>, so this is &quot;web checkout, test purchases included&quot; OR &quot;North Market without test purchases&quot;: 5182 rows instead of 5158.</p><p>When you mix <code>AND</code> and <code>OR</code>, use brackets: <code>(channel = 'web' OR channel = 'north_market') AND NOT is_test</code>.</p><p><a href=""https://butyavk.github.io/live-coding/sql/filters-and-dates/"">Read more on the site</a></p>"	"live-coding lcm::traps"	"lcm-en-trap-and-or"
"What happens with <code>WHERE channel = &quot;web&quot;</code> in PostgreSQL?"	"<p>An error: <code>column &quot;web&quot; does not exist</code>. Double quotes are for names of columns and tables; strings take single quotes: <code>channel = 'web'</code>.</p><p><a href=""https://butyavk.github.io/live-coding/sql/postgresql-dialect/"">Read more on the site</a></p>"	"live-coding lcm::traps"	"lcm-en-trap-dquote"
"<code>WHERE proceeds &gt; 50</code>, where <code>proceeds</code> is an alias from <code>SELECT</code>, or <code>HAVING n &gt; 1000</code>: do they run?"	"<p>Both fail with <code>column … does not exist</code>. <code>WHERE</code> runs before <code>SELECT</code>, and in PostgreSQL <code>HAVING</code> does not see <code>SELECT</code> aliases either.</p><p>Repeat the expression (<code>HAVING COUNT(*) &gt; 1000</code>) or compute it in a CTE and filter outside. In <code>ORDER BY</code> an alias works.</p><p><a href=""https://butyavk.github.io/live-coding/sql/grouping-and-counting/"">Read more on the site</a></p>"	"live-coding lcm::traps"	"lcm-en-trap-alias"
"The first transaction of each customer with <code>WHERE ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY start_time) = 1</code>: does it run?"	"<p>No: <code>window functions are not allowed in WHERE</code>. Windows are computed in <code>SELECT</code>, after <code>WHERE</code>.</p><p>Compute <code>rn</code> in a CTE and filter <code>WHERE rn = 1</code> outside, or use <code>DISTINCT ON (customer_id) … ORDER BY customer_id, start_time</code>.</p><p><a href=""https://butyavk.github.io/live-coding/sql-patterns/top-n-per-group/"">Read more on the site</a></p>"	"live-coding lcm::traps"	"lcm-en-trap-window-where"
"<code>ROUND(AVG(charged_usd)::float8, 2)</code>: does it work in PostgreSQL?"	"<p>No: <code>function round(double precision, integer) does not exist</code>. <code>ROUND</code> with a number of decimals exists only for <code>numeric</code>.</p><p>Cast first: <code>ROUND(x::numeric, 2)</code>. Some other databases accept the float version silently.</p><p><a href=""https://butyavk.github.io/live-coding/sql/postgresql-dialect/"">Read more on the site</a></p>"	"live-coding lcm::traps"	"lcm-en-trap-round-double"
"One country, one month: 39 transactions and 35 customers. Why do the numbers differ, and which one answers &quot;how many customers&quot;?"	"<p>Some customers had several transactions that month. &quot;How many customers&quot; is <code>COUNT(DISTINCT customer_id)</code>.</p><p>Ask first what counts as one customer: a <code>customer_id</code>, or a pair of customer and product.</p><p><a href=""https://butyavk.github.io/live-coding/sql/grouping-and-counting/"">Read more on the site</a></p>"	"live-coding lcm::traps"	"lcm-en-trap-distinct-users"
"Group payments by customer and sum the amounts: the idiom?"	"<p><code>totals = defaultdict(Decimal)</code>, then <code>totals[p['customer']] += p['amount']</code> in one loop, and <code>return dict(totals)</code>.</p><p>A new key starts at <code>Decimal('0')</code>. Return a plain <code>dict</code>: reading a missing key of a <code>defaultdict</code> adds it. Money is <code>Decimal</code> made from strings.</p><p><a href=""https://butyavk.github.io/live-coding/python/dicts-and-counting/"">Read more on the site</a></p>"	"live-coding lcm::python"	"lcm-en-py-group-sum"
"Sort rows by amount descending, then by id ascending."	"<p><code>sorted(rows, key=lambda r: (-r.amount, r.id))</code>: a tuple key, minus for the descending number.</p><p><code>reverse=True</code> would reverse the id too. For a key you cannot negate (a string), sort twice: first by the second key, then by the first. <code>sorted</code> is stable, so equal items keep their order.</p><p><a href=""https://butyavk.github.io/live-coding/python/sorting-and-top-k/"">Read more on the site</a></p>"	"live-coding lcm::python"	"lcm-en-py-sort-keys"
"Top 10 out of a million rows: do you sort everything?"	"<p>No. <code>heapq.nsmallest(10, rows, key=lambda r: (-r.revenue, r.customer_id))</code> keeps a heap of the 10 best so far: <code>O(n log k)</code> time and <code>O(k)</code> memory instead of <code>O(n log n)</code>.</p><p>In the database, <code>ORDER BY … LIMIT 10</code> does the same: the plan shows <code>top-N heapsort</code>. <code>Counter.most_common</code> breaks ties by first appearance, not by the alphabet.</p><p><a href=""https://butyavk.github.io/live-coding/python/sorting-and-top-k/"">Read more on the site</a></p>"	"live-coding lcm::python"	"lcm-en-py-top-k"
"Duplicates, or &quot;have I seen it before?&quot;: which structure, and what does it cost?"	"<p>A <code>set</code> called <code>seen</code> and one pass: membership is <code>O(1)</code> on average, so the whole pass is <code>O(n)</code>.</p><p><code>x in list</code> checks every element, <code>O(n)</code>, so inside a loop it becomes <code>O(n²)</code>. To keep the first copy of each event in order, add the id to <code>seen</code> when you keep the event.</p><p><a href=""https://butyavk.github.io/live-coding/python/sets-and-duplicates/"">Read more on the site</a></p>"	"live-coding lcm::python"	"lcm-en-py-seen-set"
"Events arrive out of order. How do you get the latest status per subscription?"	"<p>A <code>dict</code> of &quot;best so far&quot;: for each event, replace the stored one only if the new timestamp is later. One pass, <code>O(n)</code>.</p><p>Compare timestamps, not the order of arrival, and agree on a rule for equal timestamps (for example, the later one in the list wins).</p><p><a href=""https://butyavk.github.io/live-coding/python/dicts-and-counting/"">Read more on the site</a></p>"	"live-coding lcm::python"	"lcm-en-py-latest-per-key"
"Round a <code>Decimal</code> to cents, half up and down. Why not <code>round()</code>?"	"<p>Half up: <code>x.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)</code>, so <code>0.125</code> → <code>0.13</code>. Down: <code>rounding=ROUND_DOWN</code>, so <code>23.9976</code> → <code>23.99</code>.</p><p><code>round(x, 2)</code> returns a <code>Decimal</code>, but it uses banker's rounding (<code>0.125</code> → <code>0.12</code>) and cannot round down.</p><p><a href=""https://butyavk.github.io/live-coding/python/money-and-decimal/"">Read more on the site</a></p>"	"live-coding lcm::python"	"lcm-en-py-decimal-round"
"Why not <code>float</code> for money?"	"<p>Float is binary, so <code>0.1 + 0.2 != 0.3</code>, and the error grows in sums.</p><p>Use <code>Decimal</code> created from strings: <code>Decimal('0.1')</code>. From a float only through <code>str</code>: <code>Decimal(0.1)</code> keeps the binary error. In the database, <code>NUMERIC(12,2)</code>.</p><p><a href=""https://butyavk.github.io/live-coding/python/money-and-decimal/"">Read more on the site</a></p>"	"live-coding lcm::python"	"lcm-en-py-float-money"
"Split <code>10.00</code> into 3 parts that add up exactly to <code>10.00</code>."	"<p>Work in whole cents: <code>q, r = divmod(1000, 3)</code> gives <code>(333, 1)</code>. The first <code>r</code> parts get one extra cent: <code>3.34</code>, <code>3.33</code>, <code>3.33</code>.</p><p>Dividing and rounding each part separately gives parts that do not add up to the amount.</p><p><a href=""https://butyavk.github.io/live-coding/python/money-and-decimal/"">Read more on the site</a></p>"	"live-coding lcm::python"	"lcm-en-py-split-cents"
"Pay debts from a payout, oldest first, partial payments allowed: the loop?"	"<ol><li>A negative payout raises <code>ValueError</code>; <code>left = payout</code>.</li><li>For each debt in order: <code>pay = min(left, due)</code>.</li><li>Add a line only <code>if pay &gt; 0</code>, then <code>left -= pay</code>.</li><li><code>break</code> when <code>left == 0</code>. What is left goes to the merchant.</li></ol><p>One pass over the sorted debts. A <code>while</code> loop around the <code>for</code> pays the first debt twice.</p><p><a href=""https://butyavk.github.io/live-coding/python/money-and-decimal/"">Read more on the site</a></p>"	"live-coding lcm::python"	"lcm-en-py-allocate"
"When do <code>[a, b)</code> and <code>[c, d)</code> overlap, and how do you merge a list of periods?"	"<p>Overlap: <code>a &lt; d and c &lt; b</code>. Touching ends (<code>b == c</code>) do not overlap.</p><p>Merge: sort by start, then one pass. If a period starts before (or, if touching counts, at) the end of the last merged one, extend that one to <code>max(end)</code>; otherwise start a new one. <code>max</code> keeps a nested period from shortening it. <code>O(n log n)</code> because of the sort.</p><p><a href=""https://butyavk.github.io/live-coding/python/intervals/"">Read more on the site</a></p>"	"live-coding lcm::python"	"lcm-en-py-intervals"
"Add one month to 31 January 2026 in Python."	"<p>Not with <code>timedelta</code>: months have different lengths. Compute the year and the month with <code>divmod(month - 1 + n, 12)</code>, then cap the day: <code>min(day, calendar.monthrange(year, month)[1])</code>. The result is 28 February 2026.</p><p>For renewals, count each from the original date: chaining gives 28 March instead of 31 March.</p><p><a href=""https://butyavk.github.io/live-coding/python/dates-and-durations/"">Read more on the site</a></p>"	"live-coding lcm::python"	"lcm-en-py-add-months"
"A rate limiter: at most <code>limit</code> requests in any <code>window</code> seconds. The structure and the rule?"	"<p>A <code>deque</code> of accepted request times. On each call:</p><ol><li>Drop from the left while <code>times[0] &lt;= now - window</code>.</li><li>If <code>len(times) &gt;= limit</code>, return <code>False</code>: a refused request is not recorded.</li><li>Otherwise append <code>now</code> and return <code>True</code>.</li></ol><p>Pass the clock in, so tests control time without sleeping.</p><p><a href=""https://butyavk.github.io/live-coding/python/time-windows/"">Read more on the site</a></p>"	"live-coding lcm::python"	"lcm-en-py-rate-limiter"
"What is wrong with <code>def add(item, items=[])</code>?"	"<p>The default list is created once, when the function is defined, and it is shared between calls: the second call sees the items of the first.</p><p>Use <code>items=None</code> and create the list inside the function. The same trap hides in <code>_cache={}</code> and <code>seen=set()</code>.</p><p><a href=""https://butyavk.github.io/live-coding/python/classes-and-state/"">Read more on the site</a></p>"	"live-coding lcm::python"	"lcm-en-py-mutable-default"
"What does <code>functools.wraps</code> do, and where does it go?"	"<p>On the inner <code>wrapper</code>, because the wrapper replaces the original function. It copies the name, the docstring and the module, so logs and tools still see the real name. It also sets <code>__wrapped__</code> to the original: <code>help()</code> and <code>inspect.signature</code> follow it, and tests can call the original through it.</p><p>A decorator with a parameter has three levels: factory → decorator → wrapper.</p><p><a href=""https://butyavk.github.io/live-coding/python/decorators/"">Read more on the site</a></p>"	"live-coding lcm::python"	"lcm-en-py-wraps"
"The cost of a lookup in a <code>dict</code>, a <code>set</code> and a <code>list</code>, and of sorting?"	"<p>A <code>dict</code> or <code>set</code> lookup is <code>O(1)</code> on average: they are hash tables. <code>x in list</code> is <code>O(n)</code>, so inside a loop it is <code>O(n²)</code>. Sorting is <code>O(n log n)</code>; a heap push or pop is <code>O(log n)</code>.</p><p>Say it out loud: <em>&quot;It's O(n log n) because of the sort, and the memory is O(n).&quot;</em></p><p><a href=""https://butyavk.github.io/live-coding/python/testing-and-complexity/"">Read more on the site</a></p>"	"live-coding lcm::python"	"lcm-en-py-complexity"
"Parse an amount string into a <code>Decimal</code> safely: which errors do you handle?"	"<ul><li><code>Decimal('abc')</code> raises <code>InvalidOperation</code>, which is not a <code>ValueError</code>: catch it and raise <code>ValueError</code>.</li><li><code>Decimal('NaN')</code> and <code>Decimal('Infinity')</code> parse without an error: reject them with <code>is_finite()</code>.</li><li>Empty or negative input: raise <code>ValueError</code> with a clear message.</li></ul><p>Then <code>quantize</code> to cents.</p><p><a href=""https://butyavk.github.io/live-coding/python/errors-and-validation/"">Read more on the site</a></p>"	"live-coding lcm::python"	"lcm-en-py-validate"
"How do you pass an input value into SQL from Python, and where should the work happen?"	"<p>Only as a parameter: <code>con.execute('… WHERE product_id = ?', [product_id])</code>, or <code>:product</code> with SQLAlchemy. Never an f-string: that is SQL injection, and parameters also handle types and quotes.</p><p>Filter and aggregate in SQL, close to the data and its indexes; bring a small result into Python. Keep in Python only what is hard in SQL, like an allocation loop.</p><p><a href=""https://butyavk.github.io/live-coding/python/python-and-sql/"">Read more on the site</a></p>"	"live-coding lcm::python"	"lcm-en-py-sql-params"
"A query is slow. How do you find out why?"	"<p>Run <code>EXPLAIN ANALYZE</code> and read it from the most expensive node. Look for three things:</p><ul><li>a <code>Seq Scan</code> on a big table where you expected an index;</li><li>estimated rows very different from actual rows: often stale statistics, so run <code>ANALYZE</code>, or columns that depend on each other (<code>CREATE STATISTICS</code>);</li><li>a sort or hash that spills to disk: <code>external merge Disk</code>, or <code>Batches</code> above 1.</li></ul><p>Fix the biggest problem first, then measure again.</p><p><a href=""https://butyavk.github.io/live-coding/sql-patterns/indexes-and-explain/"">Read more on the site</a></p>"	"live-coding lcm::concepts"	"lcm-en-con-slow-query"
"Does the order of columns in a composite index matter?"	"<p>Yes. An index on <code>(product_id, start_time)</code> serves <code>WHERE product_id = … AND start_time &gt; …</code> and <code>WHERE product_id = …</code>, but not <code>WHERE start_time &gt; …</code> alone, at least not efficiently.</p><p>Equality columns go first, the range column last.</p><p><a href=""https://butyavk.github.io/live-coding/sql-patterns/indexes-and-explain/"">Read more on the site</a></p>"	"live-coding lcm::concepts"	"lcm-en-con-composite-index"
"There is an index on <code>start_time</code>. When will PostgreSQL not use it?"	"<ul><li>When a function wraps the column: <code>start_time::date = …</code> or <code>EXTRACT(…)</code>. Compare the raw column with a range, or create an expression index.</li><li>When the query takes a large share of the table: a sequential scan is cheaper then. How large depends on the physical order: rows written in time order keep a date range cheap for longer (<code>pg_stats.correlation</code> near 1).</li></ul><p>Check with <code>EXPLAIN ANALYZE</code>. And do not index every column: each index slows down writes and takes space.</p><p><a href=""https://butyavk.github.io/live-coding/sql-patterns/indexes-and-explain/"">Read more on the site</a></p>"	"live-coding lcm::concepts"	"lcm-en-con-index-not-used"
"Does PostgreSQL index a foreign key column automatically?"	"<p>No. Only <code>PRIMARY KEY</code>, <code>UNIQUE</code> and <code>EXCLUDE</code> constraints get an index. Joining to <code>products.id</code> uses the primary key, but <code>transactions.product_id</code> has no index until you create one.</p><p>For a report on one product, an index on <code>(product_id, start_time)</code> helps.</p><p><a href=""https://butyavk.github.io/live-coding/sql-patterns/indexes-and-explain/"">Read more on the site</a></p>"	"live-coding lcm::concepts"	"lcm-en-con-fk-index"
"What is the N+1 problem?"	"<p>One query for a list, then one more query for each item: 100 invoices become 101 queries.</p><p>The fix is a join, or one query with <code>WHERE id IN (…)</code> for all the items.</p><p><a href=""https://butyavk.github.io/live-coding/sql-patterns/database-concepts/"">Read more on the site</a></p>"	"live-coding lcm::concepts"	"lcm-en-con-n-plus-1"
"How do you make sure a webhook is processed only once?"	"<p>A unique constraint on <code>event_id</code> and <code>INSERT … ON CONFLICT (event_id) DO NOTHING</code>. The database guarantees it even with two workers.</p><p>A check in application code (&quot;select, then insert if missing&quot;) is not enough: two workers can both pass the check at the same time.</p><p>The insert and the processing commit in one transaction: if the worker crashes after the insert, both roll back, and the retry processes the event.</p><p><a href=""https://butyavk.github.io/live-coding/sql-patterns/database-concepts/"">Read more on the site</a></p>"	"live-coding lcm::concepts"	"lcm-en-con-webhook-once"
"What does a transaction give you, and what should never happen inside one?"	"<p>All or nothing: either every change is saved, or none. For example, a payout and its ledger entries are written together. Other sessions do not see the changes before <code>COMMIT</code>, and after <code>COMMIT</code> they survive a crash.</p><p>Never call an external service (a bank, a marketplace API) inside a transaction. It holds locks and a connection while it waits, and if it rolls back after a timeout, the external request may already be sent.</p><p><a href=""https://butyavk.github.io/live-coding/sql-patterns/database-concepts/"">Read more on the site</a></p>"	"live-coding lcm::concepts"	"lcm-en-con-transaction"
"Read Committed, Repeatable Read, Serializable: what does each mean in PostgreSQL?"	"<ul><li><strong>Read Committed</strong> (the default): each query sees what was committed before that query started. Two <code>SELECT</code>s in one transaction can differ.</li><li><strong>Repeatable Read</strong>: one snapshot for the whole transaction. Updating a row that another transaction changed raises an error; retry.</li><li><strong>Serializable</strong>: the result is as if transactions ran one after another; otherwise one fails with a serialization error, and the application retries it.</li></ul><p><a href=""https://butyavk.github.io/live-coding/sql-patterns/database-concepts/"">Read more on the site</a></p>"	"live-coding lcm::concepts"	"lcm-en-con-isolation"
"A limit of 1000, a debt of 700. Two workers each check the limit and issue an advance of 250 at the same time. What happens, and how do you prevent it?"	"<p>Both read 700, both see 950 ≤ 1000, both insert: the debt becomes 1200. Repeatable Read does not help, because they insert different rows.</p><p>Lock the merchant row first: <code>SELECT … FROM merchants WHERE id = … FOR UPDATE</code>. The second worker waits for the first to commit, then sees 950 and refuses. Or use Serializable and retry on the error.</p><p><a href=""https://butyavk.github.io/live-coding/sql-patterns/database-concepts/"">Read more on the site</a></p>"	"live-coding lcm::concepts"	"lcm-en-con-race-limit"
"Two workers take the same job from a job table. How do you prevent it?"	"<p><code>SELECT … FOR UPDATE SKIP LOCKED</code>: each worker locks different rows and skips the ones already taken.</p><p>Add a unique key on the business key too, so a duplicate fails even if something else goes wrong.</p><p><a href=""https://butyavk.github.io/live-coding/sql-patterns/database-concepts/"">Read more on the site</a></p>"	"live-coding lcm::concepts"	"lcm-en-con-skip-locked"
"Can we trust the refund rate for the last month?"	"<p>Not fully. Refunds come after the purchase: in the practice data, a median of about 11 days and 21 days at most. Any month younger than that looks better than it really is.</p><p>Mark those months as incomplete, or compare months by the refund rate within the first 30 days, counting only purchases that already had 30 days.</p><p><a href=""https://butyavk.github.io/live-coding/sql-patterns/database-concepts/"">Read more on the site</a></p>"	"live-coding lcm::concepts"	"lcm-en-con-maturing-month"
"The interview protocol in six steps?"	"<p><strong>REPEAT → ASK (in one batch) → COMMENTS → PLAN → CODE → CHECK against the comments.</strong></p><p>The main idea: keep the requirements in comments, not in your head, and check the code against them before you say &quot;done&quot;.</p><p><a href=""https://butyavk.github.io/live-coding/start/interview-protocol/"">Read more on the site</a></p>"	"live-coding lcm::interview"	"lcm-en-int-protocol"
"How do you split the clock on one task?"	"<p>Easy / medium / hard:</p><ul><li>Restate the task and one row of the result: 1 / 1 / 1–2 min.</li><li>The environment once, then 3–5 task questions in one batch, answers as comments: 1–2 / about 3 / up to 5 min.</li><li>A plan of 2–4 steps, out loud: 1 / 1–2 / 2 min.</li><li>So code starts at about minute 4 / 6 / 9, and gets the target time.</li><li>The rest: index, complexity, production.</li></ul><p>The clock: 25 min, or the target plus 10 when the target is over 15. Out of time for questions? <em>&quot;Let me start with these assumptions and adjust later.&quot;</em></p><p><a href=""https://butyavk.github.io/live-coding/start/interview-protocol/"">Read more on the site</a></p>"	"live-coding lcm::interview"	"lcm-en-int-timing"
"What do you say in the first minute of a task?"	"<p>Restate the task in your own words and name one row of the result: <em>&quot;So the result has one row per merchant, with columns merchant_id and revenue. Is that right?&quot;</em></p><p>If you cannot name one row, the task is not understood yet. Ask: <em>&quot;Can you show me what one row of the result should look like?&quot;</em></p><p><a href=""https://butyavk.github.io/live-coding/start/interview-protocol/"">Read more on the site</a></p>"	"live-coding lcm::interview"	"lcm-en-int-result-row"
"How do you ask clarifying questions without slowing down?"	"<p>In one batch, each with the answer you would assume: <em>&quot;A few questions, with what I'd assume. Today is 2026-09-30, not now(). Test purchases excluded. Refunds: excluded or net? Which channels? Ties by id. Is that right?&quot;</em></p><p>One more question covers data quality: <em>&quot;Anything I should know about duplicates, test data, missing values?&quot;</em></p><p><a href=""https://butyavk.github.io/live-coding/start/interview-protocol/"">Read more on the site</a></p>"	"live-coding lcm::interview"	"lcm-en-int-batch-questions"
"You see the schema for the first time. Which kinds of columns turn into questions?"	"<ul><li>A flag (<code>is_test</code>, <code>is_trial</code>): include or exclude?</li><li>A category (<code>channel</code>, <code>type</code>): group by it to see the values. Which of these count?</li><li>A time that can be <code>NULL</code> (<code>refunded_at</code>): what does NULL mean here?</li><li>Two similar amounts (<code>revenue_usd</code>, <code>charged_usd</code>): which one is right?</li><li>Several dates: which one puts a row into the period?</li><li>An event or payment id: can the same one arrive twice?</li></ul><p><a href=""https://butyavk.github.io/live-coding/start/interview-protocol/"">Read more on the site</a></p>"	"live-coding lcm::interview"	"lcm-en-int-column-questions"
"The checklist of questions before you write code?"	"<ul><li><strong>Today</strong>: a fixed date or <code>now()</code>?</li><li><strong>Every narrowing word</strong> (enrolled, paid, active, last 30 days): which column?</li><li><strong>Filters</strong>: test purchases, trials, promo access, refunds, which channels.</li><li><strong>The result row</strong>: one row per what? Include zeros and empty groups?</li><li><strong>Ties and order.</strong></li><li><strong>Edge cases</strong>: negative, zero, empty.</li><li><strong>Who uses the result</strong>: finance or a product dashboard decides refunds and rounding.</li></ul><p>Go through it in your head; ask three to five of these, the ones that change the result most, and write the rest as assumptions in the comments.</p><p><a href=""https://butyavk.github.io/live-coding/start/interview-protocol/"">Read more on the site</a></p>"	"live-coding lcm::interview"	"lcm-en-int-must-ask"
"How do the agreed answers get into the code?"	"<p>As a block of comments at the top, written while you listen. The first line is <strong>RESULT</strong> (one row per …), then today, the filters and the definitions, and the last line is <strong>PLAN</strong> (2–3 steps).</p><p>In Python: RETURNS, the rules, the edge cases, PLAN. Say: <em>&quot;Let me write your answers down as comments, so we both see them.&quot;</em></p><p><a href=""https://butyavk.github.io/live-coding/start/interview-protocol/"">Read more on the site</a></p>"	"live-coding lcm::interview"	"lcm-en-int-comments"
"Two questions to ask yourself while you plan a SQL query?"	"<ol><li>Before a <code>JOIN</code>: do both sides have many rows per key? If yes, aggregate each side in a CTE first.</li><li>Before a <code>GROUP BY</code> or <code>PARTITION BY</code>: within what am I choosing or counting? If the key is the same as the grouping of the previous step, the step does nothing.</li></ol><p>In Python, say the rule in one sentence before the code.</p><p><a href=""https://butyavk.github.io/live-coding/start/interview-protocol/"">Read more on the site</a></p>"	"live-coding lcm::interview"	"lcm-en-int-plan-checks"
"The check before &quot;done&quot;, in order?"	"<ol><li>Walk through the comments: where is each one in the code? <em>&quot;Let me check the code against what we agreed.&quot;</em></li><li>The number of rows: as expected?</li><li>One row by hand, or with a separate simple query.</li><li>Plausibility: a maximum ten times the average, <code>COUNT(*)</code> against <code>COUNT(DISTINCT id)</code>.</li><li>In Python, the edge cases from the comment: zero, partial, exactly on a boundary, more than enough, ties.</li></ol><p><a href=""https://butyavk.github.io/live-coding/start/interview-protocol/"">Read more on the site</a></p>"	"live-coding lcm::interview"	"lcm-en-int-check-before-done"
"The interviewer asks &quot;How do you know it works?&quot; or &quot;Is this what we agreed?&quot;. What do you do?"	"<p>Run it, do not explain it: <em>&quot;Good point, let me run it.&quot;</em> Then two checks: exactly on the boundary, and one second before it.</p><p>To &quot;Is this what we agreed?&quot;, do not say &quot;yes&quot; at once: <em>&quot;Let me re-read what we agreed&quot;</em>, then check the comments against the code.</p><p><a href=""https://butyavk.github.io/live-coding/start/interview-protocol/"">Read more on the site</a></p>"	"live-coding lcm::interview"	"lcm-en-int-how-do-you-know"
"You are stuck. What do you say?"	"<p>Never stay silent for more than 30 seconds; say what you are thinking about.</p><ul><li><em>&quot;I'm not sure how to … . Can I think out loud?&quot;</em></li><li><em>&quot;Let me go back to the example and check it again.&quot;</em></li><li><em>&quot;Could you point me in the right direction?&quot;</em></li><li>With five minutes left: <em>&quot;I'll finish the main case first, then the edge cases.&quot;</em></li></ul><p><a href=""https://butyavk.github.io/live-coding/start/think-aloud/"">Read more on the site</a></p>"	"live-coding lcm::interview"	"lcm-en-int-stuck"
