Determine the maximum length of a column and its use in the same query?

I would like to determine the maximum length of a column and use it in the same query. Is this possible? IE:

SELECT RPAD (last_name, SELECT MAX (LENGTH (last_name)) + 5 FROM user, '-')
OF the user.

Thank you

Hello

Welcome to the forum!

jfraley wrote:
I would like to determine the maximum length of a column and use it in the same query. Is this possible? IE:

SELECT RPAD (last_name, SELECT MAX (LENGTH (last_name)) + 5 FROM user, '-')
OF the user.

Thank you

Sure. You almost go in your message: a scalar subquery . Just put brackets around the subquery:

SELECT      RPAD ( last_name
          , (
             SELECT  MAX (LENGTH (last_name)) + 5
             FROM    user_tbl          -- USER is not a good table name
            )
          , '-'
          )          AS padded_last_name
FROM      user_tbl
;

Scalar subqueries in SQL are like tape in your garage in canvas: they are used for thousands of different things and open, maybe 1% of them. Usually, there are better ways to achieve the same results, such as the analytical functions:

SELECT      RPAD ( last_name
          , 5 + MAX (LENGTH (last_name)) OVER ()
          , '-'
          )          AS padded_last_name
FROM      user_tbl
;

Still another way is to make the subquery and then join his game as if it were a table of results:

WITH     got_max_length     AS
(
     SELECT     MAX (LENGTH (last_name))     AS max_length
     FROM     user_tbl
)
SELECT      RPAD ( u.last_name
          , m.max_length + 5
          , '-'
          )          AS padded_last_name
FROM           user_tbl     u
CROSS JOIN     got_max_length     m
;

Published by: Frank Kulash, December 12, 2011 21:17
Added cross join example

Tags: Database

