Getting limited result from oracle in order [duplicate] - sql

This question already has answers here:
How do I limit the number of rows returned by an Oracle query after ordering?
(14 answers)
Closed 8 years ago.
I have a set of 4000 records,I am only allowed to retrieve 300 records.
I am doing pagination on the resultset, but since we are limiting the result to 300 i am getting different results for each DB hit.
So is there any option to get the ordered first 300 of the 4000 records, without getting the entire result of 4000 records.
Below is the query:
select id from table where name='ronaldo' and rownum <= 300 order by id asc;

The problem is the query is processed in the following order:
The FROM/WHERE clause goes first.
ROWNUM is assigned and incremented to each output row from the FROM/WHERE clause.
SELECT is applied.
GROUP BY is applied.
HAVING is applied.
ORDER BY is applied.
For that reason, your query as written will return a random 300 records.
You'll need to do a nested query, something like this:
select * from
(select * from table
where name='ronaldo' order by id asc)
where ROWNUM <= 300;
Also, if you're using Oracle 12c or higher, you can use the completely non-standard FETCH FIRST syntax:
SELECT *
FROM table
WHERE name='ronaldo'
ORDER BY id asc
FETCH FIRST 300 ROWS ONLY;
Why they don't support the LIMIT keyword? Because they're Oracle.

Related

How could I query from the first n rows using SQL?

For example, I would like to query from the first 10 rows, how could I achieve that. (Not get the first 10 of the query results).
I tried using 'limit' first then 'where' but it doesn't work.
If I understand correctly you first want to fetch 10 rows of one query, then search within those 10 rows for data. To do that you can use a subquery:
SELECT *
FROM (SELECT *
FROM YOUR_TABLE yt
ORDER BY yt.SOME_COLUMN
LIMIT 10) sq
WHERE sq.SOME_OTHER_COLUMN > 25;
Best of luck.
Based on your sort criteria you can create a SQL like this
SELECT column1, column2, ...
FROM your table
ORDER BY sort column
LIMIT 10
This will give you the top 10 rows from your table based on your sort column

SQL Command error: Incorrect syntax near '4' [duplicate]

This question already has answers here:
LIMIT 10..20 in SQL Server
(15 answers)
Closed 5 years ago.
I get a "Incorrect syntax near '4'." while executing this command :
#"SELECT * FROM [Table] OFFSET 4 LIMIT 2;"
what is the probem here?
The SQL SELECT TOP Clause
The SELECT TOP clause is used to specify the number of records to return.
The SELECT TOP clause is useful on large tables with thousands of records. Returning a large number of records can impact on performance.
Note: Not all database systems support the SELECT TOP clause. MySQL
supports the LIMIT clause to select a limited number of records, while
Oracle uses ROWNUM.
SQL Server / MS Access Syntax:
SELECT TOP number|percent column_name(s)
FROM table_name
WHERE condition;
Example
SELECT TOP 2 *
FROM [Table]
There is no LIMIT in SQL Server. You use FETCH:
Without an ORDER BY, the OFFSET is meaningless, so you can just do
SELECT TOP 2 t.*
FROM [Table] t;
If you do have an ORDER BY:
SELECT t.*
FROM [Table] t
ORDER BY ?
OFFSET 4 ROWS FETCH FIRST 2 ROWS ONLY;
The ? is a placeholder for the name of the column you want to sort by.

How to select only 10 records from the table in jsp?

I'm try to select only 10 row from a table by using limit but it gives me an error,
My query is
SELECT *
FROM table_name
ORDER BY CUSTOMER
LIMIT 10
It gives an error :
ORA-00933: SQL command not properly ended
Can anyone guide me.
You can use ROWNUM :
SELECT *
FROM ( SELECT *
FROM table_name
ORDER BY CUSTOMER) t
WHERE ROWNUM <=10
For each row returned by a query, the ROWNUM pseudocolumn returns a number indicating the order in which Oracle selects the row from a table or set of joined rows. The first row selected has a ROWNUM of 1, the second has 2, and so on.
Or, since Oracle 12c r1, you can use FETCH :
SELECT *
FROM table_name
ORDER BY CUSTOMER
FETCH FIRST 10 ROWS ONLY
FETCH
Use this clause to specify the number of rows or percentage of rows to return. If you do not specify this clause, then all rows are returned, beginning at row offset + 1.
FIRST | NEXT
These keywords can be used interchangeably and are provided for semantic clarity.

Using rownum in oracle SQL statement in combination with order by clause

