Open a section to study the full text and its source attribution. Course links open the assigned section directly.
3 . 4 Discussion and Exercises
Assigned source reading · Pat Morin
Pat Morin — Open Data Structures, pseudocode edition 0.1G
Original source · Creative Commons Attribution 2.5 Canada · Retrieved October 25, 2026.
Changes: site navigation and active scripts removed; relative links made absolute; one default code framework retained where parallel alternatives existed. The instructional text is attributed source material, separate from original Academy teaching. No publisher endorsement is implied.
Both singly-linked and doubly-linked lists are established techniques,
having been used in programs for over 40 years. They are discussed,
for example, by Knuth [46, Sections 2.2.3-2.2.5]. Even the
SEList data structure seems to be a well-known data structures exercise.
The SEList is sometimes referred to as an unrolled linked list
[67].
Another way to save space in a doubly-linked list is to use
so-called XOR-lists.
In an XOR-list, each node,
, contains only one
pointer, called
, that holds the bitwise exclusive-or of
and
. The list itself needs to store two pointers, one to the
node and one to
(the first node, or
if the list is
empty). This technique uses the fact that, if we have pointers to
and
, then we can extract
using the formula
(Here ^ computes the bitwise exclusive-or of its two arguments.)
This technique complicates the code a little and is not possible in
some languages, like Java and Python, that have garbage collection but gives a
doubly-linked list implementation that requires only one pointer per node.
See Sinha's magazine article [68] for a detailed discussion of
XOR-lists.
Exercise 3..1
Why is it not possible to use a dummy node in an SLList to avoid
all the special cases that occur in the operations

,

,

, and

?
Exercise 3..2
Design and implement an SLList method,

, that returns
the second-last element of an SLList. Do this without using the
member variable,

, that keeps track of the size of the list.
Exercise 3..3
Implement the List operations

,

,

and

on an SLList. Each of these operations
should run in

time.
Exercise 3..4
Design and implement an SLList method,

that reverses the
order of elements in an SLList. This method should run in

time, should not use recursion, should not use any secondary data
structures, and should not create any new nodes.
Exercise 3..5
Design and implement SLList and DLList methods called

.
These methods walk through the list and count the number of nodes to
see if this matches the value,

, stored in the list. These methods
return nothing, but throw an exception if the size they compute does
not match the value of

.
Exercise 3..6
Try to recreate the code for the

operation that creates a
node,

, and adds it in a DLList just before the node

. Do not
refer to this chapter. Even if your code does not exactly match the
code given in this book it may still be correct. Test it and see if
it works.
The next few exercises involve performing manipulations on DLLists.
You should complete them without allocating any new nodes or temporary
arrays. They can all be done only by changing the
and
values of existing nodes.
Exercise 3..7
Write a DLList method

that returns

if the
list is a
palindrome,
i.e., the element at position

is equal to
the element at position

for all

.
Your code should run in

time.
Exercise 3..8
Implement a method

that ``rotates'' a DLList so that list
item

becomes list item

. This method should
run in

time and should not modify any nodes in
the list.
Exercise 3..9
Write a method,

, that truncates a DLList at position

. After executing this method, the size of the list will be

and
it should contain only the elements at indices

. The
return value is another DLList that contains the elements at indices

. This method should run in

time.
Exercise 3..10
Write a DLList method,

, that takes as an argument
a DLList,

, empties it and appends its contents, in order,
to the receiver. For example, if

contains

and

contains

, then after calling

,

will contain

and

will be empty.
Exercise 3..11
Write a method

that removes all the elements with odd-numbered
indices from a DLList and return a DLList containing these elements.
For example, if

, contains the elements

, then after
calling

,

should contain

and a list containing

should be returned.
Exercise 3..12
Write a method,

