FInding differences is successive rows in a table

Hi ,
I have a few Audit tables which store all the changes in Entities in my application.. so I have tables like
aud_table1, aud_table2 ...etc ... which have variable structure depending on actual entity audited.
Above table store the complete entity snapshot from original table as soon as they are updated. Now I need to create a difference view where I will compare adjacent rows to find out the difference and display to user. Is it possible to find these differences directly using Sql query may be using Pivot(Crosstabulation)

Hi,
It would by much more efficient to just make one pass through the table, like this:
WITH  cntr     AS
     SELECT     CASE     LEVEL
               WHEN  1  THEN  'Name'
               WHEN  2  THEN  'Quantity'
               WHEN  3      THEN  'Alias'
          END     AS fieldname
     FROM     dual
     CONNECT BY     LEVEL <= 3
,     unpivoted_data     AS
     SELECT     a.entityid
     ,     c.fieldname
     ,     CASE     c.fieldname
               WHEN  'Name'      THEN  a.name
               WHEN  'Quantity'  THEN  TO_CHAR (a.quantity)
               WHEN  'Alias'       THEN  a.alias
          END     AS newvalue
     ,      a.updatedby
     ,     a.updatedon
     FROM          auit_table     a
     CROSS JOIN     cntr          c
,     got_oldvalue     AS
     SELECT     u.*
     ,     LAG (newvalue, 1, newvalue) OVER ( PARTITION BY  entity_id
                                                  ,                fieldname
                                 ORDER BY      updatedon
                               ) AS oldvalue
     FROM     unpivoted_data     u
SELECT    entitiyid
,       fieldname
,       oldvalue
,       newvalue
,       updatedby
,       updatedon
FROM       got_oldvalue
WHERE       LNNVL (oldvalue = newvalue)
ORDER BY  entityid
,            updatedon
,       fieldname
;If you would post CREATE TABLE and INSERT statements for your sample data, then I could test this.
Edited by: Frank Kulash on May 18, 2010 11:59 PM
Tested

