Tuesday, September 22, 2015

@Rank vs @Row_Number

So recently I was asked the difference between the two and my brain froze.  There are other phrases that come to mind, but the condition of frozen brain is more PC and I'm sticking to it.

Back on topic; SQL provides a few "Ranking Functions" that can be most helpful.  There is a subtle difference between @Rank and @Row_Number I will try to demonstrate here, starting with a table called "Inventory".  For purposes of demonstration, we will assume that we can have multiple records of the same inventory item at the same location with the same quantity.  Here is the Inventory table:


The following SQL exposes the difference in the two functions:

select recordid, productid, description, location, quantity
,rank() over (partition by produtctid order by quantity desc) as rank
,row_number() over (partition by productid order by quantity desc) as row_number
from inventory

Results:

Highlighted above are the @Rank and @Row_Number for ProductID 101 at Location 1. 
Notice, that for every Product 101 at Location 1 that @Row_Number increments by 1.
@Rank, in comparison, does not. Duplicates do not cause @Rank to increment.  On rows 1 and 2, the value of @Rank is 1 - these are the number 1 values.  ODDLY though, if we look on rows 3 and 4 (also duplicate records) we see that @Rank continues with a value of 3.  This is because there are 2 records in ahead of it.

Conclusion:  @Rank and @Row_Number have different outcomes when duplicate values are present for the Partition By and Order By clauses.  


Monday, September 21, 2015

All About SQL Joins

For purposes of demonstration, lets imagine we have a zoo.
The zoo database has a table of animals it keeps named Animals.
It also has a table of the soft stuffed animals it sells in the Products table.

You have been asked to provide the following:

Find each Animal where there is not a corresponding Product:

Select A.*, P.*
from Animal A
left join Product P
on A.Animal = P.Product
where P.Product is null



Find all the Animals where there is not a corresponding Product
AND all the Products where there is not a corresponding Animal

Select A.*, P.*
from Product P
full join Animal A
on P.Product = A.Animal
where A.Animal is null or P.Product is null



Find each Animal at the zoo where there is also a corresponding Product:


select A.*, P.*
from Animal A
join Product P
on A.Animal = P.Product




Find each Animal at the zoo and also each Product whether there is a match or not:

Select A.*, P.*
from Animal A
Full join Product P
on A.Animal = P.Product