Similar Questions

  • Maximum length of a column?

    Is there a way to know the maximum length of a column in a table?


    Thanks for the help.
    select max(length(yourcolumn)) from yourtable;
    
  • explain plan for the same query diff

    Hi experts,

    Please, help me understand explain the plan.  I have tow Server (server and two server). The server are same table, even the type of database, even version Oracle (gr 11 (2), same operating system (linux Redhat 5.5) and same table and index.

    but when I explain the plan for the same query on the two server. I got diff--diff to explain the plan. reason it has different, according to my understanding, it should be same. explain please, I share the explain plan and lower indices for the two server.

    Server a

    SQL > col COLUMN_NAME format a20

    SQL > select index_name, column_name, position_colonne from user_ind_columns where table_name = 'LOAN_RUNNING_DETAILS_SOUTH"of order 1.

    INDEX_NAME COLUMN_NAME POSITION_COLONNE

    ------------------------------ -------------------- ---------------

    DATE_IND1_S LOANDATETIME 1

    IND_MSI_LN_LNS1_S MSISDN 1

    IND_MSI_LN_LNS1_S LOANDATETIME 2

    IND_MSI_LN_LNS1_S LOANSTATUS 3

    LAST_INDEX L_INDX_MSISDN_S 1

    MSISDN L_INDX_MSISDN_S 2

    SQL > select decode (status, 'N/a', 'Part Hdr', 'Global') ind_type, index_name, NULL nom_partition, status

    2 from user_indexes where table_name = 'LOAN_RUNNING_DETAILS_SOUTH '.

    3 union

    4. Select 'Local' ind_type, index_name, nom_partition, status

    5 to user_ind_partitions where index-name in (select index_name in user_indexes where table_name = 'LOAN_RUNNING_DETAILS_SOUTH')

    6 order of 1,2,3;

    IND_TYPE INDEX_NAME NOM_PARTITION STATUS

    -------- ------------------------------ ------------------------------ --------

    Global DATE_IND1_S VALID

    Global IND_MSI_LN_LNS1_S VALID

    Global L_INDX_MSISDN_S VALID

    SQL > explain plan for the small circle of MSISDN, TID, of LOAN_RUNNING_DETAILS_SOUTH where LOANDATETIME < = sysdate-2 and LOANDATETIME > sysdate-15 and LOANTYPE = 1;

    He explained.

    SQL > SQL > set line 200

    @?/rdbms/admin/utlxpls.sql

    SQL >

    PLAN_TABLE_OUTPUT

    --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    Hash value of plan: 3659874059

    ------------------------------------------------------------------------------------------------------------------

    | ID | Operation | Name                       | Lines | Bytes | Cost (% CPU). Time | Pstart. Pstop |

    ------------------------------------------------------------------------------------------------------------------

    |   0 | SELECT STATEMENT |                            |  1448K |    58 M | 21973 (2) | 00:04:24 |       |       |

    |*  1 |  FILTER |                            |       |       |            |          |       |       |

    |   2.   PARTITION LIST ALL |                            |  1448K |    58 M | 21973 (2) | 00:04:24 |     1.    11.

    |*  3 |    TABLE ACCESS FULL | LOAN_RUNNING_DETAILS_SOUTH |  1448K |    58 M | 21973 (2) | 00:04:24 |     1.    11.

    ------------------------------------------------------------------------------------------------------------------

    PLAN_TABLE_OUTPUT

    --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    Information of predicates (identified by the operation identity card):

    ---------------------------------------------------

    1 - filter(SYSDATE@!-2>SYSDATE@!-15)

    3 - filter("LOANTYPE"=1 AND "LOANDATETIME">SYSDATE@!-15 AND "LOANDATETIME"<=SYSDATE@!-2)

    16 selected lines.

    Second server

    SQL > select index_name, column_name, position_colonne from user_ind_columns where table_name = 'LOAN_RUNNING_DETAILS_SOUTH"of order 1.

    INDEX_NAME COLUMN_NAME POSITION_COLONNE

    ------------------------------ -------------------- ---------------

    DATE_IND1_S LOANDATETIME 1

    IND_MSI_LN_LNS1_S MSISDN 1

    IND_MSI_LN_LNS1_S LOANDATETIME 2

    IND_MSI_LN_LNS1_S LOANSTATUS 3

    LAST_INDEX L_INDX_MSISDN_S 1

    MSISDN L_INDX_MSISDN_S 2

    SQL > select decode (status, 'N/a', 'Part Hdr', 'Global') ind_type, index_name, NULL nom_partition, status

    2 from user_indexes where table_name = 'LOAN_RUNNING_DETAILS_SOUTH '.

    Union

    3 4 Select 'Local' ind_type, index_name, nom_partition, status

    5 to user_ind_partitions where index-name in (select index_name in user_indexes where table_name = 'LOAN_RUNNING_DETAILS_SOUTH')

    6 order of 1,2,3;

    IND_TYPE INDEX_NAME NOM_PARTITION STATUS

    -------- ------------------------------ ------------------------------ --------

    Global DATE_IND1_S VALID

    Global IND_MSI_LN_LNS1_S VALID

    Global L_INDX_MSISDN_S VALID

    SQL > explain plan for the small circle of MSISDN, TID, of LOAN_RUNNING_DETAILS_SOUTH where LOANDATETIME < = sysdate-2 and LOANDATETIME > sysdate-15 and LOANTYPE = 1;

    SQL > set line 200

    @?/rdbms/admin/utlxpls.sql

    SQL >

    PLAN_TABLE_OUTPUT

    --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    Hash value of plan: 1161680601

    ----------------------------------------------------------------------------------------------------------------------------------

    | ID | Operation | Name                       | Lines | Bytes | Cost (% CPU). Time | Pstart. Pstop |

    ----------------------------------------------------------------------------------------------------------------------------------

    |   0 | SELECT STATEMENT |                            |     2.    84.     5 (0) | 00:00:01 |       |       |

    |*  1 |  FILTER                             |                            |       |       |            |          |       |       |

    |*  2 |   TABLE ACCESS BY INDEX ROWID | LOAN_RUNNING_DETAILS_SOUTH |     2.    84.     5 (0) | 00:00:01 | ROWID | ROWID |

    |*  3 |    INDEX RANGE SCAN | DATE_IND1_S |     2.       |     3 (0) | 00:00:01 |       |       |

    ----------------------------------------------------------------------------------------------------------------------------------

    PLAN_TABLE_OUTPUT

    --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    Information of predicates (identified by the operation identity card):

    ---------------------------------------------------

    1 - filter(SYSDATE@!-2>SYSDATE@!-15)

    2 - filter ("LOANTYPE" = 1)

    3 - access("LOANDATETIME">SYSDATE@!-15 AND "LOANDATETIME"<=SYSDATE@!-2)

    17 selected lines.

    Reg,

    Hard

    Hi , HemantKChitale,

    I also update statistics manual as you say, but not see 'TABLE ACCESS FULL' good result

    What should I do? my need of production tuning, but I cannot able tune this...

    SQL > exec dbms_stats.gather_table_stats (-online 'ttt' ownname, tabname => 'LOAN_RUNNING_DETAILS_SOUTH', cascade => TRUE, estimate_percent => NULL, method_opt => 'for all columns size 254', => of degree 4);

    PL/SQL procedure successfully completed.

    SQL > explain plan for the small circle of MSISDN, TID, of LOAN_RUNNING_DETAILS_SOUTH where LOANDATETIME<=sysdate-2 and="" loandatetime="">sysdate-15 and LOANTYPE = 1;

    He explained.

    SQL > set line 200

    @?/rdbms/admin/utlxpls.sql

    SQL >

    PLAN_TABLE_OUTPUT

    --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    Hash value of plan: 3659874059

    ------------------------------------------------------------------------------------------------------------------

    | ID | Operation | Name                       | Lines | Bytes | Cost (% CPU). Time | Pstart. Pstop |

    ------------------------------------------------------------------------------------------------------------------

    |   0 | SELECT STATEMENT |                            |  1874K |    75 M | 19626 (2) | 00:03:56 |       |       |

    |*  1 |  FILTER |                            |       |       |            |          |       |       |

    |   2.   PARTITION LIST ALL |                            |  1874K |    75 M | 19626 (2) | 00:03:56 |     1.    11.

    |*  3 |    TABLE ACCESS FULL | LOAN_RUNNING_DETAILS_SOUTH |  1874K |    75 M | 19626 (2) | 00:03:56 |     1.    11.

    ------------------------------------------------------------------------------------------------------------------

    PLAN_TABLE_OUTPUT

    --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    Information of predicates (identified by the operation identity card):

    ---------------------------------------------------

    1 - filter(SYSDATE@!-2>SYSDATE@!-15)

    3 - filter("LOANDATETIME">SYSDATE@!-15 AND "LOANTYPE"=1 AND "LOANDATETIME")<>

    16 selected lines.

  • Why I have two different execution plans for the same query on two different servers

    Hello everyone.

    I need your help to solve the problem quickly.

    In a nutshell, we have two servers that have the same version of Oracle RDBMS (11.2.0.4 EE). One of them for purposes of development and another is a production one.

    We have therefore two different execution plans for the same query executed on both servers. The only case of execution is OK and another is too slow.

    So I have to slow down the work of query using the same scheme to explain that young.

    Fence wire.

  • Avoid using the same query...

    How can I avoid to use the same query again and again using a single query, such as

    SELECT
    a,
    b * (SELECT COUNT (C1) FROM T2);
    c * (SELECT COUNT (C1) FROM T2);
    d * (SELECT COUNT (C1) FROM T2)
    Of
    T1;

    Fanny says:
    How can I avoid to use the same query again and again using a single query, such as

    SELECT
    a,
    b * (SELECT COUNT (C1) FROM T2);
    c * (SELECT COUNT (C1) FROM T2);
    d * (SELECT COUNT (C1) FROM T2)
    Of
    T1;

    A few cross join?

    select a, b*cnt, c*cnt, d*cnt
      from t1, (select count(c1) cnt from t2)
    
  • FK two in the same query/tabe

    I'm trying to return two fields in the table even through two joins in the same query.

    Take this example:
    : Table
    ID Varchar PK
    Name Varchar
    FK Varchar Person.ID Chief
    Backup of Varchar Person.ID FK

    DATA:
    1 MyProduct 123 345
    2 YouProdct 345 678

    Table: person
    ID Varchar PK
    Name Varchar

    DATA
    John 123
    James 345
    Tom 678

    I need to come back

    RESULT:
    Name Leader Backup
    MyProduct John James
    Tom James YouProdct

    I have a lot of different queries, but I always get what looks like a Cartesian product or a syntax error.

    Thanks in advance

    Published by: jdc114 on March 28, 2009 17:20

    What have you tried? It seems to me

    SELECT product.name, leader.name, backup.name
      FROM product,
           person leader,
           person backup
     WHERE product.leader = leader.id
       AND product.backup = backup.id
    

    would be sufficient.

    Justin

  • Different output for the same query in SQL Server and Oracle

    I have two tables table1 and table2

    -table1 has two columns c1 int and varchar c2. There are no constraints added in it. It contains data as shown below

    C1 c2
    -------------------
    d 6
    5 d
    102 g
    6%
    f 103
    5.
    501 j
    1 g
    601 n
    2 m

    -table2 has only a single column c1 int. There is no added in constraints. It contains data as shown below

    C1
    ----
    6
    1
    4
    3
    2

    now when I run below, given the query in sql server and oracle it gives me different results

    Select *.
    FROM table1
    table2 on table2.c1 = table1.c1 inner join (SELECT ROW_NUMBER() (any ORDER by ASC c1) AS c1 from table2)

    output of SQL server
    ------------------------
    C1 c2 c1
    --------------------------------
    1 g 1
    2 m 2
    3 h 3
    4 g 4
    5 d 5


    release of Oracle
    ----------------------
    C1 C2 C1
    ---------------------------------
    5 d 5
    4 g 4
    3 h 3
    1 g 1
    2 m 2


    If you notice the first column in the two outputs. It is sorted in sql server and no oracle.

    Why he behaves differently in oracle? Is there a way I can fix this problem in oracle?

    Thank you
    Jigs

    It is NOT a behavior "differently" in Oracle; you did not specify just an order that you expect of your results, so you'll get output in what order the fantasies of the database showing (ie. no guaranteed order). It is an artifact of the way the database chooses to collect the data and databases (or same sets of data within the same database) can and will most likely behave differently.

    Same SQL Server will not be guaranteed to always get your data in an orderly manner if you exclude the order by clause, even if you think that there always display the data in an orderly manner.

    Your solution is to add an order by clause, in the TWO databases, to force the order of the data output.

  • spend multiple lines of the same query in params/variables and display

    Hi guys :)
    I can really use your help in something so that I can not find a solution.
    I need to write a procedure that displays the number of lines by an object any and it will display.

    I can write the sql query, but I can't find a way to do it in the pl/sql procedure.

    I need to pass these results in params or variables and display in dbms.output.


    SYS > select count (par_res_id), election_master.results par_res_id
    2 the par_res_id group;

    COUNT (PAR_RES_ID) PAR_RES_ID
    ----------------- ----------
    24 1
    40 2
    54 4
    5 of 23
    59 3

    could u please help.


    Thanks in advance

    Published by: 915417 on March 3, 2012 06:49
  • understand row_number() and its use in analytic function

    Hello all;

    I've been playing with row_number and trying to figure out how to use it, and yet I still can't understand...

    I have the following code below
    create table Employee(
        ID                 VARCHAR2(4 BYTE)         NOT NULL,
       First_Name         VARCHAR2(10 BYTE),
       Last_Name          VARCHAR2(10 BYTE),
        Start_Date         DATE,
        End_Date           DATE,
         Salary             Number(8,2),
       City               VARCHAR2(10 BYTE),
        Description        VARCHAR2(15 BYTE)
     )
     
    
    insert into Employee(ID,  First_Name, Last_Name, Start_Date,                     End_Date,                       Salary,  City,       Description)
                 values ('01','Jason',    'Martin',  to_date('19960725','YYYYMMDD'), to_date('20060725','YYYYMMDD'), 1234.56, 'Toronto',  'Programmer');
    
    
    
    
    insert into Employee(ID,  First_Name, Last_Name, Start_Date,                     End_Date,                       Salary,  City,       Description)
                  values('02','Alison',   'Mathews', to_date('19760321','YYYYMMDD'), to_date('19860221','YYYYMMDD'), 6661.78, 'Vancouver','Tester')
    
    
    
    
     insert into Employee(ID,  First_Name, Last_Name, Start_Date,                     End_Date,                       Salary,  City,       Description)
                 values('03','James',    'Smith',   to_date('19781212','YYYYMMDD'), to_date('19900315','YYYYMMDD'), 6544.78, 'Vancouver','Tester')
    
    
    
    
    insert into Employee(ID,  First_Name, Last_Name, Start_Date,                     End_Date,                       Salary,  City,       Description)
                  values('04','Celia',    'Rice',    to_date('19821024','YYYYMMDD'), to_date('19990421','YYYYMMDD'), 2344.78, 'Vancouver','Manager')
    
    
    
    
    insert into Employee(ID,  First_Name, Last_Name, Start_Date,                     End_Date,                       Salary,  City,       Description)
                  values('05','Robert',   'Black',   to_date('19840115','YYYYMMDD'), to_date('19980808','YYYYMMDD'), 2334.78, 'Vancouver','Tester')
    
    
    
    
     insert into Employee(ID,  First_Name, Last_Name, Start_Date,                     End_Date,                       Salary, City,        Description)
                  values('06','Linda',    'Green',   to_date('19870730','YYYYMMDD'), to_date('19960104','YYYYMMDD'), 4322.78,'New York',  'Tester')
    
    
    
    
    insert into Employee(ID,  First_Name, Last_Name, Start_Date,                     End_Date,                       Salary, City,        Description)
                  values('07','David',    'Larry',   to_date('19901231','YYYYMMDD'), to_date('19980212','YYYYMMDD'), 7897.78,'New York',  'Manager')
    
    
    
    
    insert into Employee(ID,  First_Name, Last_Name, Start_Date,                     End_Date,                       Salary, City,        Description)
                   values('08','James',    'Cat',     to_date('19960917','YYYYMMDD'), to_date('20020415','YYYYMMDD'), 1232.78,'Vancouver', 'Tester')
    I made a simple select statement

    Select * from employee

    and it returns it below
    ID   FIRST_NAME LAST_NAME  START_DAT END_DATE      SALARY CITY       DESCRIPTION
    ---- ---------- ---------- --------- --------- ---------- ---------- ---------------
    01   Jason      Martin     25-JUL-96 25-JUL-06    1234.56 Toronto    Programmer
    02   Alison     Mathews    21-MAR-76 21-FEB-86    6661.78 Vancouver  Tester
    03   James      Smith      12-DEC-78 15-MAR-90    6544.78 Vancouver  Tester
    04   Celia      Rice       24-OCT-82 21-APR-99    2344.78 Vancouver  Manager
    05   Robert     Black      15-JAN-84 08-AUG-98    2334.78 Vancouver  Tester
    06   Linda      Green      30-JUL-87 04-JAN-96    4322.78 New York   Tester
    07   David      Larry      31-DEC-90 12-FEB-98    7897.78 New York   Manager
    08   James      Cat        17-SEP-96 15-APR-02    1232.78 Vancouver  Tester
    I wrote another select statement with row_number. See below
    SELECT first_name, last_name, salary, city, description, id,
       ROW_NUMBER() OVER(PARTITION BY description ORDER BY city desc) "Test#"
       FROM employee
       
    and I get this result
    First_name  last_name   Salary         City             Description         ID         Test#
    Celina          Rice         2344.78      Vancouver    Manager             04          1
    David          Larry         7897.78      New York    Manager             07          2
    Jason          Martin       1234.56      Toronto      Programmer        01          1
    Alison         Mathews    6661.78      Vancouver   Tester               02          1  
    James         Cat           1232.78      Vancouver    Tester              08          2
    Robert        Black         2334.78     Vancouver     Tester              05          3
    James        Smith         6544.78     Vancouver     Tester              03          4
    Linda         Green        4322.78      New York      Tester             06           5
    I understand the partition by which means basically for each associated group a unique number wiill be assigned for that row, so in this case since tester is one group, manager is another group, and programmer is another group then tester gets its own unique number for each row, manager as well and etc.
    What is throwing me, that's the order of and how these numbers are assigned. Why is

    1 assigned to Alison Mathews for the tester group and 2 assigned to James Cat and assigned 3 Robert Black

    I apologize if this is a stupid question, I tried to read about this online and looking at the oracle documentation, but still do not understand why.

    user13328581 wrote:
    What is throwing me, that's the order of and how these numbers are assigned. Why is

    1 assigned to Alison Mathews for the tester group and 2 assigned to James Cat and assigned 3 Robert Black

    Description (partition by column) and city (control column) values are same for Alison, James and Robert, no sort order of these 3 records be held valid.
    Oracle just happened to choose a. What do you think should be the numbering "correct"?

  • Is the same query?

    Hi all, this question is the same?
    They get the same number of rows.

    Select employe_id, last_name, department_id
    employees
    departments of natural join
    where department_id (100);

    Select a.employee_id, a.last_name, b.department_id
    employee a, b ministries
    where a.department_id = b.department_id
    and a.department_id = 100;


    How they work?
    Thank you...!!

    Hi all, this question is the same?
    They get the same number of rows.

    You answered your own question.

    Of this manual:
    http://download.Oracle.com/docs/CD/B28359_01/server.111/b28286/statements_10002.htm

    "A natural join is based on all of the columns in the two tables with the same name."

    NATURAL JOIN is unsafe. A column can be added to the table and break your code.

    If your first query (with NATURAL JOIN) is equivalent to this:

    select  e.employee_id, e.last_name, e.department_id
    from    employees    e
    join    departments  d
    on      e.department_id = d.department_id
            and e.manager_id = d.manager_id
    where   e.department_id in (100);
    
  • I use the same query in two difference db (exp/imp) but run different times!

    Hello

    I have 2 database. One of the remote server, one at my local. I used exp/imp to retrieve data from remote to my local database. Structers, tables and indexes is the same.
    My local machine is more powerful than the remote computer. (Ram, cpu County ext)

    But when I connect remotely from my local computer, this application runs 4 second (with view). But when I connect to my local db, this query run 5 minutes.
    Number of rows returned is 18,500

    What's wrong? Why get the bytes of the value are different?

    Local explain plan is:
    SELECT STATEMENT ALL_ROWS Cost: 203 Bytes: 19,062,160 Cardinality: 18,329                                         
    Remote control explain plan is:
    SELECT STATEMENT ALL_ROWS Cost: 226 Bytes: 3,855,214 Cardinality: 18,446                                         
    My plans to explain (remote and the) and other (auto track, oracle params) data is in excel file (because of this forum not to accept more than 30,000 words);

    http://www.eksicevap.com/tech/explainplan.xls
    for winrar:
    http://www.eksicevap.com/tech/explainplan.rar

    Thanks for help

    Oracel version information:
    Local:
    Oracle Database 11g Enterprise Edition Release 11.1.0.6.0 - Production
    Distance:
    Oracle Database 10g Enterprise Edition Release 10.2.0.1.0 - 64bi

    Published by: Melike on 15.Mar.2011 02:42

    Published by: Melike on 15.Mar.2011 03:39

    Melike says:
    Thanks, Johan, I'll try.
    My first post for local oracle param, I got it 3 days ago. or I confuse my file params to oracle. (This problem continues from last week)
    Now I'm waiting still current oracle local params and these value is worse:

    Local:
    pga_aggregate_target 0
    SGA_MAX_SIZE 536.870.912
    SGA_TARGET 0

    I update the new oracle local params in my previous message.

    I'll try the update of these values, but I hope, my local oracle is not drop down :)

    Can't be worse...
    You have a parameter memory_target (and max_memory_target)? If so, you could add memory to these settings as well and only set pga_aggregate_target (no CMS or sga_max)

    My settings (on a test/dev/lab-box):
    System@oracle11 SQL > see the memory settings

    VALUE OF TYPE NAME
    ------------------------------------ ----------- ------------------------------
    hi_shared_memory_address integer 0
    whole big memory_max_target 3G
    whole large memory_target 3G
    shared_memory_address integer 0
    System@oracle11 SQL > show parameter sga

    VALUE OF TYPE NAME
    ------------------------------------ ----------- ------------------------------
    lock_sga boolean FALSE
    PRE_PAGE_SGA boolean FALSE
    SGA_MAX_SIZE large integer 0
    SGA_TARGET large integer 0
    System@oracle11 SQL > show parameter pga

    VALUE OF TYPE NAME
    ------------------------------------ ----------- ------------------------------
    pga_aggregate_target large integer 0

    This way I pushed things like Oracle by itself, memory allocation to everywhere where oracle needs him the most.

    Brgds
    Johan

  • Query with almost the same query as a subquery, can it be optimized?

    I have a query using almost a duplicate of itself (table 1) as a subquery, and I wonder if it can be rewritten better, like she just doesn't seem the right way to do it, but everything I try I can't get the same number of lines back.

    If anyone can see a better way, it would be a great help.

    Thank you very much
    SELECT t.pol_number||t.check_digit
    FROM   transactions t, policies p, funds f
    WHERE f.fnd_code = t.trn_fnd_code
    AND     t.trn_pol_number = p.pol_number
    AND     p.pol_status IN (1,2)
    AND     t.trn_status = 'NEW'
    AND     t.trn_trn_number IN
       (SELECT t2.trn_trn_number
        FROM   transactions t2, policies p2
        WHERE t2.trn_pol_number = p2.pol_number 
        AND     p2.pol_status IN (1,2)
        AND     t2.trn_status = 'NEW'
        AND     t2.trn_fnd_code = :PARAMETER)
    Surely it is not the best way to write it as you use the same table twice and restrictions?

    Published by: Scott Hillier on March 16, 2010 15:11

    It looks like you want all the lines of the siblings who do not personally meet the restriction on trn_fnd_code. You can use analytical functions;

    not tested

    select *
      from (select pol_number || check_digit col1,
                   max(case
                          when t.trn_fnd_code = :parameter then
                           1
                          else
                           0
                        end) over(partition by trn_trn_number) max_trn_number
              from transactions t, policies p, funds f
             where f.fnd_code = t.trn_fnd_code
               and p.pol_status in (1, 2)
               and t.trn_status = 'NEW')
     where max_trn_number = 1;
    
  • The execution plan changes for the same query.

    Hi all

    This issue was raised before also, but still not able to find the real cause of this.

    Thread1:
    Re: Research of fragmentation of the table in Oracle 8.1.6.3.0

    Thread2:
    CBC latch and buffer busy await you on the same table.

    It comes, sometimes hammers server 100% CPU utilization with free latch and buffer busy wait events.

    We found a single query consumes high CPU usage that is run by different sessions.

    This query have two types of execution plans, where one is accurate and is not (its primary key hit index index no appropriate means present on the table)

    Because its primary key index hit repeatedly at various sessions, some sessions are powerful db file sequential read and a few sessions waiting buffer busy waits for event. Also during this time a few sessions waiting for latch free event.

    My doubt is how to sql even with different literal values execution plan changes and causes a prob.
    select count(*),event from v$session_wait group by event;
      COUNT(*) EVENT
    ---------- ----------------------------------------------------------------
           165 SQL*Net message from client
             1 SQL*Net message to client
             3 buffer busy waits
             2 db file parallel read
            18 db file sequential read
            10 latch free
             5 log file sync
             1 pmon timer
             6 rdbms ipc message
             1 smon timer
    
    SQL> select sid from v$session_wait where event='db file sequential read';
           SID
    ----------
            26
            58
            82
           107
           116
           223
           212
           203
           192
           173
           161
           157
           150
           147
           254
           238
           229
           112
           101
            81
            68
    
    SQL> select spid, sid, s.serial#, p.program from v$session s, v$process p where paddr=addr and sid=&SID;
    Enter value for sid: 161
    old   1: select spid, sid, s.serial#, p.program from v$session s, v$process p where paddr=addr and sid=&SID
    new   1: select spid, sid, s.serial#, p.program from v$session s, v$process p where paddr=addr and sid=161
    
    SPID             SID    SERIAL# PROGRAM
    --------- ---------- ---------- ------------------------------------------------
    4231             161      49569 oracle@tfrdb3 (TNS V1-V3)
    
    
    SQL> select sql_text
    from v$process a,
         v$session b,  2    3
         v$sql c
    where a.addr = b.paddr and
         b.sql_hash_value = c.hash_value and
        a.spid = &PID;  4    5    6    7
    Enter value for pid: 4231
    old   7:     a.spid = &PID
    new   7:     a.spid = 4231
    
    SQL_TEXT
    --------------------------------------------------------------------------------
    SELECT ERROR,TIME_STAMP,O_RESOURCE,QUEUE,NEW_QUEUE FROM LOG WHERE ID = '09292AMR
    10B41FE' AND TYPE IN (11, 28, 25, 18, 60, 13) AND (LOG_SEQ>'234225222' OR TYPE =
     18 AND LOG_SEQ='234225222') ORDER BY TIME_STAMP ASC
    
    SQL> set autotrace traceonly exp
    SQL> SELECT ERROR,TIME_STAMP,O_RESOURCE,QUEUE,NEW_QUEUE FROM amrwf1.LOG WHERE ID = '09292AMR10B41FE' AND TYPE IN (11, 28, 25, 18, 60, 13) AND (LOG_SEQ>'234225222' OR TYPE =18 AND LOG_SEQ='234225222') ORDER BY TIME_STAMP ASC;
    
    Execution Plan
    ----------------------------------------------------------
       0      SELECT STATEMENT Optimizer=CHOOSE (Cost=11 Card=2 Bytes=126)
       1    0   SORT (ORDER BY) (Cost=11 Card=2 Bytes=126)
       2    1     CONCATENATION
       3    2       TABLE ACCESS (BY INDEX ROWID) OF 'LOG' (Cost=4 Card=1
              Bytes=63)
    
       4    3         INDEX (UNIQUE SCAN) OF 'PK_LOG_LOG_SEQ' (UNIQUE) (Co
              st=3 Card=1)
    
       5    2       TABLE ACCESS (BY INDEX ROWID) OF 'LOG' (Cost=4 Card=1
              Bytes=63)
    
       6    5         INDEX (RANGE SCAN) OF 'PK_LOG_LOG_SEQ' (UNIQUE) (Cos
              t=3 Card=1)
    
    
    SQL> select spid, sid, s.serial#, p.program from v$session s, v$process p where paddr=addr and sid=&SID;
    Enter value for sid: 147
    old   1: select spid, sid, s.serial#, p.program from v$session s, v$process p where paddr=addr and sid=&SID
    new   1: select spid, sid, s.serial#, p.program from v$session s, v$process p where paddr=addr and sid=147
    
    SPID             SID    SERIAL# PROGRAM
    --------- ---------- ---------- ------------------------------------------------
    6255             147      38306 oracle@tfrdb3 (TNS V1-V3)
    
    SQL> select sql_text
    from v$process a,
         v$session b,
         v$sql c  2    3
    where a.addr = b.paddr and
         b.sql_hash_value = c.hash_value and
        a.spid = &PID;  4    5    6    7
    Enter value for pid: 6255
    old   7:     a.spid = &PID
    new   7:     a.spid = 6255
    
    SQL_TEXT
    --------------------------------------------------------------------------------
    SELECT ERROR,TIME_STAMP,O_RESOURCE,QUEUE,NEW_QUEUE FROM LOG WHERE ID = '09273AMR
    62B4894' AND TYPE IN (11, 28, 25, 18, 60, 13) AND (LOG_SEQ>'223324996' OR TYPE =
     18 AND LOG_SEQ='223324996') ORDER BY TIME_STAMP ASC
    
    
    SQL> set autotrace traceonly exp
    SQL> SELECT ERROR,TIME_STAMP,O_RESOURCE,QUEUE,NEW_QUEUE FROM amrwf1.LOG WHERE ID = '09273AMR62B4894' AND TYPE IN (11, 28, 25, 18, 60, 13) AND (LOG_SEQ>'223324996' OR TYPE =18 AND LOG_SEQ='223324996') ORDER BY TIME_STAMP ASC;
    
    Execution Plan
    ----------------------------------------------------------
       0      SELECT STATEMENT Optimizer=CHOOSE (Cost=1538 Card=736 Bytes=
              46368)
    
       1    0   SORT (ORDER BY) (Cost=1538 Card=736 Bytes=46368)
       2    1     TABLE ACCESS (BY INDEX ROWID) OF 'LOG' (Cost=1527 Card=7
              36 Bytes=46368)
    
       3    2       INDEX (RANGE SCAN) OF 'LOG_ID' (NON-UNIQUE) (Cost=32 C
              ard=736)
    
    
    
    SQL> select spid, sid, s.serial#, p.program from v$session s, v$process p where paddr=addr and sid=&SID;
    Enter value for sid: 82
    old   1: select spid, sid, s.serial#, p.program from v$session s, v$process p where paddr=addr and sid=&SID
    new   1: select spid, sid, s.serial#, p.program from v$session s, v$process p where paddr=addr and sid=82
    
    SPID             SID    SERIAL# PROGRAM
    --------- ---------- ---------- ------------------------------------------------
    6172              82      45378 oracle@tfrdb3 (TNS V1-V3)
    
    
    SQL> select sql_text
    from v$process a,
         v$session b,
         v$sql c
    where a.addr = b.paddr and
         b.sql_hash_value = c.hash_value and  2
      3      a.spid = &PID;  4    5    6    7
    Enter value for pid: 6172
    old   7:     a.spid = &PID
    new   7:     a.spid = 6172
    
    SQL_TEXT
    --------------------------------------------------------------------------------
    INSERT INTO LOG (ID,TIME_STAMP,TYPE,ERROR,INSTANCE,RULE_NUM,RULE_TYPE,PRIORITY,F
    LAGS,NAME,BATCH,O_RESOURCE,QUEUE,NEW_QUEUE,SERVER,FORM,WORKSET) VALUES (:V001,:V
    002,11,0,0,3,1,0,1,:V003,:V004,:V005,:V006,:V007,:V008,:V009,:V010)
    
    INSERT INTO LOG (ID,TIME_STAMP,TYPE,ERROR,INSTANCE,RULE_NUM,RULE_TYPE,PRIORITY,F
    LAGS,NAME,BATCH,O_RESOURCE,QUEUE,NEW_QUEUE,SERVER,FORM,WORKSET) VALUES (:V001,:V
    002,11,0,0,3,1,0,1,:V003,:V004,:V005,:V006,:V007,:V008,:V009,:V010)
    
    INSERT INTO LOG (ID,TIME_STAMP,TYPE,ERROR,INSTANCE,RULE_NUM,RULE_TYPE,PRIORITY,F
    LAGS,NAME,BATCH,O_RESOURCE,QUEUE,NEW_QUEUE,SERVER,FORM,WORKSET) VALUES (:V001,:V
    002,11,0,0,3,1,0,1,:V003,:V004,:V005,:V006,:V007,:V008,:V009,:V010)
    
    SQL_TEXT
    --------------------------------------------------------------------------------
    
    INSERT INTO LOG (ID,TIME_STAMP,TYPE,ERROR,INSTANCE,RULE_NUM,RULE_TYPE,PRIORITY,F
    LAGS,NAME,BATCH,O_RESOURCE,QUEUE,NEW_QUEUE,SERVER,FORM,WORKSET) VALUES (:V001,:V
    002,11,0,0,3,1,0,1,:V003,:V004,:V005,:V006,:V007,:V008,:V009,:V010)
    
    INSERT INTO LOG (ID,TIME_STAMP,TYPE,ERROR,INSTANCE,RULE_NUM,RULE_TYPE,PRIORITY,F
    LAGS,NAME,BATCH,O_RESOURCE,QUEUE,NEW_QUEUE,SERVER,FORM,WORKSET) VALUES (:V001,:V
    002,11,0,0,3,1,0,1,:V003,:V004,:V005,:V006,:V007,:V008,:V009,:V010)
    
    INSERT INTO LOG (ID,TIME_STAMP,TYPE,ERROR,INSTANCE,RULE_NUM,RULE_TYPE,PRIORITY,F
    LAGS,NAME,BATCH,O_RESOURCE,QUEUE,NEW_QUEUE,SERVER,FORM,WORKSET) VALUES (:V001,:V
    
    SQL_TEXT
    --------------------------------------------------------------------------------
    002,11,0,0,3,1,0,1,:V003,:V004,:V005,:V006,:V007,:V008,:V009,:V010)
    
    INSERT INTO LOG (ID,TIME_STAMP,TYPE,ERROR,INSTANCE,RULE_NUM,RULE_TYPE,PRIORITY,F
    LAGS,NAME,BATCH,O_RESOURCE,QUEUE,NEW_QUEUE,SERVER,FORM,WORKSET) VALUES (:V001,:V
    002,11,0,0,3,1,0,1,:V003,:V004,:V005,:V006,:V007,:V008,:V009,:V010)
    How to avoid this... why its different execution plan using (I mean bad index PK)

    Is it possible to avoid this?

    If any details please check out some of my previous post on this specific URL (above)

    -Yasser

    My doubt is how to sql even with different literal values execution plan changes and causes a prob.

    Different literal values cause analysis difficult.
    Hard analysis includes the re-evaluation of the best path.
    Literal value is included in the assessment of the selectivity for the scan interval (log_seq >...)

    See
    http://www.centrexcc.com/A%20Look%20under%20The%20Hood%20Of%20CBO%20-%20The%2010053%20Event.ppt.PDF
    http://www.centrexcc.com/fallacies%20Of%20The%20Cost%20Based%20Optimizer.PDF
    more the book of Jonathan Lewis which other threads, I believe that you already have.

    You must lower your CPU.
    Previous discussions, if the situation is still the same, it sounded like hard analysis particularly with this SELECTION against the NEWSPAPER plays an important role in that.

    How to avoid this... why its different execution plan using (I mean bad index PK)

    The points raised in the previous discussion remain valid.
    -Do you have access to this SQL to change?
    for example using bind variable or trick it if necessary due to problems caused by data as discussed in the previous thread.
    - Or you could it repoint the view to a view and a hint?
    -If a particular user makes this sql, could affect you cursor_sharing just for this user. If not, you should consider implementing pan-Canadian database.

    Oracle 8.1.6 still?

  • How to access the AAA columns and later using ExcelRowColToRange.vi

    Hello

    I have a huge database that I need to write on Excel in the first row, so I need to access the columns AAA, AAB...

    But using ExcelRowColToRange.vi I'm able to go up to column ZZ. Can someone please suggest a way to modify this VI to meet my need.

    Thank you

    Hi panka.

    try this one...

  • What is the vertical offset and its use?

    What is use and movement of the base line?

    What is the movement of the base line and employment?

Maybe you are looking for