Similar Messages

  • How to find the difference between 2 rows in a table

    Hi all
    I have a table say emp which has only 2 rows
    emp
    empno name age sex deptno
    1 X 20 M 10
    2 Y 21 M 20
    The output should be
    empno name age deptno
    1 X 20 10
    2 Y 21 20
    Since the sex are same , so it is not included in the output.
    thanks
    Hari

    Hi there rajkumar,
    Although your lead solution is more elegant than the one presented below,
    I believe the complete answer it would be:
    with mytable as (
    SELECT ROW_NUMBER() OVER (ORDER BY EMPNO) POS, Z.* FROM (
    select 1 empno, 'X' name, 20 age, 'M' sex, 10 deptno from dual
    union
    select 2, 'Y', 21, 'M', 20 from dual) Z
    SELECT
    DECODE(A.EMPNO,B.EMPNO,NULL,A.EMPNO) EMPNO,
    DECODE(A.NAME,B.NAME,NULL,A.NAME) NAME,
    DECODE(A.AGE,B.AGE,NULL,A.AGE) AGE,
    DECODE(A.SEX,B.SEX,NULL,A.SEX) SEX,
    DECODE(A.DEPTNO,B.DEPTNO,NULL,A.DEPTNO) DEPTNO
    FROM
    (SELECT * FROM mytable WHERE POS = 1) A,
    (SELECT * FROM mytable WHERE POS = 2) B
    UNION
    SELECT
    DECODE(B.EMPNO,A.EMPNO,NULL,B.EMPNO) EMPNO,
    DECODE(B.NAME,A.NAME,NULL,B.NAME) NAME,
    DECODE(B.AGE,A.AGE,NULL,B.AGE) AGE,
    DECODE(B.SEX,A.SEX,NULL,B.SEX) SEX,
    DECODE(B.DEPTNO,A.DEPTNO,NULL,B.DEPTNO) DEPTNO
    FROM
    (SELECT * FROM mytable WHERE POS = 1) A,
    (SELECT * FROM mytable WHERE POS = 2) B
    Your query indeed returns NULL in the column for which values are the same, but still, you get just the first row.
    Anyway, the question is how to dinamically select the columns that hold NULL values, in the newly generated result. Because i believe the request is like this, if column holds equal values on both rows, then don't select the column (maybe i'm wrong).
    If this is the case then just by one sql it will not solve your problem, it needs to be more, with sqlplus and some other scripts checking the values in the columns, if it's not null then set an operator, and in the end (in sqlplus)
    select operator1, operator2 etc. from mytable.
    Hope it helps,
    Michael.
    [All the above presented is based on the fact that you shall always have TWO rows to be compared, having more or less it will fail!]
    Message was edited by:
    kjt

  • Difference between two rows of a table.

    Hi All,
    I have a requirement where I need to calculate the difference of a column, but the values are in two rows.
    Its exactly like this, I am having a table where in I have stored incidents with their status and their modified dates
    example:
    Incident_Id : Status : Modified_Date(in seconds from a specific date)
    1 : 1 : 9080890
    1 : 2 : 9080999
    1 : 3 : 9081900
    2 : 1 : 10000900
    2 : 2 : 10001000
    2 : 3 : 10002000
    Now the requirement is I have to show the time spent by each incident in each status.
    ie for status 1 I need the difference between modified date of status 2 and modified date of status 1 likewise
    for status 2 need the difference between modified date of status 3 and modified date of status 2 and so on.
    the actual result I need is like this
    Incident_Id : Status : Timespent
    1: 1: (modified_date(status2) - modified_date(status1))
    Please help me to write the query for this.
    Regards,
    Tauceef

    if only you have incremental status (example = 1,2,3, ... )
    WITH t (Incident_Id ,Status , Modified_Date) AS (
    SELECT 1 , 1 , 9080890 FROM dual UNION ALL
    SELECT 1 , 2 , 9080999 FROM dual UNION ALL
    SELECT 1 , 3 , 9081900 FROM dual UNION ALL
    SELECT 2 , 1 , 10000900 FROM dual UNION ALL
    SELECT 2 , 2 , 10001000 FROM dual UNION ALL
    SELECT 2 , 3 , 10002000 FROM dual )
    SELECT t1.Incident_Id, t1.Status, t1.Modified_Date , t2.Modified_Date-t1.Modified_Date
    FROM t t1
    LEFT JOIN t t2
    ON t2.Incident_Id = t1.Incident_Id
    AND t2.status = t1.status+1
    ORDER BY 1,2or
    there is no need to know what is the next status number :
    WITH t (Incident_Id ,Status , Modified_Date) AS (
    SELECT 1 , 1 , 9080890 FROM dual UNION ALL
    SELECT 1 , 2 , 9080999 FROM dual UNION ALL
    SELECT 1 , 3 , 9081900 FROM dual UNION ALL
    SELECT 2 , 1 , 10000900 FROM dual UNION ALL
    SELECT 2 , 2 , 10001000 FROM dual UNION ALL
    SELECT 2 , 3 , 10002000 FROM dual )
    SELECT t1.Incident_Id,
           t1.Status,
           t1.Modified_Date ,
           (LEAD(t1.Modified_Date) OVER (PARTITION BY t1.Incident_Id ORDER BY t1.status)) - t1.Modified_Date
    FROM t t1Edited by: Ramin Hashimzadeh on May 15, 2013 1:32 PM

  • Finding duplicate ranges for rows in a table

    Data in the table
    ROW NUM ID A_FROM A_TO B_FROM B_TO
    1 1 1 10 1 10
    2 1 1 20 2 20
    3 1 3 30 2 20
    4 2 10 20 10 20
    5 2 10 30 20 30
    6 3 10 20 10 20
    I want to identify rows based on "ID" columns which has overlaping range of data for column A and column B.
    example
    In above data based on ID 1 the row # 2 should be flagged due to the fact that col A_FROM and A_TO in row1 overlaps with row #1.
    Also, row #3 should be flagged due to the fact that col B_FROM and B_TO in row2 overlapps with row #2.
    Any help is appreciated.

    TABLE - "rate_table"
    ID     A_FROM     A_TO     B_FROM     B_TO     RATE
    1     10     20     100     200     0.5
    1     10     30     201     300     0.25
    1     31     40     200     300     0.25
    2     10     20     1000     2000     0.275
    2     21     30     1000     2000     0.385
    3     10     20     1000     2000     0.658
    3     10     30     2000     5000     0.541
    3     31     40     1000     2000     0.695
    Above table is being used to update another table based on ID column
    Update Statement
    Update table1 t
    set t.rate = (select r.rate from rate_table r
    where t.id = r.id and
    (t.col_a between r.a_from and r.a_to) and
    (t.col_b between r.b_from and r.b_to) )
    where exists
    (select 0 from rate_table r
    where t.id = r.id and
    (t.col_a between r.a_from and r.a_to) and
    (t.col_b between r.b_from and r.b_to) )
    This update would return error
    "ORA-01427: single-row subquery returns more than one row"
    This is due to the fact that while matching records against table TABLE1 to RATE_TABLE, the range for specific ID are overlapping.
    My question.
    How can I identity or avoid ORA-01427 error on the update statement? or how do i identity overlapping range records in RATE_TABLE?

  • PL/SQL-find out extra rows present in  table by comparing 2 similar tables

    Hi, can any one give me an idea to find out the extra rows present in table by comparing 2 similar tables using pl/sql.
    REQUIREMENT::i am working on the upgrade environment.my previous database has some tables and having data.Now functional folks are adding some new data to the existing tables for the upgrade database.I need to identify that new rows which are added by them.
    for this , i created name table with 2 columns n,n1 which contains the table names.
    Table Name:Name
    columns:n n1
    a ax
    b bx
    c cx
    a,b c........are the table names which are in the previous database environment.(approx >1500 tables)These tables having data.
    ax,bx,cx..........table names which are in the upgrade environment contains the extra data which is added by the functional folks.
    a&ax,b&bx.................(approx 1500 tables) are having same structure except some of them.
    Now i want to write a pl/sql program that reads both table names a&ax from name table and then by comparing the rows of a&ax ,i need to find out the extra rows present in the ax table to store that in different place.
    Example:
    a table
    id name
    1 co
    2 wi
    3 il
    ax table
    id name
    1 co
    2 wi
    3 il
    4 va
    5 ca
    Here i need to find out the difference b/n the 2 tables ,the extra rows id 4,5 and place it some where.

    this is just for demo, is this you mean?
    SQL> ed
    Wrote file afiedt.buf
      1  SELECT empno,ename,e.DEPTNO emp_deptno, d.deptno dept_deptno,d.DNAME
      2  FROM EMP e full outer join DEPT d
      3* on d.DEPTNO= e.DEPTNO
    SQL> /
         EMPNO ENAME      EMP_DEPTNO DEPT_DEPTNO DNAME
          7934 MILLER             10          10 ACCOUNTING
          7839 KING               10          10 ACCOUNTING
          7782 CLARK              10          10 ACCOUNTING
        snipp........
          7521 WARD               30          30 SALES
          7499 ALLEN              30          30 SALES
          156 1
    12 1
    40 OPERATIONS
    90 LOGISTIC
    18 rows selected.
    SQL> ed
    Wrote file afiedt.buf
      1  SELECT empno,ename,e.DEPTNO emp_deptno, d.deptno dept_deptno,d.DNAME
      2  FROM EMP e left outer join DEPT d
      3* on d.DEPTNO= e.DEPTNO
    SQL> /
         EMPNO ENAME      EMP_DEPTNO DEPT_DEPTNO DNAME
          7934 MILLER             10          10 ACCOUNTING
          7839 KING               10          10 ACCOUNTING
          7782 CLARK              10          10 ACCOUNTING
          7902 FORD               20          20 RESEARCH
        snipp..................
          7654 MARTIN             30          30 SALES
          7521 WARD               30          30 SALES
          7499 ALLEN              30          30 SALES
           156 1
    12 1
    16 rows selected.
    SQL> ed
    Wrote file afiedt.buf
      1  SELECT empno,ename,e.DEPTNO emp_deptno, d.deptno dept_deptno,d.DNAME
      2  FROM EMP e[b] right outer join  DEPT d
      3* on d.DEPTNO= e.DEPTNO
    SQL> /
         EMPNO ENAME      EMP_DEPTNO DEPT_DEPTNO DNAME
          7369 SMITH              20          20 RESEARCH
          7499 ALLEN              30          30 SALES
          7521 WARD               30          30 SALES
          7566 JONES              20          20 RESEARCH
          snipp......................
          7902 FORD               20          20 RESEARCH
          7934 MILLER             10          10 ACCOUNTING
                                             40 OPERATIONS
    90 LOGISTIC
    16 rows selected.

  • Number of rows in each table

    Hi
    How to find the number of rows in each table of a database by just using a SQL query,
    and should not use the data dictionary tables also... is there any way...??
    Thanks
    MJ

    It can be done in a single SQL like ->
    satyaki>
    satyaki>select * from v$version;
    BANNER
    Oracle Database 10g Enterprise Edition Release 10.2.0.1.0 - Prod
    PL/SQL Release 10.2.0.1.0 - Production
    CORE    10.2.0.1.0      Production
    TNS for Linux: Version 10.2.0.1.0 - Production
    NLSRTL Version 10.2.0.1.0 - Production
    Elapsed: 00:00:00.00
    satyaki>
    satyaki>
    satyaki>SELECT table_name,
      2         DBMS_XMLGEN.getxmltype ('SELECT Count(*) c FROM ' || table_name).EXTRACT ('//text()').ge
    tnumberval() tot_rows
      3  FROM user_tables;
    TABLE_NAME                       TOT_ROWS
    QUESTIONTYPE                            0
    SRGROUPTABLE                            1
    ST_TEST                                 4
    REGISTER                                0
    DEB_1                                   2
    EMP1                                    0
    6 rows selected.
    Elapsed: 00:00:12.04Credit goes to Michael. ;)
    Regards.
    Satyaki De.

  • Need to remove duplicate rows from a table

    Hi Gurus ,
    I am using oracle 11.2.0.3 .
    SQL> desc osstage.S_EVT_ACT_X;
    Name                                      Null?    Type
    ROW_ID                                    NOT NULL VARCHAR2(15 CHAR)
    LAST_UPD                                  NOT NULL DATE
    PAR_ROW_ID                                NOT NULL VARCHAR2(15 CHAR)
    ATTRIB_17                                          NUMBER(22,7)
    ATTRIB_26                                          DATE
    ATTRIB_02                                          VARCHAR2(100 CHAR)
    PROCESS_TIMESTAMP                                  TIMESTAMP(6);
    now when i give the below command it gives the error as someone has disabled the constraint accidently .
    alter table s_evt_act_x enable constraint S_EVT_ACT_X_P1;
    Error starting at line 3 in command:
    alter table s_evt_act_x enable constraint S_EVT_ACT_X_P1
    Error report:
    SQL Error: ORA-02437: cannot validate (OSSTAGE.S_EVT_ACT_X_P1) - primary key violated
    02437. 00000 -  "cannot validate (%s.%s) - primary key violated"
    *Cause:    attempted to validate a primary key with duplicate values or null
               values.
    *Action:   remove the duplicates and null values before enabling a primary
               key.
    Can you please guide me with this issue .

    Please refer
    Script: Deleting Duplicate Rows from a Table (Doc ID 31413.1)
    How to Find or Delete Duplicate Rows in a Table (Doc ID 1004425.6)

  • TableView Control(finding total no of Rows & Columns)

    Dear ALL SDN Members,
    Please tell me the method by which we can obtain total no. of rows and columns in TableView control.

    Hi,
    You can use Describe internal table to find the Number of Rows in the table control.or tablecontrol-lines will give the number of rows.
    for getting the number of columns you have to call the FM <b>REUSE_ALV_FIELDCATALOG_MERGE</b>
    data: v_lines type i.
    call function 'REUSE_ALV_FIELDCATALOG_MERGE'
    EXPORTING
       I_PROGRAM_NAME               = sy-repid
       I_INTERNAL_TABNAME           = 'ITAB'
       I_INCLNAME                   = sy-repid
      changing
        ct_fieldcat                  = IT_FIELDCAT
    EXCEPTIONS
       INCONSISTENT_INTERFACE       = 1
       PROGRAM_ERROR                = 2
       OTHERS                       = 3
    if sy-subrc <> 0.
    MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
             WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
    endif.
    describe table it_fieldcat lines v_lines.
    now v_lines will have the number of columns.
    Regards
    vijay

  • How to find rejected rows using External Table

    Hi all,
    I had written a stored procedure to read comma(,) separated flat file using External Tables in oracle 9i with Reject Limit "Unlimited" Option. Sometimes all rows are successfully loaded into external table and sometimes some rows are failed, I can find out those rows from logfile created by oracle. I want to inserted those rows key values into some other table. Can any body suggest/links how to write this.
    Thanking you in advance

    "Is there a way to have the system truncate the log files besides some O/S utility that will scour the directory every night, week, etc.?"
    You can use UTL_FILE.FREMOVE to delete the file, if you have sufficient privileges. You can schedule it using DBMS_JOB if you like or run it before you recreate the file, as demonstrated below. The pl/sql block to check whether the file exists is used for demonstration purposes only and is not necessary. This is just one method. There are various ways to delete or truncate a file. This just seems like the simplest.
    scott@ORA92> CREATE OR REPLACE DIRECTORY mydir AS 'c:\oracle'
      2  /
    Directory created.
    scott@ORA92> DECLARE
      2    v_bfile BFILE := BFILENAME ('MY_DIR', 'test_tab.log');
      3  BEGIN
      4    IF DBMS_LOB.FILEEXISTS (v_bfile) = 1
      5    THEN DBMS_OUTPUT.PUT_LINE ('test_tab.log exists');
      6    ELSE DBMS_OUTPUT.PUT_line ('test_tab.log does not exist');
      7    END IF;
      8  END;
      9  /
    test_tab.log exists
    PL/SQL procedure successfully completed.
    scott@ORA92> EXECUTE UTL_FILE.FREMOVE ('MY_DIR', 'test_tab.log')
    PL/SQL procedure successfully completed.
    scott@ORA92> DECLARE
      2    v_bfile BFILE := BFILENAME ('MY_DIR', 'test_tab.log');
      3  BEGIN
      4    IF DBMS_LOB.FILEEXISTS (v_bfile) = 1
      5    THEN DBMS_OUTPUT.PUT_LINE ('test_tab.log exists');
      6    ELSE DBMS_OUTPUT.PUT_line ('test_tab.log does not exist');
      7    END IF;
      8  END;
      9  /
    test_tab.log does not exist
    PL/SQL procedure successfully completed.
    scott@ORA92> CREATE TABLE test_tab
      2    (col1 NUMBER,
      3       col2 VARCHAR2(4))
      4  ORGANIZATION external
      5    (TYPE ORACLE_LOADER
      6       DEFAULT DIRECTORY mydir
      7       ACCESS PARAMETERS
      8         (RECORDS DELIMITED BY NEWLINE
      9          BADFILE 'MYDIR':'test_bad.bad'
    10          LOGFILE 'MYDIR':'test_tab.log'
    11          FIELDS TERMINATED BY ","
    12            (col1,
    13             col2))
    14       LOCATION ('test.dat'))
    15  REJECT LIMIT UNLIMITED
    16  /
    Table created.
    scott@ORA92> SELECT * FROM test_tab
      2  /
          COL1 COL2
             1 a
             2 b
    scott@ORA92> "Or is there a way to prevent the log from being written to every time it's accessed?"
    You can use NOLOGFILE as an access parameter to prevent it from being written to, as shown below.
    scott@ORA92> CREATE OR REPLACE DIRECTORY mydir AS 'c:\oracle'
      2  /
    Directory created.
    scott@ORA92> CREATE TABLE test_tab
      2    (col1 NUMBER,
      3       col2 VARCHAR2(4))
      4  ORGANIZATION external
      5    (TYPE ORACLE_LOADER
      6       DEFAULT DIRECTORY mydir
      7       ACCESS PARAMETERS
      8         (RECORDS DELIMITED BY NEWLINE
      9          BADFILE 'MYDIR':'test_bad.bad'
    10          NOLOGFILE
    11          FIELDS TERMINATED BY ","
    12            (col1,
    13             col2))
    14       LOCATION ('test.dat'))
    15  REJECT LIMIT UNLIMITED
    16  /
    Table created.
    scott@ORA92> SELECT * FROM test_tab
      2  /
          COL1 COL2
             1 a
             2 b
    scott@ORA92> "Is there a way to have the log written only when an error occurs?"
    Not that I know of, but that does not mean that somebody else doesn't know how or isn't able to figure out a way. If you do find a way, please post it for the benefit of the rest of us.

  • Difference between current row and previous row in a table

    Hi All,
    I am having a problem with the query. Can some of please help me?
    I need to get difference between current row and previous row in a table. I have a table, which have data like bellow.
    TABLEX
    ================
    Name Date Items
    AAA 01-SEP-09 100
    BBB 02-SEP-09 101
    CCC 03-SEP-09 200
    DDD 04-SEP-09 200
    EEE 05-SEP-09 400
    Now I need to get output like bellow...
    Name Date Items Diff-Items
    AAA 01-SEP-09 100 0
    BBB 02-SEP-09 101 1
    CCC 03-SEP-09 200 99
    DDD 04-SEP-09 200 0
    EEE 05-SEP-09 400 200
    Can some one help me to write a query to get above results?
    Please let me know if you need more information.
    Thanks a lot in advance.
    We are using Oracle10G(10.2.0.1.0).
    Thanks
    Asif

         , nvl (items - lag (items) over (order by dt), 0)like in
    SQL> with test as
      2  (
      3  select 'AAA' name, to_date('01-SEP-09', 'dd-MON-rr') dt,  100 items from dual union all
      4  select 'BBB' name, to_date('02-SEP-09', 'dd-MON-rr') dt,  101 items from dual union all
      5  select 'CCC' name, to_date('03-SEP-09', 'dd-MON-rr') dt,  200 items from dual union all
      6  select 'DDD' name, to_date('04-SEP-09', 'dd-MON-rr') dt,  200 items from dual union all
      7  select 'EEE' name, to_date('05-SEP-09', 'dd-MON-rr') dt,  400 items from dual
      8  )
      9  select name
    10       , dt
    11       , items
    12       , nvl (items - lag (items) over (order by dt), 0)
    13    from test
    14  ;
    NAM DT             ITEMS NVL(ITEMS-LAG(ITEMS)OVER(ORDERBYDT),0)
    AAA 01-SEP-09        100                                      0
    BBB 02-SEP-09        101                                      1
    CCC 03-SEP-09        200                                     99
    DDD 04-SEP-09        200                                      0
    EEE 05-SEP-09        400                                    200
    SQL>

  • How to find number of rows in a table

    i have one table ,it contains millions of record,how can i know number of rows in that table without using count(*),
    i tried in user_table ,for the column NUM_ROWS,but it is not showing number of rows,pls send me a solution for this.
    regards,
    singh

    Ok, that only was to show simply that max option
    might not an option to reduce execution time.Yes, but I/O variances have a tendency to really skew the observed elapsed execution time - making execution time alone a poor choice to determine what SQL will perform better than another.
    Both MAX(ROWNUM) and COUNT(*) results in the same amount of I/O - as both uses the exact same execution plan, I/O wise. In this example, a FTS.
    SQL> create table testtab nologging as select * from all_objects where rownum < 10001;
    Table created.
    -- warmed up the buffer cache with a couple of SELECTs against TESTAB in order
    -- to discard PIOs from the results
    SQL> set autotrace on
    SQL> select count(*) from testtab;
    COUNT(*)
    10000
    Execution Plan
    Plan hash value: 2656308840
    | Id | Operation | Name | Rows | Cost (%CPU)| Time |
    | 0 | SELECT STATEMENT | | 1 | 35 (9)| 00:00:01 |
    | 1 | SORT AGGREGATE | | 1 | | |
    | 2 | TABLE ACCESS FULL| TESTTAB | 9262 | 35 (9)| 00:00:01 |
    Note
    - dynamic sampling used for this statement
    Statistics
    0 recursive calls
    0 db block gets
    131 consistent gets
    0 physical reads
    0 redo size
    223 bytes sent via SQL*Net to client
    238 bytes received via SQL*Net from client
    2 SQL*Net roundtrips to/from client
    0 sorts (memory)
    0 sorts (disk)
    1 rows processed
    SQL> select max(rownum) from testtab;
    MAX(ROWNUM)
    10000
    Execution Plan
    Plan hash value: 2387991791
    | Id | Operation | Name | Rows | Cost (%CPU)| Time |
    | 0 | SELECT STATEMENT | | 1 | 35 (9)| 00:00:01 |
    | 1 | SORT AGGREGATE | | 1 | | |
    | 2 | COUNT | | | | |
    | 3 | TABLE ACCESS FULL| TESTTAB | 9262 | 35 (9)| 00:00:01 |
    Note
    - dynamic sampling used for this statement
    Statistics
    0 recursive calls
    0 db block gets
    131 consistent gets
    0 physical reads
    0 redo size
    225 bytes sent via SQL*Net to client
    238 bytes received via SQL*Net from client
    2 SQL*Net roundtrips to/from client
    0 sorts (memory)
    0 sorts (disk)
    1 rows processed
    So seeing that we have the exact same baseline for both queries, and that PIO does not influence the results, we time a 1000 executions of both.
    SQL> declare
    2 cnt number;
    3 begin
    4 for i in 1..1000
    5 loop
    6 select count(*) into cnt from testtab;
    7 end loop;
    8 end;
    9 /
    PL/SQL procedure successfully completed.
    Elapsed: 00:00:03.19
    SQL>
    SQL> declare
    2 cnt number;
    3 begin
    4 for i in 1..1000
    5 loop
    6 select max(rownum) into cnt from testtab;
    7 end loop;
    8 end;
    9 /
    PL/SQL procedure successfully completed.
    Elapsed: 00:00:15.87
    SQL>
    This shows that what makes the MAX() more expensive is just that - determining the MAX(). For each row, Oracle has to call its internal MAX() function with two values - the current max result and the new value. This function then returns the new max value. This overhead per row adds up to a significant overhead in execution time - making the MAX() approach 5x slower than the COUNT() approach.

  • How to find middle row in a table ?

    Hi Friends,
    Is it possible to find middle row in a table by SQL Query.
    KarTiK.

    Solution: sort the rows in order to create an ordered
    sequence and then there will be a "middle row".Well, not quite.
    If there are an odd number of rows then, yes, there will be a middle row in an ordered sequence, however if there is an even number of rows then the middle is between two rows... or... you could take it as the two rows either side of the middle....
    SQL> select * from emp order by empno;
         EMPNO ENAME      JOB              MGR HIREDATE                   SAL       COMM     DEPTNO
          7369 SMITH      CLERK           7902 17/12/1980 00:00:00        800                    20
          7499 ALLEN      SALESMAN        7698 20/02/1981 00:00:00       1600        300         30
          7521 WARD       SALESMAN        7698 22/02/1981 00:00:00       1250        500         30
          7566 JONES      MANAGER         7839 02/04/1981 00:00:00       2975                    20
          7654 MARTIN     SALESMAN        7698 28/09/1981 00:00:00       1250       1400         30
          7698 BLAKE      MANAGER         7839 01/05/1981 00:00:00       2850                    30
          7782 CLARK      MANAGER         7839 09/06/1981 00:00:00       2450                    10
          7788 SCOTT      ANALYST         7566 19/04/1987 00:00:00       3000                    20
          7839 KING       PRESIDENT            17/11/1981 00:00:00       5000                    10
          7844 TURNER     SALESMAN        7698 08/09/1981 00:00:00       1500          0         30
          7876 ADAMS      CLERK           7788 23/05/1987 00:00:00       1100                    20
          7900 JAMES      CLERK           7698 03/12/1981 00:00:00        950                    30
          7902 FORD       ANALYST         7566 03/12/1981 00:00:00       3000                    20
          7934 MILLER     CLERK           7782 23/01/1982 00:00:00       1300                    10
    14 rows selected.
    SQL> select e.empno, e.ename, e.job, e.mgr, e.hiredate, e.sal, e.comm, e.deptno
      2  from (select emp.*, row_number() over (order by empno) as rn from emp) e
      3      ,(select round(count(*)/2) as middle, round(((count(*)+1)/2)) as middle2 from emp) m
      4  where e.rn in (m.middle, m.middle2)
      5  /
         EMPNO ENAME      JOB              MGR HIREDATE                   SAL       COMM     DEPTNO
          7782 CLARK      MANAGER         7839 09/06/1981 00:00:00       2450                    10
          7788 SCOTT      ANALYST         7566 19/04/1987 00:00:00       3000                    20
    SQL> insert into emp values (1111, 'WILLIS', 'CLERK', 7902, sysdate, 900, null, 20);
    1 row created.
    SQL> select * from emp order by empno;
         EMPNO ENAME      JOB              MGR HIREDATE                   SAL       COMM     DEPTNO
          1111 WILLIS     CLERK           7902 18/01/2008 12:18:14        900                    20
          7369 SMITH      CLERK           7902 17/12/1980 00:00:00        800                    20
          7499 ALLEN      SALESMAN        7698 20/02/1981 00:00:00       1600        300         30
          7521 WARD       SALESMAN        7698 22/02/1981 00:00:00       1250        500         30
          7566 JONES      MANAGER         7839 02/04/1981 00:00:00       2975                    20
          7654 MARTIN     SALESMAN        7698 28/09/1981 00:00:00       1250       1400         30
          7698 BLAKE      MANAGER         7839 01/05/1981 00:00:00       2850                    30
          7782 CLARK      MANAGER         7839 09/06/1981 00:00:00       2450                    10
          7788 SCOTT      ANALYST         7566 19/04/1987 00:00:00       3000                    20
          7839 KING       PRESIDENT            17/11/1981 00:00:00       5000                    10
          7844 TURNER     SALESMAN        7698 08/09/1981 00:00:00       1500          0         30
          7876 ADAMS      CLERK           7788 23/05/1987 00:00:00       1100                    20
          7900 JAMES      CLERK           7698 03/12/1981 00:00:00        950                    30
          7902 FORD       ANALYST         7566 03/12/1981 00:00:00       3000                    20
          7934 MILLER     CLERK           7782 23/01/1982 00:00:00       1300                    10
    15 rows selected.
    SQL> select e.empno, e.ename, e.job, e.mgr, e.hiredate, e.sal, e.comm, e.deptno
      2  from (select emp.*, row_number() over (order by empno) as rn from emp) e
      3      ,(select round(count(*)/2) as middle, round(((count(*)+1)/2)) as middle2 from emp) m
      4  where e.rn in (m.middle, m.middle2)
      5  /
         EMPNO ENAME      JOB              MGR HIREDATE                   SAL       COMM     DEPTNO
          7782 CLARK      MANAGER         7839 09/06/1981 00:00:00       2450                    10
    SQL>

  • Can we find the number of rows in table from the dump file

    Hi All,
    Can we find the number of rows in table from the dump file with out importing the table in to the database?
    Please let me know ,if any option is there.
    Thanks,
    Kumar.

    <s>Try to import with option SHOW=Y, that should skip the number of rows which are into a table from a dump file.</s><br>
    <br>
    Nicolas.<br>
    Oops, sorry, that doesn't show the number of lines...<br>
    Message was edited by: <br>
    N. Gasparotto

  • How to find who has locked a row in a table?

    My DB is a Oracle Database 10g Enterprise Edition Release 10.2.0.4.0.
    My question is very simple: You try to update a row of a table but find out it is locked by somebody else.
    How do I find which user (or session) has locked that row?

    SELECT Decode(request, 0, 'Holder: ',
                           'Waiter: ')
           ||vl.sid sess,
           status,
           id1,
           id2,
           lmode,
           request,
           vl.TYPE
    FROM   v$lock vl,
           v$session vs
    WHERE  ( id1, id2, vl.TYPE ) IN (SELECT id1,
                                            id2,
                                            TYPE
                                     FROM   v$lock
                                     WHERE  request > 0)
           AND vl.sid = vs.sid
    ORDER  BY id1,
              request

  • Why there is a huge difference between a row size on a disk based table and a row size in memoptimized table of SQL 2014?

    Hi All,
    I have two table with similar structure and data, one is on disk and the other is in memory. I somehow calculated the difference between a row size of on disk and in memory table and found that the row size of in memory is 700 Bytes more than the disk based
    tables.
    aa

    As others mentioned, memory optimized tables and disk based tables have different structures in SQL Server 2014.
    For memory optimized tables, the number of indexes on table also contribute to the size. You can calculate the exact size of rows and thus the table size using the formula given in the below articles
    Table and Row Size in Memory-Optimized Tables
    Estimate the Size of a Table
    Krishnakumar S

