<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Matteo Ferrando on Medium]]></title>
        <description><![CDATA[Stories by Matteo Ferrando on Medium]]></description>
        <link>https://medium.com/@chamini2?source=rss-c52d0358a0bc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*50Ha38U5rhC2e9S4.jpeg</url>
            <title>Stories by Matteo Ferrando on Medium</title>
            <link>https://medium.com/@chamini2?source=rss-c52d0358a0bc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 04:06:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@chamini2/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Average response time with Postgres Window Functions and CTEs]]></title>
            <link>https://medium.com/@chamini2/average-response-time-with-postgres-window-functions-and-ctes-a19adb7ed4f7?source=rss-c52d0358a0bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/a19adb7ed4f7</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[window-functions]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[development]]></category>
            <dc:creator><![CDATA[Matteo Ferrando]]></dc:creator>
            <pubDate>Mon, 31 Jul 2017 01:32:28 GMT</pubDate>
            <atom:updated>2019-04-05T14:16:19.072Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-sa/4.0/</cc:license>
            <content:encoded><![CDATA[<p><a href="https://medium.com/zomoz">zomoz</a> was a peer-to-peer platform designed to connect you to the people doing amazing things you thought were out of reach but should be (and really are) available to everyone.</p><p>Since about a year, one of the biggest features we have focused on has been the chat. We offer users (clients) the ability to chat directly with the person offering the activity (hosts); we do not have a strict separation between clients and hosts, any user can act as both. So, for incentivizing hosts to respond quickly and inviting users to write more often, we were asked to start showing the <strong>average response time for the hosts</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*Xs3a8KHqE8DdfCtbaUoA0g.png" /></figure><p>This is what it looks like on our platform, <em>“</em>⏰ <em>Matteo takes around 3 minutes to respond”</em>. This was the task that made Window Functions <em>click</em> for me, that is why I thought it would be good to share my experience.</p><h3>Setup</h3><h4>Schema</h4><p>I will specify a schema that resembles the one we have but with just enough to specify the problem and solution. This may give you some ideas on how you can model a chat, in case you are wondering on how to do that too! By the way, we use Postgres 9.6.</p><p>First, we have a chats table to specify the users involved in the chat. In our production chats table, we also store the timestamp each user last opened the chat to calculate how many unread messages they have for a chat, but that is not relevant to our current problem.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/44b079e68e28599c500fecf8eb7a9e5c/href">https://medium.com/media/44b079e68e28599c500fecf8eb7a9e5c/href</a></iframe><p>Notice that I did not create a surrogate primary key but identified each row by the client <strong>and </strong>host. Then, a chat has many messages, which are all sent by the two users of the chat.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4fa98f5360129eed6ae1739de82813ac/href">https://medium.com/media/4fa98f5360129eed6ae1739de82813ac/href</a></iframe><h4>Data</h4><p>Now, let’s get some values. Each following chat matches a case to analyze. Starting with a chat where the host is the last one to send a message.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1e55e6d0efb42fcabf3b5b36d7e4b8f0/href">https://medium.com/media/1e55e6d0efb42fcabf3b5b36d7e4b8f0/href</a></iframe><p>Next, a chat where the client is the last one.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6406b2be5bed45823fdedaefee1bf09e/href">https://medium.com/media/6406b2be5bed45823fdedaefee1bf09e/href</a></iframe><p>And finally, a client who never got an answer.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/81f99180808bd669cb32ade41c01edf8/href">https://medium.com/media/81f99180808bd669cb32ade41c01edf8/href</a></iframe><h3>Rules</h3><p>Looking at the data, we can see that chats may have sequential messages from the same sender; let’s call these <em>threads</em> of messages. The rules for calculating the <em>average response time</em> we set are as follows:</p><ol><li>Get the <strong>first </strong>sent_at<strong> </strong>value for all threads.</li><li>Subtract the sent_at of each thread with the one preceding it, to get the <em>interval</em> of time that passed between the two.</li><li>Calculate the average of the intervals for the hosts.</li><li>If a client never got an answer to his first thread (the chats only has messages by the client), consider the interval as the current time subtracted from the sent_at of the client’s thread; that is, consider this interval as if the host were to answer <strong>right now</strong>.</li></ol><p>For doing this, we will rely on Postgres <a href="https://www.postgresql.org/docs/current/static/functions-window.html">Window Functions</a>. We will also use <a href="https://www.postgresql.org/docs/current/static/queries-with.html">Common Table Expressions (</a><a href="https://www.postgresql.org/docs/current/static/queries-with.html">WITH clauses)</a> to make reasoning about these concepts easier.</p><h3>Solution</h3><p>First, this is the data after insertion:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1db5d9f94fecdd0f591f2819b45c74b5/href">https://medium.com/media/1db5d9f94fecdd0f591f2819b45c74b5/href</a></iframe><p>We will not fetch the content column from now on since it makes the output harder to read and is of no value for this exercise. Let’s define a window that <em>partitions</em> (think of GROUP BY) the data by chat (i.e. by client and host), and orders the messages for each partition by sent_at.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/177c4295ee05c7d99948015dfa7a8cad/href">https://medium.com/media/177c4295ee05c7d99948015dfa7a8cad/href</a></iframe><p>Now we will use this window to apply a window function that <em>lags behind (</em>called lag) to get information about the previous message.</p><p><em>Note: I will identify modified or new lines of the statement with </em><em>-- *** at the end.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d953c48827827c28f751fe941c58fadf/href">https://medium.com/media/d953c48827827c28f751fe941c58fadf/href</a></iframe><p>As you can see, what this window function does is return the same query, but with a column lag that shows the specified value (client, host, sender) for the <strong>previous row</strong>, that is why the first row (message) of each partition (chat) has NULL, there was no previous row to get the value from.</p><p>With these values, we can identify each thread by comparing the current (client, host, sender) with the previous one.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c6a3fb8e529f1b81480a023632f5a18e/href">https://medium.com/media/c6a3fb8e529f1b81480a023632f5a18e/href</a></iframe><p>Now we know which messages are the start of a thread. This is where CTEs come in, we will abstract this table in a WITH clause to then get only the rows that are thread_start.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c5cb3c1d278cf15c2a44d91f2825b7cb/href">https://medium.com/media/c5cb3c1d278cf15c2a44d91f2825b7cb/href</a></iframe><p>Now, we have filtered only messages that are thread_start, and then, windowed these rows per chat again to apply lead (the opposite of lag) to get the next row’s sent_at. Note that we abstracted the thread_start information in a WITH clause called thread_starts. Also, notice that the rows with NULL responded_at values are threads that were never answered. We will abstract this table again in a CTE.</p><p>With this, we have enough information to get the average interval a host takes to respond. We filter the messages that the host received, to average the time they took to respond these messages.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/73c55bbc2e82b18f8b5fe36e033a4ec8/href">https://medium.com/media/73c55bbc2e82b18f8b5fe36e033a4ec8/href</a></iframe><p>We are almost there, notice how the host 3 does not have an avg_response_time, well this is because they just never answered the client. This is related to the rule 4:</p><blockquote>…consider this interval as if the host were to answer <strong>right now</strong>.</blockquote><p>So we need will add a coalesce for when responded_at is NULL.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/258369778bb1e252597e9e4be6fb7fad/href">https://medium.com/media/258369778bb1e252597e9e4be6fb7fad/href</a></iframe><p><em>Note: Keep in mind that the </em><em>avg_response_time for the host </em><em>3 will change because it depends on </em><em>CURRENT_TIMESTAMP.</em></p><p>But now the avg_response_time for the host 2 has changed even though they never missed to answer a chat. What is happening here is that when a client is the last one to message, it’s responded_at is NULL and its interval is the CURRENT_TIMESTAMP — sent_at. We need to keep track of which threads were <strong>never</strong> answered; we will do this by adding a new window function to thread_responses.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/52451fab3c7c9cbd4a84a21925c3a14a/href">https://medium.com/media/52451fab3c7c9cbd4a84a21925c3a14a/href</a></iframe><p>We count the threads in a chat and only use CURRENT_TIMESTAMP — sent_at when the client never got an answer (threads = 1).</p><p>As you can see in thread_responses, I added another window, unordered, why would we need the same partitions but one with ORDER BY and one without? Applying count as a window function on an ordered partition does the count in a progressive manner, leaving <em>the count so far</em> for each row it processes; instead, by applying the count without an ORDER BY we get the result of counting all rows at once, instead of sequentially (read more about it <a href="https://www.postgresql.org/docs/9.6/static/sql-expressions.html#SYNTAX-WINDOW-FUNCTIONS">here</a>).</p><h3>Conclusion and future work</h3><p>We were able to get the average response time of hosts using Window Functions and CTEs. This solution is adapted to our specific problem and needs; but still, is a good use case to illustrate the power of Window Functions.</p><p>A problem with this solution is that if a client messages last, this interval is not considered in the average; but if they ever resume the conversation, the time passed will be considered for the average, <em>hurting</em> the average response time of the host. This could be handled by somehow identifying when a conversation has ended and a new one has started in the same chat.</p><p><em>PD: I asked in Stack Exchange’s Database Administrators site, you can see the original question </em><a href="https://dba.stackexchange.com/questions/176221/window-function-to-merge-rows-that-meet-a-condition"><em>here</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a19adb7ed4f7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>