<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>DECISION STATS</title>
	<atom:link href="https://decisionstats.com/feed/" rel="self" type="application/rss+xml" />
	<link>https://decisionstats.com</link>
	<description>Better Decisions === Faster Stats</description>
	<lastBuildDate>Mon, 10 Aug 2026 06:35:48 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<site xmlns="com-wordpress:feed-additions:1">2245452</site><cloud domain='decisionstats.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<source:cloud xmlns:source='https://source.scripting.com/'>https://decisionstats.com/?rsscloud=notify</source:cloud>
<image>
		<url>https://secure.gravatar.com/blavatar/d336d6df5f72ded22bce06883a2ee2c996d78ac0ad720272c24535dd705a9fc9?s=96&#038;d=https%3A%2F%2Fs2.wp.com%2Fi%2Fwebclip.png</url>
		<title>DECISION STATS</title>
		<link>https://decisionstats.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="https://decisionstats.com/osd.xml" title="DECISION STATS" />
	<atom:link rel='hub' href='https://decisionstats.com/?pushpress=hub'/>
	<item>
		<title>SQL Window Functions: Ranking, Running Totals, LAG, LEAD and Moving Averages</title>
		<link>https://decisionstats.com/2026/08/10/sql-window-functions-ranking-running-totals-lag-lead-and-moving-averages/</link>
					<comments>https://decisionstats.com/2026/08/10/sql-window-functions-ranking-running-totals-lag-lead-and-moving-averages/#respond</comments>
		
		<dc:creator><![CDATA[Aviral Gupta]]></dc:creator>
		<pubDate>Mon, 10 Aug 2026 06:35:48 +0000</pubDate>
				<category><![CDATA[Analytics]]></category>
		<category><![CDATA[data]]></category>
		<category><![CDATA[sql]]></category>
		<guid isPermaLink="false">http://decisionstats.com/?p=14615</guid>

					<description><![CDATA[SQL window functions are one of the most powerful tools for analytical queries because they calculate values across related rows without collapsing the original result set. Unlike GROUP BY, which reduces many rows into a smaller number of groups, a window function returns one value for every input row while adding an analytical column. The &#8230; <a href="https://decisionstats.com/2026/08/10/sql-window-functions-ranking-running-totals-lag-lead-and-moving-averages/" class="more-link">Continue reading<span class="screen-reader-text"> "SQL Window Functions: Ranking, Running Totals, LAG, LEAD and Moving&#160;Averages"</span></a>]]></description>
										<content:encoded><![CDATA[
<h2 class="wp-block-heading"></h2>



<p class="wp-block-paragraph">SQL window functions are one of the most powerful tools for analytical queries because they calculate values across related rows without collapsing the original result set. Unlike <code>GROUP BY</code>, which reduces many rows into a smaller number of groups, a window function returns one value for every input row while adding an analytical column. The <code>OVER</code> clause defines the window through three optional components: <code>PARTITION BY</code> divides rows into independent groups, <code>ORDER BY</code> establishes their sequence, and a frame determines exactly which rows are included in the calculation. This makes window functions suitable for customer-level totals, percentage-of-total calculations, rankings, and running measures while preserving row-level detail.<br />Ranking functions provide several ways to assign positions while handling ties differently. <code>ROW_NUMBER()</code> assigns a unique sequential number and is useful for deduplication or selecting one record per group. <code>RANK()</code> gives tied rows the same position and leaves gaps after ties, making it appropriate for competition-style standings. <code>DENSE_RANK()</code> also assigns equal ranks to ties but does not leave gaps, which makes it useful for top-N tiers. <code>NTILE()</code> distributes rows into approximately equal buckets for quartiles, deciles, or cohorts. A critical detail is determinism: <code>ROW_NUMBER()</code> over a non-unique ordering can produce different assignments between executions, so a unique tiebreaker such as a primary key should be added. For Top-N-per-group queries, ranking is calculated inside a CTE or subquery and filtered in the outer query because window functions are evaluated after <code>WHERE</code>.<br />Offset functions allow SQL to compare the current row with neighbouring rows without constructing self-joins. <code>LAG()</code> retrieves a value from an earlier row, while <code>LEAD()</code> looks ahead, making them ideal for month-over-month changes, period comparisons, and time-to-next-event calculations. <code>FIRST_VALUE()</code> and <code>LAST_VALUE()</code> retrieve values from the edges of a window, but <code>LAST_VALUE()</code> requires particular care because the default frame can end at the current row, causing it to return the current value rather than the final value of the partition. Aggregate functions such as <code>SUM</code>, <code>AVG</code>, <code>COUNT</code>, <code>MIN</code>, and <code>MAX</code> can also operate as windows. With <code>ORDER BY</code>, they can produce cumulative calculations such as running totals; without ordering, they can repeat a partition-level summary on every row. An explicit <code>ROWS</code> frame can create fixed-width calculations such as seven-row moving averages.<br />Window frames are particularly important when duplicate ordering values or time gaps exist. <code>ROWS</code> defines a physical number of rows, while <code>RANGE</code> groups rows according to the ordering value, meaning duplicate order values can be treated as peers. Choosing the wrong frame can therefore produce unexpected running totals or moving-window results. The presentation also applies window functions to practical analytical patterns including Top-N per group, deduplication, gaps and islands, sessionisation, and cohort retention. In the cohort example, <code>MIN(...) OVER (PARTITION BY cust_id)</code> identifies each customer&#8217;s first month without collapsing the order rows, month arithmetic determines the customer&#8217;s offset from that cohort, and a windowed <code>MAX</code> supplies the month-zero population used as the retention denominator.<br />Performance depends largely on the sorting required by each distinct window specification. Each different <code>PARTITION BY</code> and <code>ORDER BY</code> combination may require its own sort, after which the window calculations can generally be completed in a pass over the sorted data. Reusing a named window specification can allow multiple functions to share the same sort, while an index matching the partition and ordering columns may eliminate or reduce sorting work. Execution plans should therefore be inspected for <code>WindowAgg</code> and <code>Sort</code> operations when tuning analytical queries. The presentation also highlights several common mistakes: filtering a window result directly in <code>WHERE</code>, using <code>LAST_VALUE()</code> without extending its frame, relying on non-deterministic <code>ROW_NUMBER()</code>, confusing <code>RANGE</code> with <code>ROWS</code>, and assuming window functions are always preferable to a simple <code>GROUP BY</code>. The right approach is to define the window precisely, choose ranking and frame semantics intentionally, and verify performance with the execution plan.</p>



<figure class="wp-block-embed is-type-rich is-provider-embed wp-block-embed-embed"><div class="wp-block-embed__wrapper">
<a href="https://docs.google.com/presentation/d/e/2PACX-1vT8uDq51jOMYDvaiRZi0wvCSh4at5TqwThzjD5zBHOcm0Oi45r6jmq51TP1LhyGMg/pub?start=true&#038;loop=true&#038;delayms=10000" rel="nofollow">https://docs.google.com/presentation/d/e/2PACX-1vT8uDq51jOMYDvaiRZi0wvCSh4at5TqwThzjD5zBHOcm0Oi45r6jmq51TP1LhyGMg/pub?start=true&#038;loop=true&#038;delayms=10000</a>
</div></figure>



<iframe src="https://docs.google.com/presentation/d/e/2PACX-1vT8uDq51jOMYDvaiRZi0wvCSh4at5TqwThzjD5zBHOcm0Oi45r6jmq51TP1LhyGMg/pubembed?start=true&#038;loop=true&#038;delayms=10000" frameborder="0" width="800" height="375" marginheight="0" marginwidth="0" allowfullscreen="true" mozallowfullscreen="true" webkitallowfullscreen="true"></iframe>
]]></content:encoded>
					
					<wfw:commentRss>https://decisionstats.com/2026/08/10/sql-window-functions-ranking-running-totals-lag-lead-and-moving-averages/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">14615</post-id>
		<media:content url="https://2.gravatar.com/avatar/283eba774214f34e58e5bc32c2ce8d9a28f5ab203bfa2c074415f226f01478af?s=96&#38;d=wavatar&#38;r=G" medium="image">
			<media:title type="html">aviralgupta0310</media:title>
		</media:content>
	</item>
		<item>
		<title>SQL Views &#038; Materialized Views: Designing, Securing and Optimizing Database Reporting</title>
		<link>https://decisionstats.com/2026/08/10/sql-views-materialized-views-designing-securing-and-optimizing-database-reporting/</link>
					<comments>https://decisionstats.com/2026/08/10/sql-views-materialized-views-designing-securing-and-optimizing-database-reporting/#respond</comments>
		
		<dc:creator><![CDATA[Aviral Gupta]]></dc:creator>
		<pubDate>Mon, 10 Aug 2026 06:33:08 +0000</pubDate>
				<category><![CDATA[Analytics]]></category>
		<category><![CDATA[data]]></category>
		<category><![CDATA[sql]]></category>
		<guid isPermaLink="false">http://decisionstats.com/?p=14612</guid>

					<description><![CDATA[SQL views provide a reusable interface over database queries without physically storing their result, while materialized views store the computed result for faster reads. A regular view is expanded into the calling query and is therefore always current, but the underlying computation is performed whenever the view is queried. A materialized view, in contrast, behaves &#8230; <a href="https://decisionstats.com/2026/08/10/sql-views-materialized-views-designing-securing-and-optimizing-database-reporting/" class="more-link">Continue reading<span class="screen-reader-text"> "SQL Views &#38; Materialized Views: Designing, Securing and Optimizing Database&#160;Reporting"</span></a>]]></description>
										<content:encoded><![CDATA[
<h2 class="wp-block-heading"></h2>



<p class="wp-block-paragraph">SQL views provide a reusable interface over database queries without physically storing their result, while materialized views store the computed result for faster reads. A regular view is expanded into the calling query and is therefore always current, but the underlying computation is performed whenever the view is queried. A materialized view, in contrast, behaves more like a stored reporting table: its result can be indexed and read quickly, but it is only as fresh as its most recent refresh. This distinction makes ordinary views useful for consistent business definitions and abstraction, while materialized views are particularly valuable for expensive analytical queries and dashboards where some data staleness is acceptable.</p>



<p class="wp-block-paragraph">Good view design requires deliberate layering rather than building increasingly deep chains of views. The presentation recommends separating a model into a base layer for cleaning and standardising source data, a business or entity layer for joining meaningful entities, and a reporting layer for aggregates consumed by dashboards and exports. This keeps dependencies understandable and makes each stage independently testable. <code>CREATE OR REPLACE VIEW</code> can update a definition while preserving a stable column structure, whereas dropping a view with <code>CASCADE</code> can remove dependent objects and therefore requires caution. Simple predicates from an outer query can often be pushed into a view&#8217;s plan, but aggregates, <code>DISTINCT</code>, and window functions can prevent such pushdown and make deeply nested reporting views expensive to execute.<br />Views can also act as controlled write and security boundaries. A simple view over one table without aggregation, <code>DISTINCT</code>, <code>GROUP BY</code>, or set operations can be automatically updatable, while <code>WITH CHECK OPTION</code> prevents inserts or updates that would create rows outside the view&#8217;s defining predicate. More complex views can route writes through <code>INSTEAD OF</code> triggers. From a security perspective, views can expose only approved columns, restrict rows by role or tenant, and provide a controlled interface while base-table permissions are revoked. PostgreSQL&#8217;s <code>security_barrier</code> option can prevent certain predicate-pushdown techniques from leaking filtered information through user-defined functions, while row-level security is generally the stronger mechanism for enforcing tenant isolation directly on the underlying table.</p>



<p class="wp-block-paragraph">Materialized views are particularly effective when a query is expensive but its result does not need to be generated for every request. A materialized reporting view can aggregate millions of source rows once and then serve indexed results to dashboards. <code>REFRESH MATERIALIZED VIEW</code> recomputes the result but can block readers, whereas <code>REFRESH MATERIALIZED VIEW CONCURRENTLY</code> allows readers to continue accessing the existing result during the refresh and requires a suitable unique index. When full recomputation becomes too expensive, an incremental rollup table can instead recompute only a recent time window and use an upsert to replace the affected summaries. This makes the cost of each refresh depend primarily on the changed window rather than the entire historical dataset.<br />Production view systems also require operational discipline. View dependencies should be inspected before schema changes, definitions should remain in source control rather than existing only inside the database, and reporting systems should expose the freshness of materialized results through fields such as <code>refreshed_at</code> and refresh logs. Common mistakes include using <code>SELECT *</code> inside views, creating excessive layers of nested views, forgetting to refresh materialized views, refreshing without <code>CONCURRENTLY</code> when reader availability matters, hiding important business logic exclusively inside database objects, and using <code>CASCADE</code> without checking dependencies. The practical decision is straightforward: use a view when you need a reusable, always-current query definition; a materialized view when an expensive result can tolerate scheduled refreshes; an incremental rollup table when only a bounded recent window changes; and row-level security when tenant isolation must be enforced at the table level.</p>



<figure class="wp-block-embed is-type-rich is-provider-embed wp-block-embed-embed"><div class="wp-block-embed__wrapper">
<a href="https://docs.google.com/presentation/d/e/2PACX-1vTTyHIjxEoLihpj7Er8mG5PggkoaWnW0fpiN2oBbpfjIXCtS5MCvmPkS7CPXqbnbQ/pub?start=true&#038;loop=true&#038;delayms=10000" rel="nofollow">https://docs.google.com/presentation/d/e/2PACX-1vTTyHIjxEoLihpj7Er8mG5PggkoaWnW0fpiN2oBbpfjIXCtS5MCvmPkS7CPXqbnbQ/pub?start=true&#038;loop=true&#038;delayms=10000</a>
</div></figure>



<iframe src="https://docs.google.com/presentation/d/e/2PACX-1vTTyHIjxEoLihpj7Er8mG5PggkoaWnW0fpiN2oBbpfjIXCtS5MCvmPkS7CPXqbnbQ/pubembed?start=true&#038;loop=true&#038;delayms=10000" frameborder="0" width="800" height="375" marginheight="0" marginwidth="0" allowfullscreen="true" mozallowfullscreen="true" webkitallowfullscreen="true"></iframe>
]]></content:encoded>
					
					<wfw:commentRss>https://decisionstats.com/2026/08/10/sql-views-materialized-views-designing-securing-and-optimizing-database-reporting/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">14612</post-id>
		<media:content url="https://2.gravatar.com/avatar/283eba774214f34e58e5bc32c2ce8d9a28f5ab203bfa2c074415f226f01478af?s=96&#38;d=wavatar&#38;r=G" medium="image">
			<media:title type="html">aviralgupta0310</media:title>
		</media:content>
	</item>
		<item>
		<title>SQL Transactions &#038; Concurrency: ACID, Isolation Levels, Locking, Deadlocks and Safe Patterns</title>
		<link>https://decisionstats.com/2026/08/10/sql-transactions-concurrency-acid-isolation-levels-locking-deadlocks-and-safe-patterns/</link>
					<comments>https://decisionstats.com/2026/08/10/sql-transactions-concurrency-acid-isolation-levels-locking-deadlocks-and-safe-patterns/#respond</comments>
		
		<dc:creator><![CDATA[Aviral Gupta]]></dc:creator>
		<pubDate>Mon, 10 Aug 2026 06:30:36 +0000</pubDate>
				<category><![CDATA[Analytics]]></category>
		<category><![CDATA[data]]></category>
		<category><![CDATA[sql]]></category>
		<guid isPermaLink="false">http://decisionstats.com/?p=14610</guid>

					<description><![CDATA[SQL transactions provide the foundation for reliable database operations by grouping multiple statements into a single logical unit of work. The ACID properties describe the guarantees that make transactions dependable: atomicity ensures that all statements succeed or none do, consistency preserves database constraints, isolation controls what concurrent transactions can observe, and durability ensures committed changes &#8230; <a href="https://decisionstats.com/2026/08/10/sql-transactions-concurrency-acid-isolation-levels-locking-deadlocks-and-safe-patterns/" class="more-link">Continue reading<span class="screen-reader-text"> "SQL Transactions &#38; Concurrency: ACID, Isolation Levels, Locking, Deadlocks and Safe&#160;Patterns"</span></a>]]></description>
										<content:encoded><![CDATA[
<h2 class="wp-block-heading"></h2>



<p class="wp-block-paragraph">SQL transactions provide the foundation for reliable database operations by grouping multiple statements into a single logical unit of work. The ACID properties describe the guarantees that make transactions dependable: atomicity ensures that all statements succeed or none do, consistency preserves database constraints, isolation controls what concurrent transactions can observe, and durability ensures committed changes survive failures. Transaction boundaries are controlled with <code>BEGIN</code>, <code>COMMIT</code>, and <code>ROLLBACK</code>, while <code>SAVEPOINT</code> enables partial rollback inside a larger transaction. Keeping transactions short is equally important because long-running transactions can retain locks, increase contention, and prevent old row versions from being cleaned up efficiently.<br />Concurrency becomes difficult when multiple transactions access the same data simultaneously. Common anomalies include dirty reads, non-repeatable reads, phantom reads, lost updates, and write skew. Database isolation levels determine which of these effects are prevented. <code>READ COMMITTED</code> is commonly appropriate for ordinary OLTP workloads, while <code>REPEATABLE READ</code> provides a consistent snapshot across multiple statements and is useful for multi-query reports. <code>SERIALIZABLE</code> provides the strongest isolation by making concurrent execution behave as though transactions were executed one after another, but conflicting transactions may be aborted and therefore require application-level retry logic. The exact behaviour differs across database engines, so applications should never assume that the default isolation level is universal.<br />Explicit locking is essential when correctness depends on reading a value and then making a decision based on it. <code>SELECT ... FOR UPDATE</code> locks selected rows until the transaction ends, preventing another transaction from modifying them concurrently. In simpler cases, an atomic statement such as <code>UPDATE items SET stock = stock - 1 WHERE id = 5 AND stock &gt; 0</code> is even better because the database performs the decision and modification as one operation. <code>NOWAIT</code> can fail immediately instead of waiting for a lock, while <code>SKIP LOCKED</code> allows workers to ignore already-claimed rows and is particularly useful for database-backed job queues. Deadlocks occur when transactions wait on each other in a cycle; the standard defence is to acquire locks in a deterministic order, keep transactions short, and retry the transaction that the database chooses as the deadlock victim.<br />Safe concurrent writes also require avoiding application-level race conditions. A classic check-then-insert pattern can allow two clients to observe that a record does not exist and then both attempt to insert it. Database-enforced uniqueness combined with <code>INSERT ... ON CONFLICT</code> or <code>MERGE</code> allows the database to resolve that race atomically. Idempotency keys provide another important pattern: a unique key associated with a request allows retries to become harmless no-ops rather than duplicate payments or operations. For background processing, <code>FOR UPDATE SKIP LOCKED</code> can be combined with a status column to let multiple workers claim different jobs without blocking one another. Optimistic concurrency using a version column is preferable for long-lived user interactions, while pessimistic locking with <code>FOR UPDATE</code> is better suited to short, high-contention operations such as inventory or stock decrements.<br />The central principle of SQL concurrency is to make correctness explicit rather than relying on timing or assumptions. Transactions should be opened as late as possible, perform the required database work, and commit immediately; applications should never wait for user input or external network calls while holding database locks. A robust money-transfer transaction, for example, can lock both accounts in deterministic order, verify that the source balance is sufficient, perform the debit and credit, and write the audit record within the same transaction so the audit cannot exist independently of the transfer. Production systems should combine atomic updates, appropriate isolation, deterministic lock ordering, unique constraints, idempotency keys, retry handling, and monitoring for blocked or idle-in-transaction sessions. Together, these patterns turn concurrency from a source of intermittent bugs into a deliberately controlled part of database design.</p>



<figure class="wp-block-embed is-type-rich is-provider-embed wp-block-embed-embed"><div class="wp-block-embed__wrapper">
<a href="https://docs.google.com/presentation/d/e/2PACX-1vRayDSA4uqmBs4DxcsIHqUUWbqRr2ouIuxCoyHEgL8whEpj74DwmcriTKGSWYALqg/pub?start=true&#038;loop=true&#038;delayms=10000" rel="nofollow">https://docs.google.com/presentation/d/e/2PACX-1vRayDSA4uqmBs4DxcsIHqUUWbqRr2ouIuxCoyHEgL8whEpj74DwmcriTKGSWYALqg/pub?start=true&#038;loop=true&#038;delayms=10000</a>
</div></figure>



<iframe src="https://docs.google.com/presentation/d/e/2PACX-1vRayDSA4uqmBs4DxcsIHqUUWbqRr2ouIuxCoyHEgL8whEpj74DwmcriTKGSWYALqg/pubembed?start=true&#038;loop=true&#038;delayms=10000" frameborder="0" width="800" height="375" marginheight="0" marginwidth="0" allowfullscreen="true" mozallowfullscreen="true" webkitallowfullscreen="true"></iframe>
]]></content:encoded>
					
					<wfw:commentRss>https://decisionstats.com/2026/08/10/sql-transactions-concurrency-acid-isolation-levels-locking-deadlocks-and-safe-patterns/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">14610</post-id>
		<media:content url="https://2.gravatar.com/avatar/283eba774214f34e58e5bc32c2ce8d9a28f5ab203bfa2c074415f226f01478af?s=96&#38;d=wavatar&#38;r=G" medium="image">
			<media:title type="html">aviralgupta0310</media:title>
		</media:content>
	</item>
	</channel>
</rss>
