Last n records

Yes – I’m working on a Sunday.
Okay, here’s the deal: I want to retrieve the last n
(call it 5) records (non-sequential) from a table. I can easily do
this by getting my query to sort desc, and then using maxrows so
that it gives me the last 5 – but:
1) I want the last 5 to be in order – for example, I
don’t want 10, 9, 8, 7, 6, - which is what the example above
gives me, I want 6, 7, 8, 9, 10.
2) The table will have thousands, if not 10s of thousands of
records, to select just the row_id desc, will be a huge task.
Don’t want the server to work that hard – it’s
got other things to do.
My idea is as follows – using the select max(row_id) is
easy, it gives me the last record – can't I just do something
that will step back n number times from my max query and give me
the last n records?
PS: MX8, MySql 5

add another query before your query:
<cfquery name='getrowcount' ...>
SELECT COUNT(*) AS ttlrows
FROM yuortable
</cfquery>
in your current query add the following as last line:
LIMIT #getrowcount.ttlrows-5#, 5
Azadi Saryev
Sabai-dee.com
http://www.sabai-dee.com/

Similar Messages

  • How can I get the last / newest record of a table?

    Hi,
    I am developing an ecard app that has a create greeting page, a preview page with edit and send buttons and an edit page.
    I got he insert working, and on the preview page I created a master record page (displays all records), and delete all unecessary designs. Doing it this way also gives me the 'edit' button, so people are able to edit their page.
    How do I get only the last record displayed though? At the moment it loops through all records and displays them in sets of 10. I found the variable that holds the totla count of records ('$totalRows_rs7417_content1'), but how do I (re-)write the script so it ONLY diplays the last record?
    I need to get the ID of this record as I am writing this into the PARAMs of the object and embed tags of my message .swf (this picks up the ID and based on that sucks the greetings text out of the database via another php script.
    Also, from this page, how can I send an email to the sender (ie creator of the message) as well as the recipient? Both email addresses are in the databse so should be part of the erecord returned.
    Thanks,
    Nik

    -----
    OK, So how do I recreate what I got in a non-ADDT list?
    well, when you´re just about to display one certain record, the term "list" is somewhat inappropriate anyway.
    What you´d simply need to do IMHO, is using DW´s native functions to create the basic "SELECT * FROM table_name ORDEr BY ID DESC" query, add "LIMIT 1" manually, and display the desired "dynamic text" placeholders in 1 table cell -- don´t think there were any need for all the fancy stuff
    (sorting, filtering etc) provided by ADDT´s list, as it´s just 1 record.
    It also occurred to me just now that finding the last record that has been added *may-* notbe enough if the site gets used a lot by our executives (I am thinking of a situation where 2 or three peolpe create greetings at the same time and press submit and then getting each others messges rather than their own).
    in this case you might want to additionally store the respective executive´s "kt_login_id" session variable -- because it´s this unique "identifier" which should be used to show the last inserted record of the person who actually inserted it, means adding a "WHERE submitter_id" equals the session variable kt_login_id - clause to the query.
    When creating a non-ADDT list that´s at some point based on detecting a user session, you´ll BTW need to insert at line 1
    I can't seemt o insert it on the page as it is looking for a insert, update or delete bahaviour on the page which of course I don't have
    please search these forums for several posts I made which explain my "use dummy table" approach that´s made for cases when you actually don´t have anything to insert/update/delete, but need "something" for ADDT´s send email behaviours.
    Cheers,
    Günter Schenk
    Adobe Community Expert, Dreamweaver

  • Simple Query Question - How do I return the Last 3 records of a Table?

    Question.
    For example, I have a table that has 50 records.
    How do I, specify in SQL to only return the last 3 records of the table.
    Select a.* from table a where ????

    I was just trying to show an example to a friend on
    how something like this would work and if it was even possible. But it won't work. Here's a simple example:
    SQL> create table emp
      2  (id)
      3  as
      4  select object_id
      5  from   all_objects
      6  order  by object_id;
    Table created.
    SQL> select *
      2  from  (select rownum rn
      3               ,b.*
      4         from   emp b)
      5  where  rn > ( select (max(rownum) - 3)
      6                from    emp)
      7  ;
            RN         ID
         40830      55891
         40831      55892
         40832      55893So far, so good. These are the "last 3" rows inserted. Now delete a bunch of rows and insert 3 new ones:
    SQL> delete emp where id < 40000;
    33423 rows deleted.
    SQL> commit;
    Commit complete.
    SQL> insert into emp values (60000);
    1 row created.
    SQL> insert into emp values (60001);
    1 row created.
    SQL> insert into emp values (60002);
    1 row created.
    SQL> commit;
    Commit complete.
    SQL> select *
      2  from  (select rownum rn
      3               ,b.*
      4         from   emp b)
      5  where  rn > ( select (max(rownum) - 3)
      6                from    emp)
      7  ;
            RN         ID
          7410      55891
          7411      55892
          7412      55893Here's the problem. Even though the "last 3 rows" are 60000 - 60002, I still get the same ones as the first query.

  • Different ways to get the last 5 records ordered by date

    I have a query no that returns the tickets ordered by moddt, modification date,
    I was thinking of adding a select on top, to get the last 5 records of that list the select already generates. An other way was to use that select to create a view,
    and get the 5 last records that way. I also though of a possibly impossible cursor with a sequence, but hmm well I consider that not a good solution.
    So I'm trying to find a way, using a select, the topmost select which is not completed yet, to get the last 5 records. Maybe I should just try the rownumber thing again or something likewise.
    Select * from(
    select * from(
    Select ticketid, appliecatiecd, categorieid, substr(titel,&,200)||' ...' "titel", klantproriteitid, interneprioriteitid,
    (select g.voornaam||' '||g.naam
    from gebruiker g
    Where g.gebruikerid = t.gebruikerid
    And t.applicatiecd = NVL(:P0_applicatiecd, :F101_applicatiecd))"aangemaakt door",
    (select s.statusdefoms "status"
    From status s
    Where s.statusid = t.statusid
    And t.applicatiecd = NVL(:P0_applicatiecd, :F101_applicatiecd)) "status",
    Versieid,
    Moddt,
    Row_number() over (order by ticketid desc) rn
    From ticket t
    Where applicatiecd = NVL(:P0_applicatiecd, :F101_applicatiecd) )
    Order by moddt)
    Where --

    Hi Floris,
    You can also use RANK: http://www.dba-oracle.com/oracle_news/oracle_faq/faq_beg_sql_top_n_rows.htm
    Regards Pete

  • Query : first and last 25 records of a table

    Hi @ll,
    i am going to write a query for a report. Therefor i need the first and last 25 records of a table. Does anyone got an idea for a solution ? I was trying to achieve this by using a WHERE clause. Here is a part of the query :
    SELECT
    TOP 10 T1.[ItemCode], DATEPART(mm, T1.[DocDate])   [.....]
    FROM FROM INV1 T1
    Where T1.[DocDate] >= Cast('2009  [......] AND
    T1.ItemCode = (
    SELECT TOP 10 T40.[ItemCode]
    FROM DBO.OINM
    WHERE Where T40.[DocDate] >= Cast('2009-04-01 00:00:00' AS datetime)
    AND T40.[DocDate] <= Cast('2009-04-30 00:00:00' AS datetime)
    GROUP BY T1.[ItemCode], DATEPART(mm, T40.[DocDate])
    ORDER BY SUM(T1.[TotalSumSy]) ASC)
    The where part i would use twice, once for ascending the other one for descending. But it does not work.
    Any ideas ?
    Regards Steffen

    Hi,
    Union was the keyword, that i was searching for. It is a nice way, but not practible.
    We are using coresuite for generating reports, and there were a nice possibility to connect diffrent queries.
    Thanks for your suggestion.
    Regards Steffen

  • SQL query to get last 10 records in the table?

    Hi,
    Can anyone tell me the SQL query to get last 10 records in the table?
    Thanks!!
    MCP

    Please, define what "last" means. Sets are unordered by definition, so if you want to retrieve rows from a table in a specific order you need to specify what that order is - e.g. by maintaining a value in a column (or a combination of columns) that you can use in the ORDER BY clause of the SELECT statement.
    If, for instance, you kept the time when the row was inserted in a special column (InsertedTime), you could use this in your query like this:
    select top (10)
      <column list>
      from <table or view>
      where <restriction(s)>
      order by InsertedTime desc;
    ML
    Matija Lah, SQL Server MVP
    http://milambda.blogspot.com

  • Getting Last Payroll Record

    Hi all,
    I need to fetch last payroll record of a pernr,from transaction pc_payresult.
    I am using the LDB PNP.
    After calling GET PERNR, I am using functions CU_READ_RGDIR and then PYXX_READ_PAYROLL_RESULT to fetch the last active payroll record.
    But is there any way to <b>directly</b> fetch the last active payroll record,based on the pernr? Please suggest a way.
    Thanks&Regards
    Ananya

    Hi
    To get the payroll results, you need to read the cluster CU to get RGDIR. For this CU_READ_RGDIR is used and almost all standard programs also use this FM.
    Simple Report using LDBs to get latest payroll result.
    report ythr_read_payroll .
    data: t_rgdir type pc261 occurs 0,
          t_result type payus_result,
          w_bt type line of hrpay99_bt,
          out_seqnr like pc261-seqnr.
    tables: pernr.
    get pernr.
      call function 'CU_READ_RGDIR_NEW'
           exporting
                persnr                = pernr-pernr
           tables
                in_rgdir              = t_rgdir
           exceptions
                no_record_found       = 1
                import_mismatch_error = 2
                no_read_authority     = 3
                others                = 4.
      if sy-subrc <> 0.
        write:/1 'No payroll results for ', pernr-pernr.
      endif.
    call function 'CD_READ_LAST'
           exporting
                begin_date      = pn-begda
                end_date        = pn-endda
           importing
                out_seqnr       = out_seqnr
           tables
                rgdir           = t_rgdir
           exceptions
                no_record_found = 1
                others          = 2.
      if sy-subrc <> 0.
        write:/1 'Error for ', pernr-pernr.
      endif.
      call function 'PYXX_READ_PAYROLL_RESULT'
           exporting
                clusterid                    = 'RU'
                employeenumber               = pernr-pernr
                sequencenumber               = out_seqnr
           changing
                payroll_result               = t_result
    exceptions
                illegal_isocode_or_clusterid = 1
                error_generating_import      = 2
                import_mismatch_error        = 3
                subpool_dir_full             = 4
                no_read_authority            = 5
                no_record_found              = 6
                versions_do_not_match        = 7
                error_reading_archive        = 8
                error_reading_relid          = 9
                others                       = 10.
      if sy-subrc <> 0.
        write:/1 'Error for ', pernr-pernr.
      endif.
      loop at t_result-inter-bt into w_bt.
        write:/1 pernr-pernr, out_seqnr, w_bt-bankl, w_bt-bankn.
      endloop.
    Regards
    Navneet

  • Retrive a record before the last inserted record

    Hi,
    I use simple select statement to retrive records where cola = 'Yes':
    select * from tbl1
    where cola = 'Yes';
    The result gives me about 10 records with different date.
    From the above result, I want to get the record right before the last inserted record according to the date field; which means I can not use MAX function (all I want just one record).
    If I write a function to return a date and passes it back to the SELECT statement, I'll get a date for each record, which I don't want.
    I know there's a way to do that in PL/SQL.
    Plese help me.
    pem

    select * from (
    select * from
    (select * from (select * from (table> order by <date> desc) where rownum < 3)
    order by <date>) where rownum =1

  • How to get last year records in P&L

    Hii gurus,
    I am creating Profit & Loss report.
    I need to show last year records.
    Please explain.....
    Thanks in advance......
    Moderator message: please do more research before asking, show what you have done yourself when asking.
    Edited by: Thomas Zloch on Sep 27, 2011 2:11 PM

    Hi,
    Better still if you want this to be easily changeable, i.e. not without a repository migration, put the search spec on the Applet in the Application - Personalization screen. In this way you can change the Search Spec in case of Business Requirement change without needing to go through a development cycle. Do not forget to do a Reload Personalization Rules after changing Search Spec to bring this in effect.
    If you have a standard requirement then do it preferably on the Applet so that you can use the BusComp at other locations also without having to deal with the search spec coming in uninvited.
    Thanks and Regards,
    Tanmay Jain.

  • To get last 10 records

    hi
    suppose there are 50 records in a table
    but i want last 10 records .how can we retrive them?
    thanks in advance.......

    It works fine. The only odd thing is the timestamp appears later and the message (alert) appears first. But this is much better.
    Like this -
    Current log# 2 seq# 7479 mem# 0: D:\TESTDB\ORADATA\DATAFILES\TESTDB\REDO02.LOG
    Thread 1 advanced to log sequence 7479
    Thu May 01 12:30:40 2008
    ORA-00600: internal error code, arguments: [qkatab_10], [16], [79557], [], [], [], [], []
    Errors in file d:\admin\testdb\udump\testdb_ora_2092.trc:
    Thu May 01 11:35:21 2008
    ORA-00600: internal error code, arguments: [qknltAllocate_10], [79557], [], [], [], [], [], []
    Errors in file d:\admin\testdb\udump\testdb_ora_2092.trc:
    Thu May 01 11:34:45 2008
    WARNING: inbound connection timed out (ORA-3136)
    Thu May 01 11:26:38 2008
    Thank you all,
    Sanju.

  • How to populate last 10 records from data base table

    Hi,
    My requirement is to populate last 10 transfer order items confirmed from LTAP. as the table is too large there is no point to fetch all the records and filter them...
    Please let me know better way (in terms of performace) to get last 10 records from LTAP.
    Thanks in advance.
    Nag

    Hi brother,
    the following code is working......(sample code)
    data itmara type mara occurs 0 with header line.
    select matnr from mara into corresponding fields of table itmara up to 20 rows.
    sort itmara descending by matnr.
    loop at itmara .
    write:/ itmara-matnr.
    if sy-tabix = 10.
    exit.
    endif.
    endloop.
    plz reward with maximum points
    Edited by: sreejith gn on May 13, 2008 12:52 PM

  • Delete all by last 10 records...

    I have a table where I only want to keep the last 10 records of the of the product.
    say for instance, I have a products table and it has apples, oranges... and another table that lists each sales transaction for each product.  As you can see.. you would get 1000's of records in the sales table.
    I want to delete all records in the sales table, except for the last 10 records for apples?
    any help?

    I have a table where I only want to keep the last 10 records of the of the product.
    TRUNCATE TABLE is faster than DELETE and uses fewer system and transaction log resources.
    Try
    -- code #1 v2
    IF Object_ID('tempdb..#LastSales','U') is not null DROP TABLE #LastSales;
    ;with
    SalesSeq as (
    SELECT *, Seq= row_number() over (partition by IDProd order by SalesDate desc)
      from Sales
    SELECT IDSales, IDProd, SalesDate, Qty
      into #LastSales
      from SalesSeq
      where Seq <= 10;
    TRUNCATE TABLE Sales;
    INSERT into Sales (IDSales, IDProd, SalesDate, Qty)
    SELECT IDSales, IDProd, SalesDate, Qty
    from #LastSales;
    IF Object_ID('tempdb..#LastSales','U') is not null DROP TABLE #LastSales;
    You cannot use TRUNCATE TABLE on tables that:
        Are referenced by a FOREIGN KEY constraint
        Participate in an indexed view
        Are published by using transactional replication or merge replication.
    To test:
    CREATE TABLE Products (IDProd int primary key, DescProd varchar(30));
    CREATE TABLE Sales (IDSales int primary key, IDProd int references Products, SalesDate smalldatetime, Qty smallint);
    INSERT into Products values
    (1, 'apple'), (2, 'orange');
    INSERT into Sales values
    (1, 1, '20120103', 18), (2, 1, '20120104', 22), (3, 1, '20120105', 50),
    (4, 1, '20120105', 19), (5, 2, '20120103', 5), (6, 1, '20120113', 5),
    (7, 1, '20120123', 20), (8, 1, '20120203', 7), (9, 1, '20120203', 20),
    (10, 1, '20120303', 21), (11, 1, '20120313', 2), (12, 1, '20120401', 15);
    José Diz     Belo Horizonte, MG - Brasil

  • Retrive last inserted  record  from database table

    Hi,
    some body inserting a record into table 'A' through some procedure/java program.i want to retrive the last inserted record from database table.records are not stored in order.Can any body help me.

    In general, unless you are storing a timestamp as part of the row or you have some sort of auditing in place, Oracle has no idea what the "first" or "last" record in a table is. Nor does it track when a row was inserted.
    - If you have the archived logs from the point in time when the row was inserted, you could use LogMiner to find the timestamp
    - If the insert happened recently (i.e. within hours), you may be able to use flashback query to get the value
    - If you're on 10g or later and the table was built with ROWDEPENDENCIES and the insert happened in the last few days and you can deal with a granularity of a few seconds and you don't need 100% accuracy, you could get the ORA_ROWSCN of the row and convert that to a timestamp.
    If this is something you contemplate needing, you need to store the data in the row or set up some sort of auditing.
    Justin

  • How to find last inserted record in the table.

    Version: Oracle 10g
    I have a table called "Manufacture" and 3 columns as mfno,itemname,quantity.
    How to find last inserted record in the table "Manufacture".
    As i come to know that Rowid is not result perfect results. Please provide your inputs.

    user13416294 wrote:
    Version: Oracle 10gThat is not a version. That is a product name. A version is 10.1.0.2 or 10.2.0.4, etc.
    I have a table called "Manufacture" and 3 columns as mfno,itemname,quantity.
    How to find last inserted record in the table "Manufacture".Not possible as your data model does not cater for it. That simple.
    If there is a need to determine some order or associate some time to an entity, then that should be part of the data model - and a relationship, or one or more attributes are needed to represent that information. Thus your data model in this case is unable to meet your requirements.
    If the requirements are valid, fix the data model. In other words - your question has nothing to do with Oracle and nothing to do with rowid, rowscn or other pseudo columns in Oracle. It is a pure data modeling issue. Nothing more.

  • Last 10 records of a table with out using count

    How can i get last 10 records of a table with out using count() method? if there is some page size(eg 10) , and if we want last page. is it posible without ount()? if posible how?
    Message was edited by:
    user480375

    "is there any other way without nesting?"
    Not correctly, no. What is your problem with nesting? Nested queries are not inherently slower than unnested queries. In some cases, such as this, they are the only correct way to do the query. Even an analytic version of the Top N needs to be nested because:
    SQL> SELECT object_name
      2  FROM t
      3  WHERE ROW_NUMBER() OVER (ORDER BY object_name DESC) < 11
      4  /
    WHERE ROW_NUMBER() OVER (ORDER BY object_name DESC) < 11
    ERROR at line 3:
    ORA-30483: window  functions are not allowed hereTTFN
    John

Maybe you are looking for

  • Nokia (Asha) 303 uses my credits even when I am co...

    Dear all, I bought Nokia (Asha) 303 a couple of years ago with the wish to browse the internet whenever I am close to WiFi network - which is both in my office and at home. But, whenver I connect to internet, via the Nokia Browser, it consumes my cre

  • The entry FBZ4 S  is missing in table T021V

    HI I am doing the service tax thorugh f-58 , there i am geeting this error. The entry FBZ4 S  is missing in table T021V.

  • Creating reflection in Photoshop

    Hi, Can anyone please explain how to create a reflection in Photoshop like the one at the bottom of this image? Thanks!

  • Mp3 to aac question

    i realized that when i convert my 320 kbps songs to aac 128kbps they sound the same but is'nt the quality suppose to drop when i do this our are my ears bad?

  • Audit by session VS by access!

    Hi all, My Database audit_file_dest=/u01/app/oracle/admin/orcl/adump I set: alter system set audit_trail='XML' scope=spfile; startup force; audit select, insert, update on test by access; grant connect to test identified by test; grant select, insert