Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will row_number() always break ties in the same way?

Tags:

sql

oracle

Will the function row_number() always sort the same data in the same way?

like image 559
esa606 Avatar asked Dec 24 '14 19:12

esa606


People also ask

How does row number handle ties?

ROW_NUMBER will always generate unique values without any gaps, even if there are ties. RANK can have gaps in its sequence and when values are the same, they get the same rank. DENSE_RANK also returns the same rank for ties, but doesn't have any gaps in the sequence.

What is the difference between rank () and ROW_NUMBER ()?

The ROW_NUMBER() function is self-explanatory, as you've already seen the data. It simply assigns a consecutive ranking to each row ordered by revenue. If two rows have the same value, they won't have the same ranking. The RANK() function creates a ranking of the rows based on the provided columns.

What does ROW_NUMBER () do in SQL?

ROW_NUMBER function is a SQL ranking function that assigns a sequential rank number to each new record in a partition. When the SQL Server ROW NUMBER function detects two identical values in the same partition, it assigns different rank numbers to both.

Does ROW_NUMBER require ORDER BY?

The ORDER BY clause determines the sequence in which the rows are assigned their unique ROW_NUMBER within a specified partition. It is required.


1 Answers

No. Ordering in SQL is unstable, meaning that the original sort order is not preserved. There is no guarantee that an analytic function or order by will return the results in the same order for the same key values.

You can always add a unique id as the last key in the sort to make it reproducible.

EDIT:

Note: the non-reproduciblity of order by is part of the SQL standard. Oracle documentation does not specify otherwise. And, in general, I ordering is usually not stable in databases (for equivalent key values). I would expect row_number() to behave the same way.

If you need things in a particular order, you can add rowid to the order by clause (see here). In fact, rowid may solve your problem without row_number().

like image 159
Gordon Linoff Avatar answered Oct 29 '22 08:10

Gordon Linoff