, that reverses the order of elements in
a DLList.
Exercise 3..13
This exercise walks you through an implementation of the merge-sort
algorithm for sorting a DLList, as discussed in Section
11.1.1.
- Write a DLList method called
.
This method takes the first node from
and appends it to the the
receiving list. This is equivalent to
,
except that it should not create a new node.
- Write a DLList static method,
, that takes two
sorted lists
and
, merges them, and returns a new sorted
list containing the result. This causes
and
to be emptied
in the proces. For example, if
contains
and
contains
, then this method returns a new list containing
.
- Write a DLList method
that sorts the elements
contained in the list using the merge sort algorithm.
This recursive algorithm works in the following way:
- If the list contains 0 or 1 elements then there is
nothing to do. Otherwise,
- Using the
method, split the list
into two lists of approximately equal length,
and
;
- Recursively sort
;
- Recursively sort
; and, finally,
- Merge
and
into a single sorted list.
The next few exercises are more advanced and require a clear
understanding of what happens to the minimum value stored in a Stack
or Queue as items are added and removed.
Exercise 3..14
Design and implement a MinStack data structure that can store
comparable elements and supports the stack operations

,

, and

, as well as the

operation, which
returns the minimum value currently stored in the data structure.
All operations should run in constant time.
Exercise 3..15
Design and implement a MinQueue data structure that can store
comparable elements and supports the queue operations

,

, and

, as well as the

operation, which
returns the minimum value currently stored in the data structure.
All operations should run in constant amortized time.
Exercise 3..16
Design and implement a MinDeque data structure that can store
comparable elements and supports all the deque operations

,

,

and

, and the

operation, which returns the minimum value currently stored in
the data structure. All operations should run in constant amortized
time.
The next exercises are designed to test the reader's understanding of
the implementation and analysis of the space-efficient SEList:
Exercise 3..17
Prove that, if an SEList is used like a Stack (so that the
only modifications to the SEList are done using

and

), then these
operations run in constant amortized time, independent of the value
of

.
Exercise 3..18
Design and implement of a version of an SEList that supports all
the Deque operations in constant amortized time per operation,
independent of the value of

.
Exercise 3..19
Explain how to use the bitwise exclusive-or operator,
^, to
swap the values of two

variables without using a third variable.
opendatastructures.org
11 . 1 Comparison-Based Sorting
Assigned source reading · Pat Morin
Pat Morin — Open Data Structures, pseudocode edition 0.1G
Original source · Creative Commons Attribution 2.5 Canada · Retrieved October 25, 2026.
Changes: site navigation and active scripts removed; relative links made absolute; one default code framework retained where parallel alternatives existed. The instructional text is attributed source material, separate from original Academy teaching. No publisher endorsement is implied.
Subsections
In this section, we present three sorting algorithms: merge-sort,
quicksort, and heap-sort. Each of these algorithms takes an input array
and sorts the elements of
into non-decreasing order in
(expected) time. These algorithms are all comparison-based.
These algorithms don't care what type
of data is being sorted; the only operation they do on the data is
comparisons using the
method. Recall, from Section 1.2.4,
that
returns a negative value if
, a positive
value if
, and zero if
.
11.1.1 Merge-Sort
The merge-sort algorithm is a classic example of recursive divide
and conquer:
If the length of
is at most 1, then
is already
sorted, so we do nothing. Otherwise, we split
into two halves,
and
.
We recursively sort
and
, and then we merge (the now sorted)
and
to get our fully sorted array
:
An example is shown in Figure 11.1.
Figure 11.1:
The execution of
|
|
Compared to sorting, merging the two sorted arrays
and
is
fairly easy. We add elements to
one at a time. If
or
is empty, then we add the next elements from the other (non-empty)
array. Otherwise, we take the minimum of the next element in
and
the next element in
and add it to
:
Notice that the
algorithm performs at most
comparisons before running out of elements in one of
or
.
To understand the running-time of merge-sort, it is easiest to think
of it in terms of its recursion tree. Suppose for now that
is a
power of two, so that
, and
is an integer.
Refer to Figure 11.2. Merge-sort turns the problem of
sorting
elements into two problems, each of sorting
elements.
These two subproblem are then turned into two problems each, for a total
of four subproblems, each of size
. These four subproblems become eight
subproblems, each of size
, and so on. At the bottom of this process,
subproblems, each of size two, are converted into
problems,
each of size one. For each subproblem of size
, the time
spent merging and copying data is
. Since there are
subproblems of size
, the total time spent working on problems
of size
, not counting recursive calls, is
Therefore, the total amount of time taken by merge-sort is
Figure 11.2:
The merge-sort recursion tree.
|
|
The proof of the following theorem is based on preceding analysis,
but has to be a little more careful to deal with the cases where
is not a power of 2.
Theorem 11..1
The merge_sort(a) algorithm runs in
time and
performs at most
comparisons.
Proof.
The proof is by induction on