Which of the following two SQL statements will return the desired result set (i.e. the ten rows with Status=0 and the highest StartTimes)?
Will both statements always return the same result set (StartTime is unique)?
SELECT *
FROM MyTable
WHERE Status=0
AND ROWNUM <= 10
ORDER BY StartTime DESC
SELECT *
FROM (
SELECT *
FROM MyTable
WHERE Status=0
ORDER BY StartTime DESC
)
WHERE ROWNUM <= 10
Background
My DBAdmin told me that the first statement will first limit the table to 10 rows and than order those random rows by StartTime, which is definitly not what I want.
From what I learned in that answer, the order by clause of the second statement is redundant and could be removed by an optimizer, which is also not what I want.
I asked a similar question concering the limit clause in a query to a SQLite database and am interested in understanding any differences to the above statements (using limit Vs rownum) used with an oracle db.
Your Second Query will work
Because in the first ,the first ten rows with Status 0 are selected and then the order by is done in that case the first ten rows fetched need not be in the highest order

How to select first 'N' records from a database containing million records?

I have an oracle database populated with million records. I am trying to write a SQL query that returns the first 'N" sorted records ( say 100 records) from the database based on certain condition.
SELECT *
FROM myTable
Where SIZE > 2000
ORDER BY NAME DESC
Then programmatically select first N records.
The problem with this approach is :
The query results into half million
records and "ORDER BY NAME" causes
all the records to be sorted on NAME in the descending order. This sorting is taking lot of time. (nearly 30-40 seconds. If I omit ORDER BY, it takes only 1 second).
After the sort I am interested in
only first N (100) records. So the sorting of complete records is not useful.
My questions are:
Is it possible to specify the 'N' in
query itself? ( so that sort applies to only N records and query becomes faster).
Any better way in SQL to improve the query to sort
only N elements and return in quick
time.
If your purpose is to find 100 random rows and sort them afterwards then Lasse's solution is correct. If as I think you want the first 100 rows sorted by name while discarding the others you would build a query like this:
SELECT *
FROM (SELECT *
FROM myTable
WHERE SIZE > 2000 ORDER BY NAME DESC)
WHERE ROWNUM <= 100
The optimizer will understand that it is a TOP-N query and will be able to use an index on NAME. It won't have to sort the entire result set, it will just start at the end of the index and read it backwards and stop after 100 rows.
You could also add an hint to your original query to let the optimizer understand that you are interested in the first rows only. This will probably generate a similar access path:
SELECT /*+ FIRST_ROWS*/* FROM myTable WHERE SIZE > 2000 ORDER BY NAME DESC
Edit: just adding AND rownum <= 100 to the query won't work since in Oracle rownum is attributed before sorting : this is why you have to use a subquery. Without the subquery Oracle will select 100 random rows then sort them.
This shows how to pick the top N rows depending on your version of Oracle.
From Oracle 9i onwards, the RANK() and
DENSE_RANK() functions can be used to
determine the TOP N rows. Examples:
Get the top 10 employees based on
their salary
SELECT ename, sal FROM ( SELECT
ename, sal, RANK() OVER (ORDER BY sal
DESC) sal_rank
FROM emp ) WHERE sal_rank <= 10;
Select the employees making the top 10
salaries
SELECT ename, sal FROM ( SELECT
ename, sal, DENSE_RANK() OVER (ORDER
BY sal DESC) sal_dense_rank
FROM emp ) WHERE sal_dense_rank <= 10;
The difference between the two is explained here
Add this:
AND rownum <= 100
to your WHERE-clause.
However, this won't do what you're asking.
If you want to pick 100 random rows, sort those, and then return them, you'll have to formulate a query without the ORDER BY first, then limit that to 100 rows, then select from that and sort.
This could work, but unfortunately I don't have an Oracle server available to test:
SELECT *
FROM (
SELECT *
FROM myTable
WHERE SIZE > 2000
AND rownum <= 100
) x
ORDER BY NAME DESC
But note the "random" part there, you're saying "give me 100 rows with SIZE > 2000, I don't care which 100".
Is that really what you want?
And no, you won't actually get a random result, in the sense that it'll change each time you query the server, but you are at the mercy of the query optimizer. If the data load and index statistics for that table changes over time, at some point you might get different data than you did on the previous query.
Your problem is that the sort is being done every time the query is run. You can eliminate the sort operation by using an index - the optimiser can use an index to eliminate a sort operation - if the sorted column is declared NOT NULL.
(If the column is nullable, it is still possible, by either (a) adding a NOT NULL predicate to the query, or (b) adding a function-based index and modifying the ORDER BY clause accordingly).
Just for reference, in Oracle 12c, this task can be done using FETCH clause. You can see here for examples and additional reference links regarding this matter.