One SQL Statement executed abnormally in Oracle10g Database

One programmer sent the following SQL to me, and ask why no result was returned. I knew that the SQL Statement was not good in writting and designing.
So, first we don't focus on it. we only focus on why no result was returned.
SELECT 'other Accts', 'Other Accts', TO_NUMBER(''),TO_DATE('2010-10-9', 'yyyy-MM-dd')
FROM dual
WHERE *0 = (SELECT COUNT(*)*
FROM (SELECT 'other Accts', 'Other Accts',SUM(a.qty_invoiced), a.sell_week_date
FROM sales_in_oracle_data a
WHERE NOT EXISTS
(SELECT pa.partner_number
FROM partner pa
WHERE pa.partner_number = a.customer_number)
AND a.sell_week_date >=TO_DATE('2010-10-9', 'yyyy-MM-dd')
AND a.sell_week_date <=TO_DATE('2011-1-1', 'yyyy-MM-dd')
AND a.qty_invoiced >= 0
AND EXISTS
(SELECT pp.product_id
FROM product_pn pp, product p
WHERE pp.magellan_pn = a.material
AND pp.product_id = p.product_id )
GROUP BY a.sell_week_date
the SQL sub Statement:
SELECT COUNT(*)*
FROM (SELECT 'other Accts', 'Other Accts',SUM(a.qty_invoiced), a.sell_week_date
FROM sales_in_oracle_data a
WHERE NOT EXISTS
(SELECT pa.partner_number
FROM partner pa
WHERE pa.partner_number = a.customer_number)
AND a.sell_week_date >=TO_DATE('2010-10-9', 'yyyy-MM-dd')
AND a.sell_week_date <=TO_DATE('2011-1-1', 'yyyy-MM-dd')
AND a.qty_invoiced >= 0
AND EXISTS
(SELECT pp.product_id
FROM product_pn pp, product p
WHERE pp.magellan_pn = a.material
AND pp.product_id = p.product_id )
GROUP BY a.sell_week_date
it returned 0 truely. But the entire SQL didn't return any data.
why can it execute like above description?  I guess that it maybe go against oracle basic rule.
Any one give me some suggestion?
Edited by: [email protected] on 2010/7/19 下午 6:09

I managed to track down a 10.2.0.4 instance and can confirm that this statement does not return the correct results.
Connected to:
Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 - 64bit Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options
SQL> select *
  2  from   dual
  3  where  0 = (select count(*)
  4              from  (select dummy, sum(1)
  5                     from   dual
  6                     where  dummy = 'z'
  7                     group  by dummy
  8                    )
  9             );
no rows selected
SQL> explain plan for
  2  select *
  3  from   dual
  4  where  0 = (select count(*)
  5              from  (select dummy, sum(1)
  6                     from   dual
  7                     where  dummy = 'z'
  8                     group  by dummy
  9                    )
10             );
Explained.
| Id  | Operation           | Name | Rows  | Bytes | Cost (%CPU)| Time     |
|   0 | SELECT STATEMENT    |      |     1 |     2 |     4   (0)| 00:00:01 |
|*  1 |  FILTER             |      |       |       |            |          |
|   2 |   TABLE ACCESS FULL | DUAL |     1 |     2 |     2   (0)| 00:00:01 |
|   3 |   SORT AGGREGATE    |      |     1 |     2 |            |          |
|*  4 |    TABLE ACCESS FULL| DUAL |     1 |     2 |     2   (0)| 00:00:01 |
Predicate Information (identified by operation id):
   1 - filter( NOT EXISTS (SELECT /*+ */ 0 FROM "SYS"."DUAL" "DUAL"
              WHERE "DUMMY"='z'))
   4 - filter("DUMMY"='z')
Connected to:
Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - 64bit Production
With the Partitioning, Real Application Clusters, OLAP, Data Mining
and Real Application Testing options
SQL> select *
  2  from   dual
  3  where  0 = (select count(*)
  4              from  (select dummy, sum(1)
  5                     from   dual
  6                     where  dummy = 'z'
  7                     group  by dummy
  8                    )
  9             );
D
X
SQL> explain plan for
  2  select *
  3  from   dual
  4  where  0 = (select count(*)
  5              from  (select dummy, sum(1)
  6                     from   dual
  7                     where  dummy = 'z'
  8                     group  by dummy
  9                    )
10             );
Explained.
| Id  | Operation          | Name | Rows  | Bytes | Cost (%CPU)| Time     |
|   0 | SELECT STATEMENT   |      |     1 |     2 |     6   (0)| 00:00:01 |
|*  1 |  FILTER            |      |       |       |            |          |
|   2 |   TABLE ACCESS FULL| DUAL |     1 |     2 |     3   (0)| 00:00:01 |
|*  3 |   TABLE ACCESS FULL| DUAL |     1 |     2 |     3   (0)| 00:00:01 |
Predicate Information (identified by operation id):
   1 - filter( NOT EXISTS (SELECT 0 FROM "SYS"."DUAL" "DUAL" WHERE
              "DUMMY"='z'))
   3 - filter("DUMMY"='z')
17 rows selected.Notice that the explain plan is a bit different compared to the 11.2.0.1 release. My guess is that the optimizer is doing something weird.

Similar Messages

  • Look for histroy of sql statement executed in database

    is there a way to look for histroy or list of sql statement executed in database.?
    similar to history command in linux or bash shell.

    The newer <a href="http://download.oracle.com/docs/cd/B19306_01/server.102/b14237/dynviews_2131.htm">v$sqlstats</a> (10g) is recommended over v$sql as (according to the documentation) it's "faster, more scalable, and has a greater data retention (the statistics may still appear in this view, even after the cursor has been aged out of the shared pool)", although it's missing a couple of the columns v$sql has.
    The history version (if you are licenced for AWR, which is part of the extra-cost Diagnostics Pack - you may not be licenced to use it even if the dictionary views are installed) is DBA_HIST_SQLSTAT.

  • Execute just that one SQL statement ....

    Would like to request to add running just that one sql statement in the statment worksheet which has your cursor in it without having to select the entire statement.
    Updating any part of a statement deselects it ..... reselecting a larger statement is cumbersome and time consuming
    Regards
    Ronald

    There are some problems with the statement selection (as per the other reply) but you can run just the current statement that the cursor is in, with the F9 or the Run Statement button on the SQL Worksheet.
    If you are used to using TOAD where blank lines are seperators, remember that Raptor expects you to terminate your SQL statements with a ; and your PL/SQL statements with a / (on a new line).

  • Tracking SQL statements executed

    Hi,
    After obtaining a connection to my Oracle 10g database using JDBC, I would like to know if there is a way to track all SQL statements executed since the connection was made.
    This must be pretty easy, I'm just stumped.
    Thank you
    Tom

    Hi, and it's not that easy. The driver certainly doesn't
    keep track of what's been done, but look at the documentation
    regarding the logging the driver can be configured to do. It can
    print out everything it does, so some level of detail and degree,
    and that can be collected in a file and examined externally.
    That can be voluminous too... It might be more (or just as)
    practical to examine the DBMS-side session-auditing/logging
    features the DBMS may have to collect everything the session
    has done.
    HTH,
    Joe Weinstein at BEA Systems

  • Log for all the sql statement executed

    Hi,
    I would like to know how to see the log for all the sql statement executed starting from connection to all the database related actions.
    Is it something that i need to set it up in the driver?
    I'm using Tomcat and JDBC driver.
    Please reply.
    Thanks,
    Anjana

    Make your own.
    Calendar cal = new GregorianCalendar();
    int year = cal.get(Calendar.YEAR);
    int month = cal.get(Calendar.MONTH) + 1;
    int day = cal.get(Calendar.DAY_OF_MONTH);
    //use calendar object to get other infos such as time of query
    //append your query string
    File f  =new File ("c:\\jakarta-tomcat-3.2.4\\webapps\\ASD\\LOGS\\log" + df.format(day) + df.format(month) + year + ".txt");
                   if (! f.exists())
                        f.createNewFile();
                   FileWriter fw = new FileWriter (f, true);
                   // append new log to end of file
                   fw.write(buf.toString());
                   fw.write("\n");
                   fw.flush();
                   fw.close();
              catch (IOException ioe)
                   System.out.println(ioe.toString());

  • How can i use one SQL statement to solve problem?

    How can i use one SQL statement to solve the question below?
    For a Table named A, there is a column named F(char type).
    Now select all the records where F like '%00' and update their F value to '%01'
    Just one SQL statement.Do not use PL/SQL block.
    How to do that?
    Thanks.

    What is the data volume for this table?
    Do you expect lots of rows to have '%00' as their value?
    Following two statements come to mind. Other experts would be able to provide better alternatives:
    If you have index on SUBSTR(f, 2):
    UPDATE A
    SET    f = SUBSTR(f,
                      1,
                      length(f) - 2) || '01'
    WHERE  substr(f,
                  -2) = '00';If most of the rows have pattern '%00':
    UPDATE A
    SET    f = SUBSTR(f,
                      1,
                      length(f) - 2) ||
               DECODE(SUBSTR(f,
                             -2),
                      '00',
                      '01',
                      SUBSTR(f,
                             -2));

  • Can you really update two tables in one SQL statement

    Ok a post in the forum has got me awefully curious:
    Can you update two tables in one update statement i.e something like this
    update table a , b
    set b.<column> = something
    a.<column> = something
    Something to this effect.
    If you are curious to know what post I am talking about it is called "updating a single row"

    No. You can only update one table in one SQL statement.

  • Getting A Count In One SQL Statement

    Since I don't know how to do what I'm about to ask, I would normally create a table (tbl1) with the main dataset I want and then create a second table (tbl2) with additional data I want, join the two and update tbl1 data with tbl2 data.
    However, I would like to know how to do this in one SQL statement. I somehow need to link the count sql with the main body..?
    So..I have to pull data by group id. Each group id can have a certain number of active members in it. I would like to use one SQL statement to pull the group id's and also, at the same time, give me a count of each group's active membership. Both the main and count statments in the below SQL include the emp_grps table which can obviously be linked so the right groups are updated..
    Not sure how to begin to reflect this in an SQL statement, so I'll just give you the wrong version to show what data elements I have. The following gives the total count by all group's in each groups individual record. Of course, as mentioned, all I want is that group's share of the membership in their individual record:
    select group_id,
    (select count(*)
    from elig elg
    join emp_grps eg
    on elg.group_id = eg.group_id
    where eg.rmc_code in ('CR')
    and elg.elig_start_date < sysdate
    and elg.elig_end_date > sysdate) mbr_count
    from odw.emp_grps eg
    where eg.rmc_code in ('1M')
    Output from this query:
    GROUP_ID MBR_COUNT
    A 10,000
    B 10,000
    C 10,000
    D 10,000
    What I want to see:
    GROUP_ID MBR_COUNT
    A 7,000
    B 1,000
    C 1,500
    D 500
    Thanks for any assistance..

    Hi,
    So you want one row for every distinct value of group_id, with a count that reflects just that group_id.
    That sound like a job for GROUP BY group_id and the aggregate COUNT function, like this:
    SELECT    eg.group_id
    ,       COUNT ( CASE
                      WHEN  eg.rmc_code  IN ('CR')
                    THEN  1
                  END
                )     AS mbr_count
    FROM        elig           elg
    JOIN       emp_grps      eg    ON   elg.group_id  = eg.group_id
    WHERE       eg.rmc_code             IN ('CR', '1M')
    AND       elg.elig_start_date < SYSDATE
    AND       elg.elig_end_date   > SYSDATE
    GROUP BY  eg.group_id
    HAVING       COUNT ( CASE
                      WHEN  eg.rmc_code  IN ('1M')
                    THEN  1
                  END
                ) > 1
    ORDER BY  eg.group_id
    ;It's unclear what you're trying to do with eg.rmc_code. I'm guessing you want to count the rows where it's one value ('CR'), but only display groups that also have another value ('1M').
    Of course, I can't say for sure without seeing your actual tables, or at least small test versions of them.
    Post CREATE TABLE and INSERT statements (relevant columns only) for all tables involved, and the resutls you want from that sample data (if it's not the results you already posted).
    Always say which version of Oracle you're using.

  • SQL STATEMENT EXECUTES

    Hi All
    HOw oracle SQL statements executes ? Can anyone explain me for SELECT, INSERT,UPDATE and COMMIT statements works ?
    Regards
    Krishna

    Krishna,
    Search for SQL Statement Execution and see the Flow Chart.
    http://download-west.oracle.com/docs/cd/B19306_01/server.102/b14220/sqlplsql.htm
    -Anantha

  • How to trace the SQL statements executed in a database

    I am using Oracle9i Enterprise Edition Release 9.2.0.7.0 - 64bit Production on a sun server and I am not familiar with Oracle but with MS SQL there is a tool called profiler, it allows you to monitor and see what is going on in a specific databases whether it is SQL statement executins or anything else. I have installed the oracle enterpise manager console at my windows client and I tried to look for a tool similar to the profiler in the MS SQL. I tried the TRACE DATA VIEWER and I inputed the login credentials but I don' t actually know the service name and I am getting an error ORA-12514 The TSN listener can not resolve the service name given in the connect descriptor. Therefore, am I on the right road so i have to look for the service name or are there any other ways i can trace the currently executing SQL statement in a specific database. I am really stuck there. I would appreciate if somebody help me out. Thanks
    Abdel Moalim

    Abdel Moalim wrote:
    I am using Oracle9i Enterprise Edition Release 9.2.0.7.0 - 64bit Production on a sun server and I am not familiar with Oracle but with MS SQL there is a tool called profiler, it allows you to monitor and see what is going on in a specific databases whether it is SQL statement executins or anything else. I have installed the oracle enterpise manager console at my windows client and I tried to look for a tool similar to the profiler in the MS SQL. I tried the TRACE DATA VIEWER and I inputed the login credentials but I don' t actually know the service name and I am getting an error ORA-12514 The TSN listener can not resolve the service name given in the connect descriptor. Therefore, am I on the right road so i have to look for the service name or are there any other ways i can trace the currently executing SQL statement in a specific database. I am really stuck there. I would appreciate if somebody help me out. Thanks
    Abdel MoalimHi
    I see others have answered the network connectivity issues, I'll try and address the tracing issue. Your best bet is to review http://www.petefinnigan.com/ramblings/how_to_set_trace.htm for the many ways in which a sessions SQL and indeed other activity can be traced. In version 7 (which I'm guessing is yours from the sid) the only profiler available was tkprof (Trace Kernel Profiler) which will do a good job of analysing your trace file. The trace files themselves are generated on the server in a protected directory so you may need to ask your dba for access to them. There are other profilers around now (I have one which runs in v9 and higher database at http://www.niall.litchfield.dial.pipex.com/SimpleProfiler/SimpleProfiler.html which will analyse your files for example) but tkprof is the start point - or else just reading the trace file in a text editor. There is also a utility written by the Oracle Apps guys trcanalyzer that will do a good job for you. In general the interface is poor compared with the ms utility but the information is deeper and more helpful
    Niall Litchfield
    http://www.orawin.info/

  • How to find SQL Statement fired using SYS.AUD$ - Database Auditing

    Dear Friends
    I am having Oracle 9i Database and have configured it with database auditing option by setting the following parameter in init.ora file
    AUDIT_TRAIL = "DB"
    I want to audit SELECT, INSERT , UPDATE and DELETE operations on PRACTICE.EMP table for which I did :
    1) Logged in as SYS
    2) SQL> AUDIT SELECT, INSERT, UPDATE, DELETE
    ON PRACTICE.EMP
    BY ACCESS
    WHENEVER SUCCESSFUL;
    Audit Succedded
    Now how should I find out the SQL statement that does the insert, update or delete operation on the EMP table using SYS.AUD$ table
    Thanks

    Hi,
    It's contents can be viewed directly or via the following views:
    * DBA_AUDIT_EXISTS
    * DBA_AUDIT_OBJECT
    * DBA_AUDIT_SESSION
    * DBA_AUDIT_STATEMENT
    * DBA_AUDIT_TRAIL
    * DBA_OBJ_AUDIT_OPTS
    * DBA_PRIV_AUDIT_OPTS
    * DBA_STMT_AUDIT_OPTS
    The audit trail contains a lot of data, but the following are most likely to be of interest:
    * Username : Oracle Username.
    * Terminal : Machine that the user performed the action from.
    * Timestamp : When the action occured.
    * Object Owner : The owner of the object that was interacted with.
    * Object Name : The name of the object that was interacted with.
    * Action Name : The action that occured against the object. (INSERT, UPDATE, DELETE, SELECT, EXECUTE)
    So, take a look at action_name column from DBA_AUDIT_TRAIL view.
    Cheers
    Legatti

  • Returning sql statement instead of values from database

    hi am reading value from database but my problem is am get sql statement values instead of values in database
    my code is
    java:337)

    There is no doubt: you get what you want:
        return s_getValue;
    bye
    TPD

  • Performance Issue using min() and max() in one SQL statement

    I have a simple query that selects min() and max() from one column in a table in one sql statment.
    The table has about 9 Million rows and the selected column has a non unique index. The query takes 10 secs. When i select min() and max() in separate statements, each takes only 10 msecs:
    This statement takes 10 secs:
    select min(date_key) , max(date_key)
    from CAPS_KPIC_BG_Fact_0_A
    where date_key != TO_DATE(('1900-1-1' ),( 'YYYY-MM-DD'))
    This statement takes 10 msecs:
    select min(date_key)
    from MYTABLE
    where date_key != TO_DATE(('1900-1-1' ),( 'YYYY-MM-DD'))
    union all
    select max(date_key) from MYTABLE
    Because the first statement is part of an autmatic generated SQL of an application, i can't change it and i have to optimize the data model. How can i speed up the first statement?

    I've ran similar query on a table that has 10 milliion rows, with an index on the date column
    This is what I have found:
    SQL> set timing on
      1  SELECT MIN(ID_DATE) MIN_DATE, MAX(ID_DATE) MAX_DATE
      2      FROM MY_DATE
      3*     WHERE ID_DATE != TO_DATE(('1900-1-1' ),( 'YYYY-MM-DD'))
    SQL> /
    MIN_DATE  MAX_DATE
    03-APR-76 06-JAN-02
    real: 43383
    SQL> SELECT MIN(ID_DATE) MIN_DATE FROM MY_DATE
      2   WHERE ID_DATE != TO_DATE(('1900-1-1' ),( 'YYYY-MM-DD'))
      3  UNION ALL
      4  SELECT MAX(ID_DATE) MAX_DATE FROM MY_DATE
      5   WHERE ID_DATE != TO_DATE(('1900-1-1' ),( 'YYYY-MM-DD'))
      6  /
    MIN_DATE
    03-APR-76
    06-JAN-02
    real: 20
    SQL> SELECT MIN_DATE, MAX_DATE FROM
      2  (SELECT MAX(ID_DATE) MAX_DATE FROM MY_DATE
      3  WHERE ID_DATE != TO_DATE(('1900-1-1' ),( 'YYYY-MM-DD')) ) A,
      4  (SELECT MIN(ID_DATE) MIN_DATE FROM MY_DATE
      5  WHERE ID_DATE != TO_DATE(('1900-1-1' ),( 'YYYY-MM-DD')) ) B
      6  /
    MIN_DATE  MAX_DATE
    03-APR-76 06-JAN-02
    real: 10
    SQL> My conculsion, there is nothing you can do to the tables that will improve that particular statement.
    Why can't you modify the application?

  • How to insert 22.5K rows in one sql statement in Oracle

    Hi Gurus,
    I have a one table with one column. I require to input 22.5k numbers example "08323459" in that table. Can anyone tell me how to insert those 22.5K numbers with one sql command.
    I am using PL/SQL client. And oracle version is 11G.

    If you have an Excel file, the simplest approach is generally to save the file as a CSV, copy it to the database server, create an external table that exposes the file as a table, and then write your INSERT by selecting the data from the external table.
    INSERT INTO permanent_table( column_name )
      SELECT column_name
        FROM external_tableAssuming you have SQL*Loader installed on your client machine, you could also use SQL*Loader to read the data in the file and load it into the database table.
    Justin

  • One SQL Statement

    I have a text column with values like listed below:
    rec_num text_column
    10001 'Today_is__my_birthday.'
    10002 'I have__a___dog_and_a____cat.'
    where '_' indicates space.
    How can I use one SQL 'select ....' statement to get rid of the multiple spaces and replace with just one space?
    I expect a result like 'Today is my birthday.' or 'I have a dog and a cat.' with just one space between word.
    THANKS a million.

    Hi,
    SELECT     rec_num
    ,     REGEXP_REPLACE ( text_column
                     , ' +'          - or ' {2,}'
    FROM    table_x;As you've noticed, this site compresses white space by default.
    To post formatted text, type these 6 characters:
    &#123;code&#125;
    (small letters only, inside curly brackets) before and after sections of formatted text, to preserve spacing.

Maybe you are looking for

  • Including Vendor Name in Standard report 'MB51' transaction

    Hi Friends, I have a requirement of Displaying the Vendor Name in the standard report 'MB51', after the vendor No. I checked the report and it is really confusing ..... ( i ve seen something like when i double click the document number it is going to

  • Error bars in Charts?

    Hello everyone- Would anyone know how to create error bars in charts in Keynote 3? I can't seem to find an answer anywhere to this question. Many thanks to future replies... Powerbook G4   Mac OS X (10.4.6)  

  • How to format Lion OS X 10.7.5?

    I Don't figure out a lot from computers but my MacBook has been hacked I suppose and I want to format it in a cvery easy way. What is the simplest way to do it?

  • CS6 Panels not showing up

    I can create panels for CS5.5 and they show up in the extensions, but when I try to make them for CS6 they just don't show up. I am putting them in the CS6 Photoshop>PlugIns>Panels folder and I am making them as CS6 in Configurator. Not sure what the

  • OC4J-Weblogic

    Hi, please help me, we need to communicate two j2ee applications, one is deployed in bea weblogic 7 service pack 4, the other is deployed in oracle ias 903, we want to call session beans methods deployed in bea from session beans deployed in ias. But