Query Issue with select level from dual
Hi,
I have a question regarding this query. The problem seems that when selecting level from dual while including another table the rows returned seem to increase exponentially.
I can add distinct and get the correct number of rows but am worried that this will cause a possible performance issue. Am I using the level option wrong?
I have included details below.
There are 4 rows in tbl_incidents
When I run the following queries I get rows returned based on the total number of rows
select start_date + level - 1, tbl_incidents.incident_id, level
from dual, tbl_incidents
where incident_id = 6
connect by level <= 1;
returns 1 row
select start_date + level - 1, tbl_incidents.incident_id, level
from dual, tbl_incidents
where incident_id = 6
connect by level <= 2;
returns 5 rows
select start_date + level - 1, tbl_incidents.incident_id, level
from dual, tbl_incidents
connect by level <= 3 and incident_id = 6;
returns 21 rows
select start_date + level - 1, tbl_incidents.incident_id, level
from dual, tbl_incidents
connect by level <= 4 and incident_id = 6;
returns 85 rows
select start_date + level - 1, tbl_incidents.incident_id, level
from dual, tbl_incidents
connect by level <= 5 and incident_id = 6;
returns 341 rows
So with
r being the number of rows in tbl_incidents and
l being the number used in the connect by for level and
q being the number of rows returned by the query
it appears that
q(l) = r * q(l-1) + 1
level 2: 4 * 1 + 1 = 5
level 3: 4 * 5 + 1 = 21
level 4: 4 * 21 + 1 = 85
level 5: 4 * 85 + 1 = 341
Thanks much,
Nora
Hi,
The dual table is used when you want to do something in SQL when you are not otherwise using a table.
Generating a "counter table" of the integers 1, 2, 3,..., X is an example
SELECT LEVEL AS n
FROM dual
WHERE LEVEL <= x;There is never any point in joining dual to another table, as in
select start_date + level - 1
, tbl_incidents.incident_id
, level
from dual
, tbl_incidents
where incident_id = 6
connect by level <= x;You will always get the same more easily by just eliminating dual:
select start_date + level - 1
, incident_id
, level
from tbl_incidents
where incident_id = 6
connect by level <= x;It is quite useful and common to join a counter-table to a real table, like this cross-join:
WITH counter_table AS
SELECT LEVEL AS n
FROM dual
WHERE LEVEL <= x
select start_date + n - 1
, incident_id
, n
from tbl_incidents
, counter_table
where incident_id = 6
Similar Messages
-
Strange "select level from dual connect by level :N" behavior
Oracle SQL Deveoper version:1.1.0.23
Oracle database server version:
select * from v$version;
Oracle9i Enterprise Edition Release 9.2.0.7.0 - Production
PL/SQL Release 9.2.0.7.0 - Production
"CORE 9.2.0.7.0 Production"
TNS for 32-bit Windows: Version 9.2.0.7.0 - Production
NLSRTL Version 9.2.0.7.0 - Production
Run the following queries in sequence as a script and look at number of rows returned:
select 1, level l from dual connect by level < 1;
select 2, level l from dual connect by level < 2;
select 3, level l from dual connect by level < 3;
select 4, level l from dual connect by level < 4;
select 5, level l from dual connect by level < 5;
select 6, level l from dual connect by level < 6;
select 7, level l from dual connect by level < 7;
select 8, level l from dual connect by level < 8;
select 9, level l from dual connect by level < 9;
select 10, level l from dual connect by level < 10;
select 11, level l from dual connect by level < 11;
select 12, level l from dual connect by level < 12;
1 L
1 1
1 rows selected
2 L
2 1
1 rows selected
3 L
3 1
3 2
2 rows selected
4 L
4 1
4 2
4 3
3 rows selected
5 L
5 1
5 2
5 3
5 4
4 rows selected
6 L
6 1
6 2
6 3
6 4
6 5
5 rows selected
7 L
7 1
7 2
7 3
7 4
7 5
7 6
6 rows selected
8 L
8 1
8 2
8 3
8 4
8 5
8 6
8 7
7 rows selected
9 L
9 1
9 2
9 3
9 4
9 5
9 6
9 7
9 8
8 rows selected
10 L
10 1
10 2
10 3
10 4
10 5
10 6
10 7
10 8
10 9
9 rows selected
11 L
11 1
11 2
11 3
11 4
11 5
11 6
11 7
11 8
11 9
11 10
10 rows selected
12 L
12 1
12 2
12 3
12 4
12 5
12 6
12 7
12 8
12 9
12 10
10 rows selected
1000 L
1000 1
1000 2
1000 3
1000 4
1000 5
1000 6
1000 7
1000 8
1000 9
1000 10
10 rows selected
-- wrong result. return 1 row, should return 0 row
-- May have some automagical code saw dual and return 1 row.
select 1, level l from dual connect by level < 1;
-- wrong result. Should return 11 rows, but it stopped at 10 rows.
select 12, level l from dual connect by level < 12;
select 1000, level from dual connect by level < 1000;""By default, when Oracle JDBC executes a query, it receives the result set 10 rows at a time from the database cursor.""
Sql dev overrides the default and fetches 50 (1.0) or 100 (1.1) rows at a time. In 1.1 this is configurable.
"I don't HATE any SQL, as long as it's valid."
That statement is absurd. So, if someone tells you a way to write your query that it allows it to run faster, you wouldn't care? You should hate some SQL, some of it is pure crap and needs to be rewritten. This is what we call 'junk code'. As a developer, your goal should be to write maintainable code. In short, if you have the choice between something that looks fancy and something that is legible and maintainable, choose the maintainability. Sorry, but if I ever saw that statement in a code review I would have made you rewrite it. Also, anything that runs differently on different databases should be avoided, its that simple. -
Issues with selecting value from XMLType column
I want to retrieve values from my XMLType column. Can anyone tell me why this works
select XMLCAST
XMLQUERY
'declare default element namespace "urn:hl7-org:v3"; (: :)
declare namespace voc = "urn:hl7-org:v3/voc"; (: :)
$doc/ClinicalDocument/recordTarget/patientRole/patient/name/family'
passing CCD_DOC as "doc"
returning content
as VARCHAR2(4000)
from CCDbut this doesn't?
select
ccdid,
extractvalue(CCD_DOC,'/recordTarget/patientRole/patient/name/given') "given",
extractvalue(CCD_DOC,'/recordTarget/patientRole/patient/name/family') "family",
extractvalue(CCD_DOC,'/recordTarget/patientRole/providerOranization/name') "name",
extractvalue(CCD_DOC, 'title') as Title
from CCDwhere ClinicalDocument is the root element?
I don't get any errors from the second one but the three XML-derived columns are null. The values are not retrieved while the values ARE retrieved using the first method.
Thanks!XMLTable..
select x.*
from CCD,
XMLTable
xmlNamespaces
default 'urn:hl7-org:v3',
'urn:hl7-org:v3/voc' as "voc"
'$doc/ClinicalDocument/recordTarget/patientRole'
passing CCD_DOD as "doc"
columns
given varchar2(128) path 'patient/name/given',
family varchar2(128) path 'patient/name/family',
name varchar2(128) path 'providerOranization/name'
) x -
Select user from dual with oid + oss ?
Implementing a solution for global user administration, authentication and application schema mapping, will it break the simple but efficient possibility to do a 'select user from dual' ?
If it is possible which value will we get, a global user identifier from the directory or something else ?
Thanks in advance for your helpActually we authenticate user using internal database users. Each user depending on his enterprise role will have a set of synonyms deployed to map the application schema. It is complex to handle a large set of users schema. With OSS it seem to be possible to authenticate user using an external LDAP directory (OID) and to map this user to an application schema switch user's enterprise role.
But I want to evaluate the impact of deployeing such solution, because our application use some 'select user from dual' single query to track user activity in some manner (this can be done using triggers or pl/sql api that do this job). If it is possible to have an unique user identifier in the database session context, even using external authentication and schema mapping of OSS we'll have less impact on the application. Else we'll have to change some API signatures to handle this user identifier.
Context is :
- use LDAP external functionalities provided with OSS to increase user management at an enterprise level ... single sign-on is our goal ,-)
- use schema mapping to reduce our complexity of schema management. One schema foreach role rather than one schema per user.
So, will we be able to individually know which user have the session in the database, rather than the shared schema name. If it is possible, the impact on our application will be really minor ...
Thanks in advance for your help. If someone who read this lines have such system deployed and can try the 'select user from dual', I'll be glad on the answer that the database will give ,-) -
I am having issues with streaming music from iTunes on my MacBook Pro to my audio system through AirPlay. Works perfectly with my iPod Touch. The AirPlay icon appears irregularly in iTunes and when selected doesn't connect. Running latest IOS software.
Try:
- Reset the iOS device. Nothing will be lost
Reset iOS device: Hold down the On/Off button and the Home button at the same time for at
least ten seconds, until the Apple logo appears.
- Unsync all music and resync
- Reset all settings
Go to Settings > General > Reset and tap Reset All Settings.
All your preferences and settings are reset. Information (such as contacts and calendars) and media (such as songs and videos) aren’t affected.
- Restore from backup. See:
iOS: How to back up
- Restore to factory settings/new iOS device.
If still problem, make an appointment at the Genius Bar of an Apple store since it appears you have a hardware problem.
Apple Retail Store - Genius Bar
You said:
No, I do not want to "factory reset" my iPod. No I do not wish to do anything crazy long or hard to fix this.
That may be necessary, It is not what you want to do/not do but what is required to resolve your problem. -
JDBC Lookup in PI 7.1 - SELECT ? FROM DUAL and Connection timed out
Hi,
We have a scenarios (Idoc to JMS) with JDBC lookup. We have used graphical JDBC lookup functionality.
We are reading country names for a given country code from SAP in an external database table. The query is so simple. That should not take much time
Now the actual issues is,
When we are executing the scenario, its taking quite a long time. Almost 6 minutes to excute a mapping. Which causing high performance issue in the Porduction.
We started the inviestigation about found some interesting stuff. Here we have used Willy Introscope for the investigation.
1. First few messages are taking quite a long time. LIke 6 minutes per messages. As i can see in the log i am getting below error in Willy,
I dont know why PI is executing below queury apart from real secelt query to fetch the country name. I am getting below error: Error Message: Backends|ABCD2 mydatabase01-1526 (Oracle DB)|SQL|Dynamic|Query|SELECT ? FROM DUAL: java.sql.SQLException: Io exception: Connection timed out
2. After couple of messages, interface works very normal. I mean rest of the messages works pretty fine.
Please let me know if you have any idea about this error. What could be the problem for the issue.
Thank you in advnace.
Best Regards,
Prasad.Did you check how many SQL requests were executed per one message ? Do you have a log of these SQL requests ?
I assume that the country table is quite small, so that lookup should not be an issue.
About this:
>Message: Backends|ABCD2 mydatabase01-1526 (Oracle DB)|SQL|Dynamic|Query|SELECT ? FROM DUAL: >java.sql.SQLException: Io exception: Connection timed out
1. I only know SELECT * FROM DUAL, not SELECT ? FROM DUAL. Better use the former
2. the exception means that the database server can not be reached => check your network configuration
So I assume that there is a network (performance) problem between PI and this Oracle server. Or the Oracle Server is so overloaded that it has (sometimes) problems in processing new requests.
CSY
Edited by: Christian Sy on Mar 9, 2010 10:17 AM -
Hi
I work with Oracle JDev 10g with database as Oracle 10g.The query:
SELECT ''x'' FROM DUAL
is executed automatically whenever I forward my application control from one java file to another through structs.
I have not coded this query anywhere in my application. I did a full search in the application. The query is no where found. But the database shows this query as the most executed query in the application.
Has anyone faced a similar knid of issue?
Thanks in Advance
ShobaHi,
did you check te business service? Struts alone doesn't query the database, so my assumption is that there must be a View instance doing it
Frank -
Issue with Select options in select statement - ABAP Question
Hi
I am facing an issue with select options. Select statement is returning sy-subrc as 4.
I wrote the program as below:
SELECT-OPTIONS:
s_kunnr FOR bsad-kunnr,
s_lifnr FOR bsak-lifnr,
s_gjahr FOR bsad-gjahr,
s_bukrs FOR bsad-bukrs,
s_saknr FOR bsad-saknr,
s_budat FOR bsak-budat.
In start of selection I have written the select statement as
SELECT * FROM bsak INTO TABLE lt_bsak
WHERE bukrs IN s_bukrs AND lifnr = s_lifnr AND gjahr IN s_gjahr AND budat IN s_budat AND saknr IN s_saknr.
In selection screen I have not entered any values and executed the program. I am not getting any result. When I debug that, sy-subrc is 4 at above select statement. But table has records.
If am removing the "lifnr = s_lifnr " condition in select then select is returning values.
I am not getting where I made the mistake. Please suggest.
Thank you
HanuHi,
The problem here with where condition select option lifnr = s_lifnr.
Use below select query.
SELECT * FROM bsak INTO TABLE lt_bsak
WHERE bukrs IN s_bukrs
AND lifnr IN s_lifnr
AND gjahr IN s_gjahr
AND budat IN s_budat
AND saknr IN s_saknr.
s_lifnr is a select option and you are passing it as parameter lifnr = s_lifnr.
if you want to pass this s_lifnr as single vale then pass in below mentioned way.
lifnr = s_lifnr-low
BR,
Vijay -
Select sysdate from dual, why?
I have been looking at the SQL that is generated during fetches, updates
etc. Why is the SELECT SYSDATE FROM DUAL being executed prior to every sql
statement being executed?
If I had to guess I would say it has to do with locking or logging but
don't really have a clue!
I suppose the final question is ... how can I switch it off!
Thanks in advance
MattHave not seen oracle just dropping connection. In any case if you are using
oracle JDBC 2 it has error event which lets you handle error conditions plus
PooledConnection.getConnection() raises exception if its underlying physical
connection is dead so you can catch it and discard old PooledConnection (and
do not return it to the pool) and create new one without error ever going to
the user. No need for "select sysdate from dual" once in a while or god
forbid on every getConnection() /* hope oracle handles it more efficiently
*/ I stress tested my pool implementation - running many threads on JDO
reads and killing connections on server left and right and Kodo never saw
killed connections - it all was handled within pool itself without anything
like "select sysdate from dual". What I am trying to say is at least as far
as Oracle JDBC concerned their PooledConnection takes care of this
"Patrick Linskey" <[email protected]> wrote in message
news:[email protected]...
Matt,
We issue this to validate that connections retrieved from the pool are,
in fact, open. Oracle has a nasty habit of dropping connections (you'd
be surprised with some of the ways that Oracle sucks...), so it tends
to be good to do this check relatively frequently.
The frequency at which it occurs depends on a number of factors. First,
it depends on whether or not you are using a connection pool. I believe
that if you do not use the conn pool, then we probably check every time
you get a connection. Second, it depends on the setting of the
com.solarmetric.kodo.impl.jdbc.ConnectionTestTimeout setting, which
specifies how often to check connections for validity. I believe that
it's a number in seconds, but I'm not 100% sure; the configuration
section of our docs will have the right answer. Third, it depends on
the setting of com.solarmetric.kodo.impl.jdbc.ConnectionRetainMode,
which controls when we get connections and when we release them.
Finally, you can turn it off altogether by setting the
com.solarmetric.kodo.impl.jdbc.DBDictionaryProperties property to
contain the string 'ValidateConnections=false', which will turn off
connection validation altogether.
-Patrick
Patrick Linskey
SolarMetric Inc. -
URGENT HELP PLS : Issue with Multi Level Master Detail block
This is an issue someone else had posted in this forum few years back but there was no solution mentioned, I have run into this same issue , The problem is as explained below.
Any help on this is appreciated.
Scenario:
There are 3 Blocks in the form : A (Master Block)
: B (Detail of A )
: C (Detail of B )
There is master detail relation created between A and B and B and C. So initially when we query for a record in Master A, it shows all records properly in B and C.
Now if i navigate to the first record of B , and then second record of B , records corresponding to that record shows up properly in C block.
Till now everything works fine.
Issue 1:
But in case after querying initially on Master Block A,If I go directly to the second record of B block, it clears the whole B block and C block.
Issue 2:
Same thing happens if I am on C block ( corresponding to second record of B block) and then navigate to first record in B block , it again clears the whole B block and C block.
Please Help !!
Thanks !Thanks Xem for Your reply , I tried those settings but it did not help..here is the original link that to the thread that talks about the same problem ,
Issue with Multi Level Master Detail block
The last update to this was the following :
"I figured out that this is happening because Block Status is set to 'Changed' and this is causing it to clear out the blocks.
But cant figure out why the status is setting to 'Changed' "
Any Help from the form Gurus on this form in this matter is truely appreicated !!
Thanks,
Zid. -
Mutating Problem when insert while selecting data from dual
Hi All,
we have a table
test (
ID NUMBER
NAME VARCHAR2(100)) and a before insert trigger
create or replace trigger test1
before insert on test
for each row
begin
select decode(max(id),null,1,max(id)+1) into :new.id from test;
end;
i am able to insert values by using
"insert into test(name) values('test1')" with out any issues.
when i am inserting the values
"insert into test(name) select 'test1' from dual" i am getting error
ORA-04091: table SCOTT.TEST is mutating, trigger/function may not see it
Could someone please advice why i am getting error in second scenario.
Thanks in Advance
PrasadPrasad
try
insert into test (name) values ((select 'test1' from dual));
Frank -
What is "Select 'x' from dual" for?
I found a lot of sessions remains open with the statement "SELECT 'x' FROM DUAL".
I think it cause my db server become slowly and can't be connected.
I want to know where the statement is from and why it exist.
pls help me,thanks"Select 'x' from dual" is issued to make sure that database is still alive. It is issued by BC4J AM pool code and OC4J.
Thanks.
Sung -
declare
begin
for cur in (select (select 1 from dual) col from dual)
loop
null;
end loop;
end;in TOAD, OK, BUT IN FORM ERROR!
Edited by: indoracle on Feb 23, 2012 2:38 AM
Edited by: indoracle on Feb 23, 2012 2:40 AMA couple of things.
First, please take a few minutes to review the following:
<ul>
<li>Oracle Forums FAQ
<li>Before posting on this forum please read
<li>10 Commandments for the OTN Forums Member
<li>How to ask questions the smart way
</ul>
Following these simple guidelines will ensure you have a positive experience in any forum; not just this one! ;-)
Using the formating information in the Oracle Forms FAQ, it is always recommended that you put your code samples in the ... tags (use lower case "code") so your code is more readable.
Second, the use of all capital letters is concidered YELLING. I'm sure you did not intend to YELL at anyone, so please only use capital letters when they are needed, not for everything. :)
Third, what is your Forms Version? If you look at the *10 Commandments for the OTN Forums Member* you'll see that it is always best to give program version information. Depending on your Forms version, the subquery in your SQL statement may not be supported or it could simply be the Cursor For Loop construct [ FOR j IN ( SQL Statement)...] that is not supported. You may have to declare an explicit cursor and reference the explicit cursor in place of your SQL Statement.
Forth, your FOR LOOP doesn't do anything!
LOOPEND LOOP; There is nothing between LOOP and END LOOP. I am going to assume that this is intented and just a point of sanatizing your code because what happens in the loop is not relevant to the error.
ERROR 103.. This is a Forms internal PL/SQL error; meaning the Forms PL/SQL engine can not parse your code. Again, this is probably because the subquery or cursor FOR loop with (SQL Statement versus explicit cursor) is not supported by your Forms version.
Please, what is your Forms version and any other information that might be helpful.
Craig... -
Select sysdate from dual (to custom format).
Dear all,
i like to SELECT SYSDATE FROM DUAL, and run this result in a query something like:
SELECT X, Y, Z FROM TABLENAME WHERE ACCESSDATE = (SELECT SYSDATE FROM DUAL);
The problem is that the value of ACCESSDATE is in an format like DD-MM-YYYY and that sysdate form dual is
DD-MON-YYYY.
How do i get sysdate into the format DD-MM-YYYY?
Thanks already,
Johan.Perhaps usefull for performance:
first of all: no subselect is not needed. sysdate can be used as an argument directly (all functions are).
secondly, if accessdate is of type 'date' and the table has a lot of rows, converting it to a char will bypass the index usage. Instead, if you are worrying about the time try this (the display format is of no concern here if the datatype is date):
SELECT X, Y, Z FROM TABLENAME WHERE ACCESSDATE >trunc(sysdate) and ACCESSDATE < trunc(sysdate+1);
if accessdate is of type 'varchar2' then this should be enough (and should remain using the indexes on accessdate):
SELECT X, Y, Z FROM TABLENAME WHERE ACCESSDATE = to_date(sysdate,DD-MM-YYYY);
Hope this helps,
L. -
BC4J smarter way to: select sysdate from dual ????
Our architecture uses the DB server's date/time as the application's single
place to get date / time. So our UI's / business logic needs sysdate in several
places through screen flow and VO/Entities called by the business logic.
I'll create a SQLView at design time to package calling select sysdate from dual.
We're currently using Dynamic unnamed Views which are more expensive than just
getting sysdate deserves and also are a memory leak if you don't
call vo.remove() after you're done with the result set.
But is there a simplier or smarter way to get sysdate from the DB than the more
heavy weight than seems necessary step of instantiating a VO and creating a
result set to get the String sysdate???
Thanks,
curtI cache viewObjects in the MT using some ViewObjectManager and had no
problems till now (more then 6 months of production). Any AM that
serve dynamic requests should have own ViewObjectManager-object.
import oracle.jbo.*;
import java.util.Hashtable;
import java.util.Enumeration;
public class ViewObjectManager {
private ApplicationModule _appMod;
private Hashtable _viewObjectNames;
public ViewObjectManager(ApplicationModule am) {
_appMod = am;
_viewObjectNames = new Hashtable();
public ViewObject getViewObject( String selectClause_,
String fromClause_,
String whereClause_ ) {
ViewObject vo_ = null;
String sqlStmt_ = _getSQLStmtFromClauses
( selectClause_, fromClause_, whereClause_ );
String key_ = sqlStmt_;
String voName_ = (String)_viewObjectNames.get(key_);
boolean isNew_ = ( voName_ == null );
if ( !isNew_ ) {
vo_ = appMod.findViewObject(voName);
if ( vo_ == null ) {
viewObjectNames.remove(key);
isNew_ = true;
if ( isNew_ ) {
vo_ = appMod.createViewObjectFromQueryStmt( null, sqlStmt );
viewObjectNames.put( key, vo_.getName() );
return vo_;
private String getSQLStmtFromClauses( String selectClause,
String fromClause_,
String whereClause_ ) {
return
"SELECT "+selectClause_
+" FROM "+fromClause_
+( whereClause_ == null || whereClause_.equals("")
? "" : " WHERE "+whereClause_ ) ;
Client method in this case looks like that:
public static synchronized BigDecimal getNewId
( RequestOnNewId request__,
QueryableApplicationModule am__ ) {
String viewObjectName_ = request__.viewObjectName,
sequenceName_ = request__.sequenceName,
fromClause_ = request__.fromClause;
BigDecimal new_id_ = null;
ViewObject vo_;
Row row_;
Object obj_;
vo_ = am__.getViewObjectManager()
.getViewObject( sequenceName_+".NEXTVAL AS \"NEWID\"",
"DUAL",
null );
vo_.executeQuery();
row_ = vo_.first();
obj_ = row_.getAttribute("NEWID");
new_id_ = (obj_ == null) ? null : ((Number)obj_).bigDecimalValue();
return new_id_;
Hope this helps.
Arkadi Ganov
[email protected]
Maybe you are looking for
-
Hi, I have Yahoo mail and I use Firefox. I'm just wondering how opening attachments works with Yahoo mail. Today I opened an attachment and it gave a preview of what the attachment was. Does this preview mean that the attachment has downloaded onto m
-
Poor Quality Table borders in PDF
Hello. I am having problems having the tables borders in Word 2007 look the same in the PDF (using Arobat 9 Pro). The quality is very poor which appears the lines are thicker than in the Word document. I am using 4000 DPI, High Quality print but stil
-
Requried Help in creating function
Hi All, i need one help in creating function my input parameters for that function will be 1 or 1,2 or 1,2,3 my output should be If i pass as 1 as input parameter it should return 1 If i pass 1,2 as input parameter it should return 1,2 in different r
-
Hi, I am working with smartforms.How can I see the second page in print view.I am getting only 1 of 1.I need 1 of 2 and 2 of 2.I kept in main window command node->goto->second page.But I can not see main window in first page. Thanks rahul
-
Hunt group type Set up with outside ext numbers ie Cell phones
Using CUCM 9.1 Is there a quick and easy way to create a hunt group type set up using outside (cell phone numbers)? The scenario will be one (person who will be ON Call) using an internal DID that is forwarded to to a cell phone of the oncall person