How to select top 10 records

How can I use SQL to select the top 10 records (do not use cursor)

... not only that but the order by and rownum check cannot be done in the same select. You need an in-line view.
select * from
(select * from table
order by whatever)
where rownum < 11
BEWARE: Incorrect use of rownum (which is very common) often returns the correct result by accident, but you cannot guarantee that the accident will continue to happen.

Similar Messages

  • How to select the first record?

    Hi,
    Could anyone tell me how to select the first record of every
    group?
    ex, I want to find out every customer their first purcaseDate.
    CustomerID PurcaseDate Region
    A00000001 2001/01/01 AA
    A00000001 2001/02/02 AA
    A00000002 2001/03/01 AC
    A00000002 2001/05/07 AC
    A00000003 2001/03/05 DD
    result:
    A00000001 2001/01/01 AA
    A00000002 2001/03/01 AC
    A00000003 2001/03/05 DD
    Thanks

    Vincent,
    You could do it as Carl suggested, with a couple of
    corrections.  You would need to include the CustomNo column in
    the order by clause of your cursor.  You would also need to add
    a where clause to your update statement, otherwise everywhere
    Region in the table would be updated with the same value of the
    last CustomNo in the cursor, regardless of the CustomNo in the
    table.  See corrected code below:
    DECLARE
      CURSOR     cust
      IS
      SELECT     DISTINCT CustomNo, Region, Purchase_Date
      FROM       my_table
      ORDER BY   CustomNo, Purchase_Date, Region;
      c_customer VARCHAR2 (9) := '...';
      c_region   VARCHAR2 (2) := '..';
      cntr       NUMBER := 0;
    BEGIN
      FOR x IN cust
      LOOP
        IF x.CustomNo != c_customer
        THEN
          c_customer := x.CustomNo;
          c_region := x.Region;
        ELSE
          UPDATE my_table
          SET    Region = c_region
          WHERE  CustomNo = c_customer;
          cntr := cntr + 1;
          IF cntr = 25
          THEN
            COMMIT;
            cntr := 0;
          END IF;
        END IF;
      END LOOP;
      COMMIT;
    EXCEPTION
      WHEN OTHERS THEN 
        NULL;
    END;
    Another option is that you could just use one update statement,
    like this:
    UPDATE my_table a
    SET    Region =
           (SELECT DISTINCT Region
            FROM   my_table b
            WHERE  (CustomNo, Purchase_Date) IN
                   (SELECT   CustomNo, MIN (Purchase_Date)
                    FROM     my_table
                    GROUP BY CustomNo)
            AND    a.CustomNo = b.CustomNo)
    Barbara

  • How to Get Top 10 records using SQL select statement.

    :-) Hiee E'body,
    I want to generate a sql report in which I only want the top 10 records based on the numeric value of a column.
    For Example,
    To generate a Location Wise, Employee Wise Years of Service Report.
    Here I need the Top 10 Employees according to their No. of Years of Service for all the existing locations using a single query.
    eg.
    Location Emp No. YOS
    India - 22 30
    212 28
    819 24 ...
    US 123 40
    312 33
    90 33
    144 30 ...
    UK 77 20
    79 20
    331 18
    109 16 ...
    Every Location should display their respective Top 10 Employees
    regarding their No. of Years of Service.
    Please let me the know the solution to this.
    Have a nice day.
    Thanking You,
    Vivek Kapoor.

    For example if the table contained (India rows only shown) :
    India 202 30
    India 212 28
    India 819 24
    India 820 24
    India 900 20
    India 920 18
    India 922 17
    India 925 16
    India 926 15
    India 927 14
    India 928 13
    India 929 13
    India 930 12
    do you want to see
    India 202 30
    India 212 28
    India 819 24
    India 820 24
    India 900 20
    India 920 18
    India 922 17
    India 925 16
    India 926 15
    India 927 14
    or
    India 202 30
    India 212 28
    India 819 24
    India 820 24
    India 900 20
    India 920 18
    India 922 17
    India 925 16
    India 926 15
    India 927 14
    India 928 13
    India 929 13
    Also if the India rows were
    India 202 30
    India 212 30
    India 819 30
    India 820 30
    India 900 30
    India 920 30
    India 922 30
    India 925 30
    India 926 30
    India 927 30
    India 928 30
    India 929 30
    do you want to see
    India 202 30
    India 212 30
    India 819 30
    India 820 30
    India 900 30
    India 920 30
    India 922 30
    India 925 30
    India 926 30
    India 927 30
    or
    India 202 30
    India 212 30
    India 819 30
    India 820 30
    India 900 30
    India 920 30
    India 922 30
    India 925 30
    India 926 30
    India 927 30
    India 928 30
    India 929 30
    Please clarify.
    Thanks,
    Partha

  • How to select only one record at a time in ALV

    Hi all,
    I have to use ALV report.  Each record on the report output should have a button (or radio button) which will allow the record to be selected.  My requirement is to select only one record at a time.
    please guide me how to proceed further.
    regards
    manish

    hi
    https://www.sdn.sap.com/irj/sdn/wiki?path=/display/snippets/sampleCheckBoxProgram
    Regards
    Pavan

  • Selecting Top N records in a table using a slider or drop down list

    Hi Experts,
    I have a query that  displays 1000 records ( say) in VC iview.
    Can i have a drop down list in the variable form to control the number of records displayed in the output table by the user .
    or can i have a horizaontal slider ( Min value is 2 -max 1000)  to display the number of records in the output table  selected by the horizaontal slider.
    basically iam having a requirement to give the user the capability to select the Top N records of the output table...where the user enters the N value in Drop downlist of variable form or user slides the N value using Horizontal slider
    Thnaks
    P.Navakanth

    Hi
    Yes it is possible. First you need to create 'Condition' in BEx query where you have to create 'TOP N' & 'N' should be a variable input. Then you will get this in 'Variable Screen' of a query. In VC for this same variable you can use slider. Use 'Select' function in the 'Action' of the slider & pass it to require table/graph.
    Try this, this will give you the required result.
    Regards
    Sandeep

  • JDBC: How  to select only those records which contains col1 is NULL

    Hi All,
    In JDBC SELECT scenario.
    I wants to select only those records which contains col1 is NULL.
    I am trying as follows:
    <key>
    <col1 isNull="TRUE" />
    </key>
    but in moni/monitoring i am getting Following Error
    006-12-01 19:35:20 Error Unable to execute statement for table or stored procedure. 'BG_SALARY_SEND_SAP_D' (Structure 'SELECT') due to java.sql.SQLException: FATAL ERROR document format: structure 'SELECT', key element 'key' contains no values
    2006-12-01 19:35:20 Error Exception caught by adapter framework: Error processing request in sax parser: Error when executing statement for table/stored proc. 'BG_SALARY_SEND_SAP_D' (structure 'SELECT'): java.sql.SQLException: FATAL ERROR document format: structure 'SELECT', key element 'key' contains no values
    Please suggest how to do select rows with col1 is null.
    Regards

    Rohan,
    isNull= true is used to make the KEY element not mandatory.
    In your case, if the select query is
    select emp from emptest where empno is null
    , then the datatype will be,
    <root>
    <StatementName>
    <dbTableName action=”SELECT”>
      <table>emptest</table>
    <access>
    <emp></emp>
    </access>
    <key1>
    <b><empno hasQuot="NO">is null</empno></b>
    </key1>
    </dbTableName> 
    </StatementName>
    </root>
    I dont have a DB access to try this, but I think this should work.
    If this doesnt work, then you would need to use SQL_QUERY,
    <root>
    <StatementName>
    <anyName action=” SQL_QUERY”>
    <access>select emp from emptest where empno is null</access>
    </anyName > 
    </StatementName>
    </root>
    http://help.sap.com/saphelp_nw04/helpdata/en/2e/96fd3f2d14e869e10000000a155106/content.htm
    Regards,
    Bhavesh

  • How to select first several records from a database table by using select?

    Hi,
       I want to select first 100 records from a database table by using select clause. How to write it?
       Thanks a lot!

    hai long!
                 well select statement is used to retrive
    records from the database.
    following is the syntax to be used.
    1) select *  into corresponding fields of itab from basetable where condition.
    endselect.
      ex: select * into corresponding fields of itab from mara
                where matnr >= '1' and  matnr <= '100'.
           append itab.
          endselect.
    select * is a loop statement.it will execute till matnr is less than or equal to 100.
    note: you can also mention the required field names in the select statement otherwise it will select all the field from table mara.
    note: itab means your internal table name.
    hope you got the required thing.if it really solved u r problem then award me the suitable points.<b></b>

  • How to get top 3 record from aggregated column

    Hello,
    i have a simple query which return all student in class with total marks. now i want to select top 3 student whose score is maximum. simple top three position. how can i use rank function here? or any other way to do that
    select  st.sti_roll_no  ,st.sti_name , sum(rd.rd_obt_marks) as  mycol  from rd_result_detail rd , rm_result_master rm, sti_student_info st
    where rm.rm_result_id = rd.rd_result_id
    and st.sti_roll_no= rd.rd_student_id
    --and  rd.rd_student_id = 'MBP10293'
    and rm.rm_semester = 3
    and rm_session = 2009
    and rm_batch= 3
    and rm.rm_exam_type ='FINAL TERM'
    and rm.rm_class_id = 'MBA'
    group by st.sti_name, st.sti_roll_no
    order by st.sti_roll_no;

    Not sure!!!!!!!!!!!!!
    with t as
    (select  st.sti_roll_no  ,st.sti_name , sum(rd.rd_obt_marks) as  mycol  from rd_result_detail rd , rm_result_master rm, sti_student_info st
    where rm.rm_result_id = rd.rd_result_id
    and st.sti_roll_no= rd.rd_student_id
    --and  rd.rd_student_id = 'MBP10293'
    and rm.rm_semester = 3
    and rm_session = 2009
    and rm_batch= 3
    and rm.rm_exam_type ='FINAL TERM'
    and rm.rm_class_id = 'MBA'
    group by st.sti_name, st.sti_roll_no
    order by st.sti_roll_no)
    select sti_roll_no  ,sti_name,mycol,dense_rank()over(order by mycol desc) rnk
    from t
    --where rnk<=3
    SQL> ed
    Wrote file afiedt.buf
      1  select e.* from (select empno,ename,sal,dense_rank()over(order by sal desc) rnk
      2* from emp)e where rnk<=3
    SQL> /
         EMPNO ENAME             SAL        RNK
          7839 KING             5000          1
          7788 SCOTT            3000          2
          7902 FORD             3000          2
          7566 JONES            2975          3

  • How to select top one in CDS view ?

    I have tried following logic to select top one in CDS view but its giving error -
    define view Cds_View_First_Reference as select  top one CReferredObject from CDSVIEWCROSSREF

    Hi Ruchi,
    since you posted this question in "ABAP in Eclipse" I assume you are asking about CDS in ABAP. This is important because the CDS features sets in ABAP and (native) HANA are different.
    Be that as it may,, SELECT TOP 1 is neither supported in the CDS implementation in ABAP nor in HANA.
    In ABAP you might consider using the min() or max() function together with the appropriate GROUP BY clause in the CDS view (depending on what you want to achieve), but you can also easily "implement" this in the Open SQL statement which selects from your CDS view.
    Using the additions SELECT SINGLE or UP TO 1 ROWS and an appropriate ORDER BY clause in Open SQL, you can achieve the same as SELECT TOP 1.
    Unfortunately there is currently no possibility to define a view which delivers the TOP 1 which you can again use in another view ("view on view").
    Kind regards
    Chris

  • How do I select top 100 records in query

    I would like to get only the first 100 or 200 records in a query. In Access query, it is TOP 100, is there an equal in Oracle sql?
    Thanks!

    select * from your_table
    where rownum < 101;

  • HOW TO GET TOP N RECORDS IN SQL , URGENT

    Hi,
    I want to get the TOP 2 and BOTTOM 2 records (TOP 2 SAL , BOTTOM 2 SAL) from the following query result for each department . How do I get it using a SQL statement ? Thanks
    SQL> SELECT A.DNAME, B.ENAME, B.SAL FROM DEPT A, EMP B WHERE A.DEPTNO = B.DEPTNO ORDER BY DNAME, SAL
    DNAME------------ENAME--------SAL
    ACCOUNTING-------KING--------5000
    ----------------CLARK--------2450
    ---------------MILLER--------1300
    RESEARCH--------SCOTT--------3000
    -----------------FORD--------3000
    ----------------JONES--------2975
    ----------------ADAMS--------1100
    ----------------SMITH---------800
    SALES-----------BLAKE--------2850
    ----------------ALLEN--------1600
    ---------------TURNER--------1500
    -----------------WARD--------1250
    ---------------MARTIN--------1250
    ----------------JAMES---------950
    14 rows selected.

    If Feroz is asking the TOP 2 Salaried employees and BOTTOM 2 Salaried employees
    for ***EACH**** DEPARTMENT, then following SQL is one of the many ways(proves good with performance).Also brings top2+ bottom2 in one shot.SELECT dname, ename, sal FROM
    (SELECT d.DNAME, e.ENAME, e.SAL,
           dense_rank() over(PARTITION BY e.DEPTNO ORDER BY e.SAL) dr
    FROM EMP e, DEPT d
    WHERE e.DEPTNO = d.DEPTNO)
    WHERE dr <= 2
    UNION
    SELECT dname, ename, sal FROM
    (SELECT d.DNAME, e.ENAME, e.SAL,
           dense_rank() over(PARTITION BY e.DEPTNO ORDER BY e.SAL DESC) dr
    FROM EMP e, DEPT d
    WHERE e.DEPTNO = d.DEPTNO)
    WHERE dr <= 2
    /Thx,
    SriDHAR

  • How to select Most recent record with rest of record in ascending order...?

    Dear Expert,
    I have one table called Tab1 & have a lot columns. For this schenario, i mentioned few of the columns.
    The columns are
    product_type varchar2(100),
    curr_date date (storing with time stamp),
    other1_cloumn varchar2(10),
    other2_cloumn varchar2(10)
    Now I want to display all the records in ascending order except most recent record for every product_type || Union all || Most recent records in ascending order in single query.
    For example...
    product_type curr_date date other1_cloumn other2_cloumn
    1, "10-May-2005 10:10:10", 10, 10
    1, "10-May-2005 10:10:11", 10, 10
    1, "10-May-2005 10:10:12", 10, 10
    1, "10-May-2005 10:10:09", 10, 10
    2, "10-May-2005 10:10:10", 10, 10
    2, "10-May-2005 10:10:11", 10, 10
    2, "10-May-2005 10:10:12", 10, 10
    2, "10-May-2005 10:10:09", 10, 10
    3, "10-May-2005 10:10:10", 10, 10
    3, "10-May-2005 10:10:11", 10, 10
    3, "10-May-2005 10:10:12", 10, 10
    3, "10-May-2005 10:10:09", 10, 10
    Now I want to display (OUTPUT) like...
    1, "10-May-2005 10:10:10", 10, 10
    1, "10-May-2005 10:10:11", 10, 10
    1, "10-May-2005 10:10:09", 10, 10
    2, "10-May-2005 10:10:10", 10, 10
    2, "10-May-2005 10:10:11", 10, 10
    2, "10-May-2005 10:10:09", 10, 10
    3, "10-May-2005 10:10:10", 10, 10
    3, "10-May-2005 10:10:11", 10, 10
    3, "10-May-2005 10:10:09", 10, 10
    1, "10-May-2005 10:10:12", 10, 10
    2, "10-May-2005 10:10:12", 10, 10
    3, "10-May-2005 10:10:12", 10, 10
    Plz, provide a solution....

    I want to display like...
    select * from tab1 where (product_type,curr_date) in
    (select product_type,max(curr_date) from tab1 group by product_type)
    order by product_type
    Union All
    (select * from tab1 where (product_type,curr_date) NOT IN
    (select product_type,max(curr_date) from tab1 group by product_type)
    order by product_type)
    But, In the above case, The ORDER BY Clause will not work...How to get this one...?
    I mean.. I want to display all the records in ascending order except Most recent record base on Product type and next I want to display Most recent record in ascending order. I want to display both cases in a single query...?

  • HOW TO SELECT ONLY THOSE RECORDS WHERE NOT AVAILABLE ON SECOND TABLE

    hi
    i have two tables one name is menus and second name is UGroupDetail. Actually i have created it for user role privileges for my application
    USE [LedgerDB]
    GO
    /****** Object: Table [dbo].[Menus] Script Date: 03/28/2015 13:45:27 ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    CREATE TABLE [dbo].[Menus](
    [RightID] [int] NOT NULL,
    [RightName] [nvarchar](200) NULL,
    [GroupID] [int] NULL,
    CONSTRAINT [PK_Menus] PRIMARY KEY CLUSTERED
    [RightID] ASC
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
    ) ON [PRIMARY]
    second table is
    USE [LedgerDB]
    GO
    /****** Object: Table [dbo].[UGroupDetail] Script Date: 03/28/2015 13:46:12 ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    CREATE TABLE [dbo].[UGroupDetail](
    [RightID] [int] NOT NULL,
    [RightName] [nvarchar](200) NULL,
    [GroupID] [int] NULL
    ) ON [PRIMARY]
    GO
    ALTER TABLE [dbo].[UGroupDetail] WITH CHECK ADD CONSTRAINT [FK_UGroupDetail_Menus] FOREIGN KEY([RightID])
    REFERENCES [dbo].[Menus] ([RightID])
    ON UPDATE CASCADE
    ON DELETE CASCADE
    GO
    ALTER TABLE [dbo].[UGroupDetail] CHECK CONSTRAINT [FK_UGroupDetail_Menus]
    GO
    ALTER TABLE [dbo].[UGroupDetail] WITH CHECK ADD CONSTRAINT [FK_UGroupDetail_UserGroup] FOREIGN KEY([GroupID])
    REFERENCES [dbo].[UserGroup] ([GroupID])
    ON UPDATE CASCADE
    ON DELETE CASCADE
    GO
    ALTER TABLE [dbo].[UGroupDetail] CHECK CONSTRAINT [FK_UGroupDetail_UserGroup]
    UGroupDetail have many groups as assigned to a new user but Menus table has only default groups which is 90 records
    Menus table is a primary table and UGroupDetail is a Foreign key table
    now i want to combined these tables and want to get only remaining records for each group
    for example i have assigned 5 roles to GroupID 2 and now when i apply select commands the result should be 85 out 90 for GroupID 2
    but i have not idea how to modify select query for get desired result

    I don't really understand the tables. What is GroupID doing in the Menues table? And what does an entry without a RightName mean? Shouldn't that column be NOT NULL?
    The UGroupDetail does not have any primary key. From your description, I would expect the PK to be (RightID, GroupID). But strangely enough, GroupID is nullable. So is RightName, but I think this column is redundant and should be removed.
    Anyway, if I understand your question correctly, you need something like:
    SELECT UG.Name, M.RightName
    FROM   UserGroups UG
    CROSS  JOIN Menus M
    WHERE  NOT EXISTS (SELECT *
                       FROM   UGroupDetail UGD
                       WHERE  UG.GroupID = UGD.GroupID
                         AND  UG.RightID = M.RightID)
    Erland Sommarskog, SQL Server MVP, [email protected]

  • How to select 10 random records?

    Requirement is:
    Show all records if query returns less than equal to 10 records.
    Else
    Show random 10 records.
    How do I achieve that using SQL alone?
    Tried with sample but that didn't work. The number of records in table continuously growing.
    Thanks

    Hi,
    would tell me how it works. little bit confusing me..
    SQL> select count(*) from scott.emp;
      COUNT(*)
            14
      1* SELECT *   FROM scott.emp SAMPLE (8)
    SQL> /
         EMPNO ENAME      JOB              MGR HIREDATE         SAL       COMM     DEPTNO EMAIL
          7839 KING       PRESIDENT            17-NOV-81       5200       8250         10
    SQL>
    SQL> ED
    Wrote file afiedt.buf
      1* SELECT *   FROM scott.emp SAMPLE (7.5)
    SQL> /
         EMPNO ENAME      JOB              MGR HIREDATE         SAL       COMM     DEPTNO EMAIL
          7788 SCOTT      ANALYST         7566 09-DEC-82       3200        450         20
          7934 MILLER     CLERK           7782 23-JAN-82       1500        195         10
    SQL> SELECT *   FROM scott.emp SAMPLE (7.5);
         EMPNO ENAME      JOB              MGR HIREDATE         SAL       COMM     DEPTNO EMAIL
          7902 FORD       ANALYST         7566 03-DEC-81       3200        450         20Edited by: Ravi291283 on Jul 27, 2009 2:32 AM

  • How to display top n records(sorted by no of defects) within date range

    I would like to display top n production orders(sorted by defects linked with each order) within the date range entered by the user.
    Please advice.
    I have 3 parameters to my report:
    1. n(n is no of top records to be displayed)
    2. From date
    3. To date
    Appreciate quick response.
    Regards,
    Hari

    if you use the parameters in the report by placing them in the record selection it should display the records within your date range.
    if {date field} in ?start to ?end then true

Maybe you are looking for

  • How to sync bb/outlook/gmail contacts and calendar

    i have a bb 9530 and outlook 2007 running on a 64-bit windows 7 pc.  i use outlook to view my gmail.  i also have the bb gmail app on my phone and that keeps email in sync between gmail servers and the phone as well as outlook since it is setup for a

  • Red r3d 3k fails on CUDA export Media encoder CC

    Been having some problems with Red 3k. Several times recently for some low budget stuff I have shot 3k and put it in a 720P timeline. All of my 3k material will fail under media encoder CUDA export.....it works under software but a 20 minute CUDA enc

  • HP 7510 all-in-one, not working on Windos 7 with McAfee

    Hp 7510 all-in one printer on a desktop using windows 7 will not print if McAfee firewall is active.  "What settings need to be changed?

  • Same position in differenet org unit

    HI Folks, Is it possible that one same position is available in two different org units with 100% occupation. actaully, I have a situation where an EE is moved to diff. org unit but it is not updating org key automatically generated by combining per

  • Copy Company code

    Hello all I want to copy company code in development please tell me from which company code i should copy it, 0001 ro IN01 company code. I am asking this question because whether no range wpuld be transported to it or not. suggest Edited by: Prem Kum