. The base case, in which

,
is trivial; when presented with an array of length 0 or 1 the algorithm
simply returns without performing any comparisons.
Merging two sorted lists of total length
requires at most
comparisons. Let
denote the maximum number of comparisons performed by
on an array
of length
. If
is even, then we apply the inductive hypothesis to
the two subproblems and obtain
The case where

is odd is slightly more complicated. For this case,
we use two inequalities that are easy to verify:
 |
(11.1) |
for all

and
 |
(11.2) |
for all

. Inequality (
11.1) comes from the fact that

while (
11.2) follows from the fact that

is a concave function. With these tools in hand we have, for odd

,
The quicksort algorithm is another classic divide and conquer
algorithm. Unlike merge-sort, which does merging after solving the two
subproblems, quicksort does all of its work upfront.
Quicksort is simple to describe: Pick a random pivot element,
, from
; partition
into the set of elements less than
, the
set of elements equal to
, and the set of elements greater than
;
and, finally, recursively sort the first and third sets in this partition.
An example is shown in Figure 11.3.
Figure 11.3:
An example execution of
|
|
All of this is done in place, so that instead of making copies of
subarrays being sorted, the
method only sorts the
subarray
. Initially, this method is invoked
with the arguments
.
At the heart of the quicksort algorithm is the in-place partitioning
algorithm. This algorithm, without using any extra space, swaps elements
in
and computes indices
and
so that
This partitioning, which is done by the
loop in the code, works
by iteratively increasing
and decreasing
while maintaining the
first and last of these conditions. At each step, the element at position
is either moved to the front, left where it is, or moved to the back.
In the first two cases,
is incremented, while in the last case,
is not incremented since the new element at position
has not yet been
processed.
Quicksort is very closely related to the random binary search trees
studied in Section 7.1. In fact, if the input to quicksort consists
of
distinct elements, then the quicksort recursion tree is a random
binary search tree. To see this, recall that when constructing a random
binary search tree the first thing we do is pick a random element
and
make it the root of the tree. After this, every element will eventually
be compared to
, with smaller elements going into the left subtree
and larger elements into the right.
In quicksort, we select a random element
and immediately compare
everything to
, putting the smaller elements at the beginning of
the array and larger elements at the end of the array. Quicksort then
recursively sorts the beginning of the array and the end of the array,
while the random binary search tree recursively inserts smaller elements
in the left subtree of the root and larger elements in the right subtree
of the root.
The above correspondence between random binary search trees and quicksort
means that we can translate Lemma 7.1 to a statement about quicksort:
Lemma 11..1
When quicksort is called to sort an array containing the integers
, the expected number of times element
is compared
to a pivot element is at most
.
A little summing up of harmonic numbers gives us the following theorem
about the running time of quicksort:
Theorem 11..2
When quicksort is called to sort an array containing
distinct
elements, the expected number of comparisons performed is at most
.
Proof.
Let

be the number of comparisons performed by quicksort when sorting

