Introduction to Window Functions
Discover the window functions available in MySQL.
We'll cover the following...
SQL allows us to read a table using TABLE, select rows with a suitable WHERE clause, or groups of rows based on common criteria with GROUP BY. By those means, we can get only so far, though. For example, let us consider a scenario where an SQL table records the timestamps of a user’s session on a website:
It is fairly easy for us to answer the following questions using one of the three approaches mentioned above:
However, the following question is surely more difficult to answer: what is the average time between the sessions of the user with user_id = 2? That is because we are looking for information that is not explicitly represented in Log, i.e., for the difference between log_out and log_in for each pair of adjacent sessions. While we can handle implicit information about groups of rows with the GROUP BY clause, there is no criterion in Log that would allow us to form pairs of adjacent sessions since they are not ordered within the table. So, how do we establish such an order to access rows based on it?
Row-based queries
To establish an order in Log ...