Skip to main content

Posts

Showing posts from November, 2015

The Difference Between ROW_NUMBER(), RANK(), and DENSE_RANK()

One of the most obvious and useful set of window functions are ranking functions where rows from your result set are ranked according to a certain scheme. There are three ranking functions: ROW_NUMBER() RANK() DENSE_RANK() The difference is easy to remember. For the examples, let’s assume we have this table (using PostgreSQL syntax): 1 2 3 4 5 CREATE TABLE t(v) AS SELECT * FROM (    VALUES ( 'a' ),( 'a' ),( 'a' ),( 'b' ),          ( 'c' ),( 'c' ),( 'd' ),( 'e' ) ) t(v) ROW_NUMBER() … assigns unique numbers to each row within the  PARTITION  given the ORDER BY  clause. So you’d get: 1 2 SELECT v, ROW_NUMBER() OVER() FROM t Note that some SQL dialects (e.g. SQL Server) require an explicit  ORDER BY clause in the  OVER()  clause: 1 2 SELECT v, ROW_NUMBER() OVER( ORDER BY v) FROM t The above query returns: | V | ROW_NUMBER | |---|-------