distinct elements. Using Lemma
11.1 and linearity of
expectation, we have:
Theorem 11.3 describes the case where the elements being sorted are
all distinct. When the input array,
, contains duplicate elements,
the expected running time of quicksort is no worse, and can be even
better; any time a duplicate element
is chosen as a pivot, all
occurrences of
get grouped together and do not take part in either
of the two subproblems.
Theorem 11..3
The
method runs in
expected
time and the expected number of comparisons it performs is at most
.
11.1.3 Heap-sort
The heap-sort algorithm is another in-place sorting algorithm.
Heap-sort uses the binary heaps discussed in Section 10.1.
Recall that the BinaryHeap data structure represents a heap using
a single array. The heap-sort algorithm converts the input array
into a heap and then repeatedly extracts the minimum value.
More specifically, a heap stores
elements in an array,
, at array locations
with the smallest value stored at the root,
. After transforming
into a BinaryHeap, the heap-sort
algorithm repeatedly swaps
and
, decrements
, and
calls
so that
once again are
a valid heap representation. When this process ends (because
)
the elements of
are stored in decreasing order, so
is reversed
to obtain the final sorted order.11.1Figure 11.4 shows an example of the execution of
.
Figure 11.4:
A snapshot of the execution of
.
The shaded part of the
array is already sorted. The unshaded part is a BinaryHeap.
During the next iteration, element
will be placed into array
location
.
|
|
A key subroutine in heap sort is the constructor for turning
an unsorted array
into a heap. It would be easy to do this
in
time by repeatedly calling the BinaryHeap
method, but we can do better by using a bottom-up algorithm.
Recall that, in a binary heap, the children of
are stored at
positions
and
. This implies that the elements
have no children. In other
words, each of
is a sub-heap
of size 1. Now, working backwards, we can call
for
each
. This works, because by
the time we call
, each of the two children of
are the root of a sub-heap, so calling
makes
into the root of its own subheap.
The interesting thing about this bottom-up strategy is that it is more
efficient than calling
times. To see this, notice that,
for
elements, we do no work at all, for
elements, we call
on a subheap rooted at
and whose height is one, for
elements, we call
on a subheap whose height is two,
and so on. Since the work done by
is proportional to
the height of the sub-heap rooted at
, this means that the total
work done is at most
The second-last equality follows by recognizing that the sum
is equal, by definition of expected value,
to the expected number of times we toss a coin up to and including the
first time the coin comes up as heads and applying Lemma 4.2.
The following theorem describes the performance of
.
Theorem 11..4
The
method runs in
time and performs at
most
comparisons.
Proof.
The algorithm runs in three steps: (1) transforming

into a heap,
(2) repeatedly extracting the minimum element from

, and (3) reversing
the elements in

. We have just argued that step 1 takes

time and performs

comparisons. Step 3 takes

time and
performs no comparisons. Step 2 performs

calls to

.
The

th such call operates on a heap of size

and performs
at most

comparisons. Summing this over

