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

Similar Messages

  • SQL query to get last 6 months records neglect the current month

    Hi All;
    I need help with 
    sql query to get last 6 months records neglect the current month
    Any help much appreciated
    Thanks
    Pradnya07

    SELECT <> FROM tbl WHERE dt >=dateadd(month,-6,GETDATE())
    Best Regards,Uri Dimant SQL Server MVP,
    http://sqlblog.com/blogs/uri_dimant/
    MS SQL optimization: MS SQL Development and Optimization
    MS SQL Consulting:
    Large scale of database and data cleansing
    Remote DBA Services:
    Improves MS SQL Database Performance
    SQL Server Integration Services:
    Business Intelligence

  • How to find the last records of the table in adventure work db

    hi all,
    i want to find out " how to receive a last records of the table (eg:  person.emailaddress ) in sql 2008 and 2005"
    Thanks

    If you are looking for the latest record( the one which got inserted/modified last) then use this query
    select top 1 * from person.emailaddress
    Order by ModifiedDate desc
    Satheesh
    My Blog |
    How to ask questions in technical forum

  • Sql query to get Thursday (Date) for the year 2014

    Hello All,
    I want to get the date for all the Thursdays in the year 2014. How can I achieve this using SQL query? Can anybody give me a hand with this? Thanks.
    Amol

    Hi,
    Check if this can help you
    DECLARE @counter INT
    DECLARE @Date Date
    SELECT @counter = 0
    Select @Date = '20131226'
    WHILE @counter <= 52
    BEGIN
    select Thursday = convert(varchar(10),DATEADD(WEEK,1, @Date),120)
    SELECT @counter = @counter + 1
    Select @Date = DATEADD(WEEK,1, @Date)
    END
    Regards
    Prasad Tandel
    Please dont forget to mark as answer if this helps you :)

  • How to fetch last record from the table to display in screen painter?

    Hi Gurus,
                  I have a requirement where i have to fetch the last record value in the table.
    I have a screen where the TEXT name is REQUEST and I/P field name is REQ and SAVE push button.
    In this I/P field automatically 1 should display when i excecute the program and when i save this, the request number should turn to 2 that is dynamically..once agin save then 3 and so on....and this 1, 2, 3 will be storeing in table.
    I have succeeded till generating the values dynamically and saving in the table like 1 is displayed and when i click save it is changeing to 2..but the problem is when i am coming out of program and logon again the request number is again displaying as 1 rather it has to start with 4 because already 3 request are there in the table.
    My code is...
    Table zsave.
    data declarations....
    data req type i.
    req = 0.
    req = zsave-req.
    PROCESS BEFORE OUTPUT
    req = 0.
    select req into table fun_st from zsave.
    req = zsave-req.
    zsave-req = req.
    req = zsave-req + 1.
    PAI
    req = zsave-req + 1.
    zsave-req = req.
    when 'save'.
    wa_funst-req = zsave-req.
    Please can you provide me with the solution....answer will be rewared.
    THKS

    Can you tell me, when updaing the ZSAVE table with the counter value are you modifying the exisiting value or inserting the value as new record?
    From the code in your first post, i see that you are extracting records into internal table but when you are moving to variable REQ, you are moving from table work area which is blank, so everytime when you execute it may be starting as 0.
    Hope below code can help you understand on handling your requirement
    Global Declaration:
    >DATA: l_req TYPE i. 
    PBO:
      SELECT MAX( req ) INTO l_req FROM zsave.
      l_req = l_req + 1.
    PAI:
      DATA: wa TYPE zsave.
      CASE ucomm.
      WHEN 'SAVE'.
        wa-req = l_req.
        INSERT zsave FROM wa.
      ENDCASE.

  • Query to get last updated time of tables

    Hi,
    How to get the last updated date time of the Max DB table
    Regards,
    Satish

    Hi,
    Unfortunately, do not this this would be possible. Check this thread:
    MAXDB Audit logs
    Regards,
    Srikishan

  • SQL Query to Read each record in a table

    Can you please share any T-SQL block of statement, that reads reach record row by row
    for example
    Table1
    Row_1 a b c
    Row_2 d e f
    I need to call an stored proc which takes record values as parameters(row by row)
    Equalent logic in c#
    foreach row in Table1
          Sp(row)

    Try
    --Create table
    CREATE TABLE Test1 (
    id INT identity(1, 1)
    ,Val INT
    ,flag CHAR(1) DEFAULT 'F'
    --Feed value
    INSERT INTO Test1
    VALUES (
    1
    ,'F'
    2
    ,'F'
    3
    ,'F'
    SELECT *
    FROM Test1
    --Create SP
    CREATE PROCEDURE yourSp @param INT
    AS
    BEGIN
    SELECT 'Yes'
    ,@param
    END
    DECLARE @i INT = 1
    ,@count INT = 0
    ,@val INT = 0
    SELECT @count = count(1)
    FROM Test1
    WHILE (@i <= @count)
    BEGIN
    SELECT @val = Val
    FROM Test1
    WHERE id = @i
    EXEC YourSP @val
    SET @i = @i + 1
    END
    Thanks
    Manish
    Please click Mark as Answer if my post solved your problem and click
    Vote as Helpful if this post was useful.

  • How to get the only the last raw of the table

    Hello All,
    While fetching a table into internal table, how to get only the last record of the table.?
    Thanks and Regards, Pradeep

    I hope following code will solve your problem.
    DATA : it_bseg TYPE TABLE OF bseg,
           x_bseg TYPE bseg,
           v_index TYPE i.
    SELECT COUNT(*)
      FROM bseg
      INTO v_index.
    SELECT *
      FROM bseg
      INTO TABLE it_bseg.
    READ TABLE it_bseg INTO x_bseg INDEX V_INDEX.
    First SELECT will give you the number of rows in a table in v_index. Second SELECT will fetch all table data and then READ will give you the last record of the table in a structure x_bseg.
    Reward points if the answer is helpful.

  • How to rerieve records from the table starting with character 'D'

    Hi Folks,
    How to get the records from the table starting with character 'D'.
    Select Max (fld1) fron tab1 into tab1-fld1 where fld 2 = l_fld2 and starting character of fld(1) is 'D'.
    last record in the table starting with character 'D'
    How can i do that??
    Pl explain.
    Thanks,
    Matt

    Hi,
    Select Max (fld1) fron tab1 into tab1-fld1 where fld 2 = l_fld2 and starting character of fld(1) is 'D'.
    Select MAX (fld1)
       From  tab1
    into table itab
    where fld 2 = l_fld2
       and fld1 like 'D%'.

  • How to get the last record from the database

    I am using MS Access database and Swings as GUI. I want to get the last record of a particular column from the table and store it as a varaible.

    Hi
    To get Last record of resultset, you have pass some parameter in constructor of CreateStatement.In such case Resultset should be scrollable and Readonly
    Example
    objStatement=objCon.createStatement ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
    mwwResultSet=cwwStatement.executeQuery(mwwSqlQuery);
    while(mwwResultSet.next())
    if(mwwResultSet.isLast())
    //Fetch the required column record.
    String abc=mwwResultSet.getString(1);
    I think this will work. Try it.
    bye

  • How do i get the approximate size of back up file required to save on disk using sql query because i want to show the required sapce for backup on my application

    hi i am face with problem that is i want to show the how much approximate space required for backup or .bak file to get backup using sql query because i want to show the required memory for backup file on my java application  

    Hi FIROZ
    TENNALI
    Is this still an issue, or can we close the thread?
    * closing a thread by marking the answer/s (there is a link beneath each response) and you can vote for useful responses as well (there is a link to vote on the left of each response)
      Ronen Ariely
     [Personal Site]    [Blog]    [Facebook]

  • SQL query to get the Datetime 06 hours prior to the table Datetime value

    Hi Experts,
                    I'm just trying to create a SQL query to get the Datetime which should be 06 hours prior to my Table column value(Executiontime),
    Eg: my Executiontime(column) value is 07:00AM means, this query should fetch the detail of first VMName from table at 01:00AM, 
    SQL Table Name: TestTable
    Columns: VMName(varchar),status(varchar) Executiontime(Datetime)
    SQL Query : Select Top 1 VMName from
    TestTable where convert(date,Exeutiontime)=convert(date,getdate()) and
    status='0' and ExecutionTime > dateadd(hour,6,getdate())
    Request someone to alter this Query to my requirement or give me the new one.
    Regards,
    Sundar
    Sundar

    Hi All,
            Thanks for your Prompt response. I tried the below queries, but still I don't have any luck. Actually the queries are returning the value before the condition met (say when the time difference is more than 06 hours). I want the
    query to return exactly @ 06 hour difference or less than 06 hours,
    Query 01: Select Top 1 VMName from TestTable where
    convert(date,Exeutiontime)=convert(date,getdate())
    and status='0'
    and ExecutionTime >
    dateadd(hour,-6,getdate())
    Query 02: Select
    Top 1 VMName from TestTable where
    status='0'
    and ExecutionTime >
    dateadd(hour,-6,getdate())
    Query 03: Select
    Top 1 VMName from TestTable where status='0'
    and ExecutionTime >
    dateadd(hour,-6,ExecutionTime)
              Can someone point out the mistake please.
    Regards,
    Sundar
    Sundar

  • SQL query to get the list of approvals

    Hi,
    Could someone let me know the SQL query to get the list of all the pending approvals for a user in OIM 11g R2.
    Thanks

    There are a few ways to do this:
    -  The easiest would be to use a Relationship Query from the CMC. To do this, go to the Universes section on the CMC, right click on the relevant universe, select tools >> Check Relationships.
    - Use Query Builder. You will need more than one query to pull the information you need. You could try something like the below (for Webi)
    SELECT SI_NAME, SI_WEBI, SI_DATACONNECTION FROM CI_APPOBJECTS
    WHERE SI_KIND = 'universe' and SI_NAME = 'Universe Name'
    This will give you a list of Webi Reports by SI_ID.
    You'll need another query to list Webi report names:
    SELECT SI_NAME FROM CI_INFOOBJECTS WHERE SI_ID IN (SI_ID from query above)
    - This is trivial via Auditing / the Activity universe. This of course will only return reports that have already run.
    Best.
    Srinivas

  • Sql query to get union of matching rows

    I want to write a sql query that shows union f all the [Type] for each [Key] if [Key] has atleast one [Type] in common and for non matched [Key]s it will return the row as it is.
    For example In the sql table below [Key] '1' and '2' has [Type] 'B' in common and [Key] '1' and '4' has [Type] 'A' in common. In this case [Key] '1', '2' and '4' are related so result will be union of [Type]s in [Key]s '1', '2' and '4' which are 'A', 'B', 'C'
    and 'E' for each [Key]. And [Key] '3' has no [Type] in common so it will return itself.
    Input:
    declare @categories table ([Key] int, [Type] Char(1))
    insert into @categories ([Key], [Type]) values (1, 'A')
    insert into @categories ([Key], [Type]) values (1, 'B')
    insert into @categories ([Key], [Type]) values (2, 'B')
    insert into @categories ([Key], [Type]) values (2, 'C')
    insert into @categories ([Key], [Type]) values (3, 'D')
    insert into @categories ([Key], [Type]) values (4, 'E')
    insert into @categories ([Key], [Type]) values (4, 'A')
    insert into @categories ([Key], [Type]) values (5, 'F')
    insert into @categories ([Key], [Type]) values (5, 'G')
    insert into @categories ([Key], [Type]) values (6, 'G')
    insert into @categories ([Key], [Type]) values (6, 'H')
    Desired output:
    Key Type
    1 A
    1 B
    1 C
    1 E
    2 A
    2 B
    2 C
    3 D
    4 A
    4 B
    4 E
    5 F
    5 G
    5 H
    6 F
    6 G
    6 H

      
    The data element names are wrong. KEY is a reserved word; “Categories" and "type" are called attribute properties in ISO-11179 rules. Matthias Kläy is right; this is a graph problem in disguise, but you can do it with set theory to get  what are called
    equivalence classes. 
    An edge in a graph has two nodes. Some authors allow a single node to count as a edge, but a better way is to put the same node on both ends of the edge. Here is the graph in a table with all the needed constraints. This is why you should post DDL and not be
    so rude.  
    DROP TABLE Graph;
    CREATE TABLE Graph
    (edge INTEGER NOT NULL,
     node_1 CHAR(1) NOT NULL,
     node_2 CHAR(1) NOT NULL,
     CHECK (node_1 <= node_2),
     PRIMARY KEY (node_1, node_2));
    Here is your data in the correct format. 
    INSERT INTO Graph 
    VALUES 
     (1, 'A', 'B'),
     (2, 'B', 'C'),
     (3, 'D', 'D'), -- orphan node
     (4, 'A', 'E'),
     (5, 'F', 'G'),
     (6, 'G', 'H');
    Now Google Warshall's Algorithm. It uses three nested loops and an adjacency array. This is very clean and fast in a procedural language. Not so much in SQL. Let us do this in steps:
    WITH X1 (edge, node1_1, node1_2, node2_1, node2_2 )
    AS
    (SELECT CASE WHEN G1.edge <> G2.edge 
           THEN G1.edge ELSE G2.edge END,
           G1.node_1, G1.node_2, 
           G2.node_1, G2.node_2       
      FROM Graph AS G1, Graph AS G2
     WHERE G1.node_1 IN (G2.node_1, G2.node_2) 
       AND G1.edge <> G2.edge),
    X2 (edge, node_1, node_2)
    AS
    (SELECT edge, 
    CASE WHEN node1_1 IN (node2_1, node2_2) THEN node1_2 ELSE node1_1 END,
    CASE WHEN node2_1 IN (node1_1, node1_2) THEN node2_2 ELSE node2_1 END
    FROM X1)
    SELECT DISTINCT edge,
           CASE WHEN node_1 < node_2 THEN node_1 ELSE node_2 END,
           CASE WHEN node_2 < node_1 THEN node_1 ELSE node_2 END
     FROM X2;
    The X1 subquery gets the paths of length two. The X2 subquery removes the middle node and creates a new sorted edge. Insert these new rows into Graphs, if they are not there. Repeat the process until no more rows are added. 
    DROP TABLE Graph;
    CREATE TABLE Graph
    (edge INTEGER NOT NULL,
     node_1 CHAR(1) NOT NULL,
     node_2 CHAR(1) NOT NULL,
     CHECK (node_1 <= node_2),
     PRIMARY KEY (node_1, node_2));
    INSERT INTO Graph 
    VALUES 
     (1, 'A', 'B'),
     (2, 'B', 'C'),
     (3, 'D', 'D'), -- orphan node
     (4, 'A', 'E'),
     (5, 'F', 'G'),
     (6, 'G', 'H');
    Here is the monster rolled up into a single statement. 
    INSERT INTO Graph
    SELECT DISTINCT edge,
           CASE WHEN node_1 < node_2 THEN node_1 ELSE node_2 END,
           CASE WHEN node_2 < node_1 THEN node_1 ELSE node_2 END
     FROM (SELECT edge, 
    CASE WHEN node1_1 IN (node2_1, node2_2) THEN node1_2 ELSE node1_1 END,
    CASE WHEN node2_1 IN (node1_1, node1_2) THEN node2_2 ELSE node2_1 END
    FROM 
    (SELECT CASE WHEN G1.edge < G2.edge 
           THEN G1.edge ELSE G2.edge END,
           G1.node_1, G1.node_2, 
           G2.node_1, G2.node_2       
      FROM Graph AS G1, Graph AS G2
     WHERE G1.node_1 IN (G2.node_1, G2.node_2) 
       AND G1.edge <> G2.edge) AS X1(edge,node1_1, node1_2, node2_1, node2_2) )
        AS X2(edge, node_1, node_2)
    EXCEPT 
     SELECT * FROM Graph;
     SELECT * FROM Graph ORDER BY edge, node_1, node_2;
    1 A B
    1 A C
    1 B E
    1 C E
    2 B C
    3 D D
    4 A E
    5 F G
    5 F H
    6 G H
    --CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
    in Sets / Trees and Hierarchies in SQL

  • SQL query to get a list of relations between workitems

    How can I create a SQL query to get a list of all problems with related changes?  And all problems with related incidents?
    I have tried to join the tables RelationshipTypeDim with ProblemDimKey and ChangeRequestDim, but the results are not correct.

    The relationships in the data warehouse can be kind of tricky. The relationships are contained in the WorkItemRelatesToWorkItemFactvw table. This table lists the related items by their WorkItemDimKey, so you cannot reference directly from the ChangeRequestDimvw
    or ProblemDimvw. You will need to reference the WorkItemDimvw to get the WorkItemDimKey for each entry.
    The query below will get all of the related work items from the Change Request class. The way the joins work is ChangeRequestDimvw gets the list of change requests. Then inner joins WorkItemDimvw to get the WorkItemDimKey for each CR. Then inner joins WorkItemRelatesToWorkItemFactvw
    to get all of the CRs with related work items. Then inner joins the WorkItemDimvw again to get the ID of the related work item. 
    Now the tricky part is it appears that these relationship are set based on which item  that created the relationship. So you need to union a second query that reverse the relationship on the WorkItemRelatesToWorkItemFactvw. 
    This query should give you a good start on getting the related work items. You can filter it down from here if you only want to include problems.
    SELECT C.ID, WIWI.ID
    FROM dbo.ChangeRequestDimvw C
    INNER JOIN dbo.WorkItemDimvw WI ON
    WI.EntityDimKey = C.EntityDimKey
    INNER JOIN dbo.WorkItemRelatesToWorkItemFactvw AS WIRWI ON
    WIRWI.WorkItemDimKey = WI.WorkItemDimKey
    INNER JOIN dbo.WorkItemDimvw AS WIWI ON
    WIWI.WorkItemDimKey = WIRWI.WorkItemRelatesToWorkItem_WorkItemDimKey
    union
    SELECT C.ID, WIWI.ID
    FROM dbo.ChangeRequestDimvw C
    INNER JOIN dbo.WorkItemDimvw WI ON
    WI.EntityDimKey = C.EntityDimKey
    INNER JOIN dbo.WorkItemRelatesToWorkItemFactvw AS WIRWI ON
    WIRWI.WorkItemRelatesToWorkItem_WorkItemDimKey = WI.WorkItemDimKey
    INNER JOIN dbo.WorkItemDimvw AS WIWI ON
    WIWI.WorkItemDimKey = WIRWI.WorkItemDimKey
    Order by C.ID
    Matthew Dowst |
    Blog | Twitter

Maybe you are looking for