2

I have a table named "Orders" with 1-1000 rows and 3 columns (S.no, Order and Status). I need to fetch Order from 50-1000 which has its Status as "Cancelled". How can i do this in SQL Server?

potashin
  • 44,205
  • 11
  • 83
  • 107
Assassin
  • 215
  • 1
  • 4
  • 13
  • Orders with S.no range 50-1000. You can take it as OrderID – Assassin Apr 12 '14 at 16:27
  • 1
    In that case, all four answers below are correct. Just pick whatever it easiest for you to maintain (if your data were huge, you might want to look at performance differences of BETWEEN vs >= AND <, and make sure none apply... but this is not much data. Just pick what's easiest to maintain – Evan Volgas Apr 12 '14 at 16:37
  • @Manish Sahni : Have you succeeded? – potashin Apr 12 '14 at 16:49
  • 1
    @evanv: `BETWEEN` has no difference in performance vs. using `>=` and `<=` – ypercubeᵀᴹ Apr 12 '14 at 18:08

4 Answers4

3

Logic operator:

SELECT Order 
FROM Orders 
WHERE Status = 'Cancelled'
  AND (S.no > 50 AND S.no < 1000)

BETWEEN:

SELECT Order 
FROM Orders 
WHERE Status = 'Cancelled'
  AND (S.no BETWEEN 50 and 1000)
potashin
  • 44,205
  • 11
  • 83
  • 107
2

You can try something like this:

SELECT *
FROM Orders
WHERE (S.no BETWEEN 50 AND 1000) AND (Status = 'Cancelled')

Hope this helps

Milica Medic Kiralj
  • 3,580
  • 31
  • 31
2
select *
  from orders
 where no between 50 and 1000
   and status = 'Cancelled'

Assuming you meant to say that the column was named "no". S.no would not be a valid column name.

Brian DeMilia
  • 13,103
  • 1
  • 23
  • 33
0

If you're using SQL Server, you don't have access to Limit and Offset (unless that's changed in the last year or so, in which case please someone correct me).

There's a really nice generalizable solution discussed here: Equivalent of LIMIT and OFFSET for SQL Server?

I'd definitely take a look at that. If indeed your s_no values range from 1-1000, then the solution above by Notulysses should work just fine. But if you don't have so_no between 1-1000 (or in some other easy to filter way) then check out the solution linked to above. If you can what Notulysses recommended, go for it. If you need a generalizable solution, the one above is very good. I've also copied it below, for reference

  ;WITH Results_CTE AS
(
    SELECT
        Col1, Col2, ...,
        ROW_NUMBER() OVER (ORDER BY SortCol1, SortCol2, ...) AS RowNum
    FROM Table
    WHERE <whatever>
)
SELECT *
FROM Results_CTE
WHERE RowNum >= @Offset
AND RowNum < @Offset + @Limit
Community
  • 1
  • 1
Evan Volgas
  • 2,900
  • 3
  • 19
  • 30
  • Milica's answer is also good, if your so_no is easily filterable like that (or if you have an auto increment column that accurately orders your order numbers) – Evan Volgas Apr 12 '14 at 16:34