gives
Adding the number of comparisons performed in each of the three steps
completes the proof.
We have now seen three comparison-based sorting algorithms that each run
in
time. By now, we should be wondering if faster
algorithms exist. The short answer to this question is no. If the
only operations allowed on the elements of
are comparisons, then no
algorithm can avoid doing roughly
comparisons. This is
not difficult to prove, but requires a little imagination. Ultimately,
it follows from the fact that
(Proving this fact is left as Exercise 11.10.)
We will start by focusing our attention on deterministic algorithms like
merge-sort and heap-sort and on a particular fixed value of
. Imagine
such an algorithm is being used to sort
distinct elements. The key
to proving the lower-bound is to observe that, for a deterministic
algorithm with a fixed value of
, the first pair of elements that are
compared is always the same. For example, in
, when
is even, the first call to
is with
and the
first comparison is between elements
and
.
Since all input elements are distinct, this first comparison has only
two possible outcomes. The second comparison done by the algorithm may
depend on the outcome of the first comparison. The third comparison
may depend on the results of the first two, and so on. In this way,
any deterministic comparison-based sorting algorithm can be viewed
as a rooted binary comparison tree.
Each internal node,
,
of this tree is labelled with a pair of indices
and
.
If
the algorithm proceeds to the left subtree,
otherwise it proceeds to the right subtree. Each leaf
of this
tree is labelled with a permutation
of
. This permutation represents the one that is
required to sort
if the comparison tree reaches this leaf. That is,
An example of a comparison tree for an array of size
is shown in
Figure 11.5.
Figure 11.5:
A comparison tree for sorting an array
of length
.
|
|
The comparison tree for a sorting algorithm tells us everything about
the algorithm. It tells us exactly the sequence of comparisons that
will be performed for any input array,
, having
distinct elements
and it tells us how the algorithm will reorder
in order to sort it.
Consequently, the comparison tree must have at least
leaves;
if not, then there are two distinct permutations that lead to the same
leaf; therefore, the algorithm does not correctly sort at least one of
these permutations.
For example, the comparison tree in Figure 11.6 has only
leaves. Inspecting this tree, we see that the two input arrays
and
both lead to the rightmost leaf. On the input
this leaf correctly outputs
. However, on the
input
, this node incorrectly outputs
.
This discussion leads to the primary lower-bound for comparison-based
algorithms.
Figure 11.6:
A comparison tree that does not correctly sort every input
permutation.
|
|
Theorem 11..5
For any deterministic comparison-based sorting algorithm
and any integer
, there exists an input array
of
length
such that
performs at least
comparisons when sorting
.
Proof.
By the preceding discussion, the comparison tree defined by

must have at least

leaves. An easy inductive proof shows that
any binary tree with

leaves has a height of at least

.
Therefore, the comparison tree for

has a leaf,

,
with a depth of at least

and there is an input array

that leads to this leaf. The input array

is an input for which

does at least

