A week ago, I was asked to write a query to return rows between 30 and 40 of a particular ID column of a particular table and the result set should be sorted. There are 4 different ways of achieving this:
For this example, I took the products table from Northwind database.
For this example, I took the products table from Northwind database.
Method 1: Using the between keyword
select productid, productname from Products where ProductID between 30 and 40
Method 2: Using the except keyword (set theory)
select productid, productname from Products where ProductID < 41 except
select productid, productname from Products where ProductID < 30 order
select productid, productname from Products where ProductID < 30 order
Method 3: Using ranking function and a subquery
select temp1.rownum, temp1.ProductName from (select ROW_NUMBER()
over(order by productId desc) as rownum, ProductName
from Products) as temp1 where temp1.rownum between 30 and 40
over(order by productId desc) as rownum, ProductName
from Products) as temp1 where temp1.rownum between 30 and 40
Method 4: Using CTE and ranking function
with temp as
(
select ROW_NUMBER() over(order by productId desc) as rownum, ProductName
from Products
)
select * from temp where rownum between 30 and 40
(
select ROW_NUMBER() over(order by productId desc) as rownum, ProductName
from Products
)
select * from temp where rownum between 30 and 40
To do:
Analysis the performance on a large dataset and compare efficiencies
Analysis the performance on a large dataset and compare efficiencies
No comments:
Post a Comment