Maybe you are looking for

  • Hard Cover

    I haven't purchased a hard cover book yet but I want to know if I don't want to use the dust jacket, will I have the title and cover photo on the actual hard cover of the album?

  • Brush licensing in illustrator

    Recently I was doing a few designs and I wanted to draw a design uses brushes that mimic painting and I found some in the brush library. After using them I realized since it didn't create those brushes it wasn't fully my design. Can the brushes be us

  • Can't delete the Element enty, which is marked as XXSalary

    Hi experts i have created a person, than using Entries. Th window showing me in the Entries the element: XXSalary. If i try to delete this record, the system doesn't allow me, ebcause the X on the menue bar is deactive. But if i have another elements

  • Single Inbox on Unity Connection 8.5 and Exchange 2003 SP2

    Hi, We have Unity Connection 8.5 (with SU2) and Exchange 2003 SP2 We want to setup the Single Inbox feature that works well with Exchange 2007 and 2010, but my customer is running Exchange 2003 SP2. We met all of the requirements outlined in: http://

  • Maps 3.01 and low memory

    I had to reset my N97 to factory standards and I uninstalled the latest version of maps .I think it is 3.03. Now I am trying to reinstall it, but it tells me I don't have enough memory. I have 14.3mb free in phone memory. is there a way to uninstall