comparisons.
Theorem 11.5 deals with deterministic
algorithms like merge-sort and heap-sort, but doesn't tell us anything
about randomized algorithms like quicksort. Could a randomized algorithm
beat the
lower bound on the number of comparisons?
The answer, again, is no. Again, the way to prove it is to think
differently about what a randomized algorithm is.
In the following discussion, we will assume that our decision
trees have been ``cleaned up'' in the following way: Any node that can not
be reached by some input array
is removed. This cleaning up implies
that the tree has exactly
leaves. It has at least
leaves
because, otherwise, it could not sort correctly. It has at most
leaves since each of the possible
permutation of
distinct
elements follows exactly one root to leaf path in the decision tree.
We can think of a randomized sorting algorithm,
, as a
deterministic algorithm that takes two inputs: The input array
that should be sorted and a long sequence
of random real numbers in the range
. The random numbers provide
the randomization for the algorithm. When the algorithm wants to toss a
coin or make a random choice, it does so by using some element from
.
For example, to compute the index of the first pivot in quicksort,
the algorithm could use the formula
.
Now, notice that if we fix
to some particular sequence
then
becomes a deterministic sorting algorithm,
, that has an associated comparison tree,
. Next, notice that if we select
to be a random
permutation of
, then this is equivalent to selecting
a random leaf,
, from the
leaves of
.
Exercise 11.12 asks you to prove that, if we select
a random leaf from any binary tree with
leaves, then the expected
depth of that leaf is at least
. Therefore, the expected
number of comparisons performed by the (deterministic) algorithm
when given an input array containing a random
permutation of
is at least
. Finally,
notice that this is true for every choice of
, therefore it holds even for
. This completes the proof of the lower-bound for randomized algorithms.
Theorem 11..6
For any integer
and any (deterministic or randomized)
comparison-based sorting algorithm
, the expected number
of comparisons done by
when sorting a random permutation
of
is at least
.
Footnotes
- ... order.11.1
- The algorithm
could alternatively redefine the
function so that the
heap sort algorithm stores the elements directly in ascending order.
opendatastructures.org
2.5. Querying a Table #
Assigned source reading · The PostgreSQL Global Development Group and The Regents of the University of California
Portions Copyright © 1996–2026 The PostgreSQL Global Development Group. Portions Copyright © 1994 The Regents of the University of California.
Original source · PostgreSQL License · Retrieved October 25, 2026.
Changes: site navigation and active scripts removed; relative links made absolute; one default code framework retained where parallel alternatives existed. The instructional text is attributed source material, separate from original Academy teaching. No publisher endorsement is implied.
Full license and notices
License
PostgreSQL is released under the
PostgreSQL License
,
a liberal Open Source license, similar to the BSD or MIT licenses.
PostgreSQL Database Management System
(also known as Postgres, formerly as Postgres95)
Portions Copyright © 1996-2026, The PostgreSQL Global Development Group
Portions Copyright © 1994, The Regents of the University of California
Permission to use, copy, modify, and distribute this software and its
documentation for any purpose, without fee, and without a written agreement
is hereby granted, provided that the above copyright notice and this
paragraph and the following two paragraphs appear in all copies.
IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING
LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS
DOCUMENTATION, EVEN IF THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATIONS TO
PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
Will PostgreSQL ever be released under a different license?
The PostgreSQL Global Development Group remains committed to making
PostgreSQL available as free and open source software in perpetuity. There are
no plans to change the PostgreSQL License or release PostgreSQL under a
different license.
If you would like to read more about this topic, then please take a look at
the
mailing list archives
at one of the many discussions
on this subject.
To retrieve data from a table, the table is queried. An SQL SELECT statement is used to do this. The statement is divided into a select list (the part that lists the columns to be returned), a table list (the part that lists the tables from which to retrieve the data), and an optional qualification (the part that specifies any restrictions). For example, to retrieve all the rows of table weather, type:
SELECT * FROM weather;
Here * is a shorthand for “all columns”. So the same result would be had with:
SELECT city, temp_lo, temp_hi, prcp, date FROM weather;
The output should be:
city | temp_lo | temp_hi | prcp | date
---------------+---------+---------+------+------------
San Francisco | 46 | 50 | 0.25 | 1994-11-27
San Francisco | 43 | 57 | 0 | 1994-11-29
Hayward | 37 | 54 | | 1994-11-29
(3 rows)
You can write expressions, not just simple column references, in the select list. For example, you can do:
SELECT city, (temp_hi+temp_lo)/2 AS temp_avg, date FROM weather;
This should give:
city | temp_avg | date
---------------+----------+------------
San Francisco | 48 | 1994-11-27
San Francisco | 50 | 1994-11-29
Hayward | 45 | 1994-11-29
(3 rows)
Notice how the AS clause is used to relabel the output column. (The AS clause is optional.)
A query can be “qualified” by adding a WHERE clause that specifies which rows are wanted. The WHERE clause contains a Boolean (truth value) expression, and only rows for which the Boolean expression is true are returned. The usual Boolean operators (AND, OR, and NOT) are allowed in the qualification. For example, the following retrieves the weather of San Francisco on rainy days:
SELECT * FROM weather
WHERE city = 'San Francisco' AND prcp > 0.0;
Result:
city | temp_lo | temp_hi | prcp | date
---------------+---------+---------+------+------------
San Francisco | 46 | 50 | 0.25 | 1994-11-27
(1 row)
You can request that the results of a query be returned in sorted order:
SELECT * FROM weather
ORDER BY city;
city | temp_lo | temp_hi | prcp | date
---------------+---------+---------+------+------------
Hayward | 37 | 54 | | 1994-11-29
San Francisco | 43 | 57 | 0 | 1994-11-29
San Francisco | 46 | 50 | 0.25 | 1994-11-27
In this example, the sort order isn't fully specified, and so you might get the San Francisco rows in either order. But you'd always get the results shown above if you do:
SELECT * FROM weather
ORDER BY city, temp_lo;
You can request that duplicate rows be removed from the result of a query:
SELECT DISTINCT city
FROM weather;
city
---------------
Hayward
San Francisco
(2 rows)
Here again, the result row ordering might vary. You can ensure consistent results by using DISTINCT and ORDER BY together:
SELECT DISTINCT city
FROM weather
ORDER BY city;
3.5. Window Functions #
Assigned source reading · The PostgreSQL Global Development Group and The Regents of the University of California
Portions Copyright © 1996–2026 The PostgreSQL Global Development Group. Portions Copyright © 1994 The Regents of the University of California.
Original source · PostgreSQL License · Retrieved October 25, 2026.
Changes: site navigation and active scripts removed; relative links made absolute; one default code framework retained where parallel alternatives existed. The instructional text is attributed source material, separate from original Academy teaching. No publisher endorsement is implied.
Full license and notices
License
PostgreSQL is released under the
PostgreSQL License
,
a liberal Open Source license, similar to the BSD or MIT licenses.
PostgreSQL Database Management System
(also known as Postgres, formerly as Postgres95)
Portions Copyright © 1996-2026, The PostgreSQL Global Development Group
Portions Copyright © 1994, The Regents of the University of California
Permission to use, copy, modify, and distribute this software and its
documentation for any purpose, without fee, and without a written agreement
is hereby granted, provided that the above copyright notice and this
paragraph and the following two paragraphs appear in all copies.
IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING
LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS
DOCUMENTATION, EVEN IF THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATIONS TO
PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
Will PostgreSQL ever be released under a different license?
The PostgreSQL Global Development Group remains committed to making
PostgreSQL available as free and open source software in perpetuity. There are
no plans to change the PostgreSQL License or release PostgreSQL under a
different license.
If you would like to read more about this topic, then please take a look at
the
mailing list archives
at one of the many discussions
on this subject.
A window function performs a calculation across a set of table rows that are somehow related to the current row. This is comparable to the type of calculation that can be done with an aggregate function. However, window functions do not cause rows to become grouped into a single output row like non-window aggregate calls would. Instead, the rows retain their separate identities. Behind the scenes, the window function is able to access more than just the current row of the query result.
Here is an example that shows how to compare each employee's salary with the average salary in his or her department:
SELECT depname, empno, salary, avg(salary) OVER (PARTITION BY depname) FROM empsalary;
depname | empno | salary | avg
-----------+-------+--------+-----------------------
develop | 11 | 5200 | 5020.0000000000000000
develop | 7 | 4200 | 5020.0000000000000000
develop | 9 | 4500 | 5020.0000000000000000
develop | 8 | 6000 | 5020.0000000000000000
develop | 10 | 5200 | 5020.0000000000000000
personnel | 5 | 3500 | 3700.0000000000000000
personnel | 2 | 3900 | 3700.0000000000000000
sales | 3 | 4800 | 4866.6666666666666667
sales | 1 | 5000 | 4866.6666666666666667
sales | 4 | 4800 | 4866.6666666666666667
(10 rows)
The first three output columns come directly from the table empsalary, and there is one output row for each row in the table. The fourth column represents an average taken across all the table rows that have the same depname value as the current row. (This actually is the same function as the non-window avg aggregate, but the OVER clause causes it to be treated as a window function and computed across the window frame.)
A window function call always contains an OVER clause directly following the window function's name and argument(s). This is what syntactically distinguishes it from a normal function or non-window aggregate. The OVER clause determines exactly how the rows of the query are split up for processing by the window function. The PARTITION BY clause within OVER divides the rows into groups, or partitions, that share the same values of the PARTITION BY expression(s). For each row, the window function is computed across the rows that fall into the same partition as the current row.
You can also control the order in which rows are processed by window functions using ORDER BY within OVER. (The window ORDER BY does not even have to match the order in which the rows are output.) Here is an example:
SELECT depname, empno, salary,
row_number() OVER (PARTITION BY depname ORDER BY salary DESC)
FROM empsalary;
depname | empno | salary | row_number
-----------+-------+--------+------------
develop | 8 | 6000 | 1
develop | 10 | 5200 | 2
develop | 11 | 5200 | 3
develop | 9 | 4500 | 4
develop | 7 | 4200 | 5
personnel | 2 | 3900 | 1
personnel | 5 | 3500 | 2
sales | 1 | 5000 | 1
sales | 4 | 4800 | 2
sales | 3 | 4800 | 3
(10 rows)
As shown here, the row_number window function assigns sequential numbers to the rows within each partition, in the order defined by the ORDER BY clause (with tied rows numbered in an unspecified order). row_number needs no explicit parameter, because its behavior is entirely determined by the OVER clause.
The rows considered by a window function are those of the “virtual table” produced by the query's FROM clause as filtered by its WHERE, GROUP BY, and HAVING clauses if any. For example, a row removed because it does not meet the WHERE condition is not seen by any window function. A query can contain multiple window functions that slice up the data in different ways using different OVER clauses, but they all act on the same collection of rows defined by this virtual table.
We already saw that ORDER BY can be omitted if the ordering of rows is not important. It is also possible to omit PARTITION BY, in which case there is a single partition containing all rows.
There is another important concept associated with window functions: for each row, there is a set of rows within its partition called its window frame. Some window functions act only on the rows of the window frame, rather than of the whole partition. By default, if ORDER BY is supplied then the frame consists of all rows from the start of the partition up through the current row, plus any following rows that are equal to the current row according to the ORDER BY clause. When ORDER BY is omitted the default frame consists of all rows in the partition. Here is an example using sum:
SELECT salary, sum(salary) OVER () FROM empsalary;
salary | sum
--------+-------
5200 | 47100
5000 | 47100
3500 | 47100
4800 | 47100
3900 | 47100
4200 | 47100
4500 | 47100
4800 | 47100
6000 | 47100
5200 | 47100
(10 rows)
Above, since there is no ORDER BY in the OVER clause, the window frame is the same as the partition, which for lack of PARTITION BY is the whole table; in other words each sum is taken over the whole table and so we get the same result for each output row. But if we add an ORDER BY clause, we get very different results:
SELECT salary, sum(salary) OVER (ORDER BY salary) FROM empsalary;
salary | sum
--------+-------
3500 | 3500
3900 | 7400
4200 | 11600
4500 | 16100
4800 | 25700
4800 | 25700
5000 | 30700
5200 | 41100
5200 | 41100
6000 | 47100
(10 rows)
Here the sum is taken from the first (lowest) salary up through the current one, including any duplicates of the current one (notice the results for the duplicated salaries).
Window functions are permitted only in the SELECT list and the ORDER BY clause of the query. They are forbidden elsewhere, such as in GROUP BY, HAVING and WHERE clauses. This is because they logically execute after the processing of those clauses. Also, window functions execute after non-window aggregate functions. This means it is valid to include an aggregate function call in the arguments of a window function, but not vice versa.
If there is a need to filter or group rows after the window calculations are performed, you can use a sub-select. For example:
SELECT depname, empno, salary, enroll_date
FROM
(SELECT depname, empno, salary, enroll_date,
row_number() OVER (PARTITION BY depname ORDER BY salary DESC, empno) AS pos
FROM empsalary
) AS ss
WHERE pos < 3;
The above query only shows the rows from the inner query having row_number less than 3 (that is, the first two rows for each department).
When a query involves multiple window functions, it is possible to write out each one with a separate OVER clause, but this is duplicative and error-prone if the same windowing behavior is wanted for several functions. Instead, each windowing behavior can be named in a WINDOW clause and then referenced in OVER. For example:
SELECT sum(salary) OVER w, avg(salary) OVER w
FROM empsalary
WINDOW w AS (PARTITION BY depname ORDER BY salary DESC);
More details about window functions can be found in Section 4.2.8, Section 9.22, Section 7.2.5, and the SELECT reference page.