GROUP BY and DISTINCT clause in single query
Hi All,
I have this query:
SELECT studyid,baseline_no,trans_date, min(trunc(compass_date)),drug_related_yn
FROM cp_bdr_trigger_tbl cbtt
WHERE NOT EXISTS (SELECT 1
FROM cp_patient_info_tbl
WHERE studyid = cbtt.studyid
AND baseline_no = cbtt.baseline_no)
AND studyid = '0431-020'
GROUP BY BASELINE_NO,STUDYID,DRUG_RELATED_YN;
The o/p of this query has around 20 rows with same studyid and distinct baseline_no.
Now I want to select the data all to be distinct by limiting it somehow by GROUP BY clause.
Is this possible?
I mean grouping should be done in such a way that it should return distinct values only...
The o/p of this query is input to other query for insertion in some table.
* there is a Unique index in the target table on studyid+basline_no combination so the combination has to be unique*
Thanks,
Aashish S.
The GROUP BY is in a way an implied DISTINCT because it will return ONE record for each of the columns identified in the GROUP BY clause.
Either way your requirements aren't very clear. If you can please post the following we may be able to help:
1. Oracle version (e.g. 10.2.0.4)
2. CREATE / INSERT statements with sample data
3. Expected output
4. Use \ tags (surround #2 and #3 in these tags)
5. Explanation of logic in achieving #3.
Thanks!
Similar Messages
-
Avoid distinct clause in the query
hi i have a query from a single table using distinct clause and has columns (a,b,c,d,e,f,g,h,i)
eg: select distinct a,b ,c,d from table
where a<>0 and b<>0 and c<>0 and d<>0 and e=o and f=0 and g=0 and h=0 and i=0 ;
when i see the execution plan with out distinct... it performs a bit faster.
how do i remove distinct clause and make the query perform better
this particular query is used as inline view in my vieiw . it is used in from clause .
please suggest
second question.... iam getting bitmap index to rowid conversion ...is this good? does it hamper performance . how to avoid this?
regards
raj
Edited by: raj_fresher on Jul 17, 2009 7:48 AMHi Raj
what is e in the query ?It is the column name you provided yourself in your own unformatted example.
After 400+ posts I thought you would understand that it's not that hard to put this exact tag => (yes, 6 characters, 4 letters between 2 curly brackets) before and after your code examples or sample data or explain plans.
That way you maintain formatting and improve readability for us poor readers by magnitudes.
But, I'm sure you'll succeed as well as all the others who can.
I always look on the bright side.
Example:
Earlier this week another Raj also finally got enlightened about it, and his life has since then changed forever!
+He drives a Bentley now, you know+ ;) -
Suppress "Distinct" Clause from Answers Query
Hello All:
How can I suppress the "Distinct" clause that the BI Server issues to the Oracle Database?
For Ex:
I have a customer Table with FirstName and LastName as columns. If I Query FirstName and LastName in Answers, BI server sends a Query like this:
select distinct T8944.fname as c1,
T8944.lname as c2
from
CUSTOMER T8944
order by c1, c2
This will suppress customers having the same name even if their customer Id is different. I want their names included also.
I would appreciate your help.
Thanks
rkingmduAFAIK, there's no config setting or so to prevent this implicit grouping. What you can do though is to add the customer Id ot the report and make the column hidden (Column Format - Hide).
Hth,
Chris
Edited by: Christian Berg on Sep 25, 2008 4:39 PM:
Or what Matt said ;-) Should type faster... -
Use of group by and having clause
hi frnds
can anybody explain me the use of group by an having clause in select state mentHi Rohit,
1. GROUP BY f1 ... fn
2. GROUP BY (itab)
1. GROUP BY f1 ... fn
Effect
Groups database table data in a SELECT command on one line in the result set. A group is a set of lines which all have the same values in each column determined by the field descriptors f1 ... fn.
... GROUP BY f1 ... fn always requires a list in the SELECT clause. If you use field descriptors without an aggregate funciton in the SELECT clause, you must list them in the GROUP BY f1 ... fn clause.
Example
Output the number of passengers, the total weight and the average weight of luggage for all Lufthansa flights on 28.02.1995:
TABLES SBOOK.
DATA: COUNT TYPE I, SUM TYPE P DECIMALS 2, AVG TYPE F.
DATA: CONNID LIKE SBOOK-CONNID.
SELECT CONNID COUNT( * ) SUM( LUGGWEIGHT ) AVG( LUGGWEIGHT )
INTO (CONNID, COUNT, SUM, AVG)
FROM SBOOK
WHERE
CARRID = 'LH' AND
FLDATE = '19950228'
GROUP BY CONNID.
WRITE: / CONNID, COUNT, SUM, AVG.
ENDSELECT.
Note
... GROUP BY f1 ... fn is not supported for pooled and cluster tables.
2. GROUP BY (itab)
Effect
Works like GROUP BY f1 ... fn if the internal table itab contains the list f1 ... fn as ABAP source code. The internal table itab can only have one field. This field must be of the type C and should not be more than 72 characters long. itab must be enclosed in parentheses and there should be no blanks between the parentheses and the table name.
Note
The same restrictions apply to this variant as to GROUP BY f1 ... fn.
Example
Output all Lufthansa departure points with the number of destinations:
TABLES: SPFLI.
DATA: BEGIN OF WA.
INCLUDE STRUCTURE SPFLI.
DATA: COUNT TYPE I.
DATA: END OF WA.
DATA: WA_TAB(72) TYPE C,
GTAB LIKE TABLE OF WA_TAB,
FTAB LIKE TABLE OF WA_TAB,
COUNT TYPE I.
CLEAR: GTAB, FTAB.
WA_TAB = 'COTYFROM COUNT( * ) AS COUNT'. APPEND FTAB.
APPEND WA_TAB TO FTAB.
WA_TAB = 'CITYFROM'.
APPEND WA_TAB TO GTAB.
SELECT DISTINCT (FTAB)
INTO CORRESPONDING FIELDS OF WA
FROM SPFLI
WHERE
CARRID = 'LH'
GROUP BY (GTAB).
WRITE: / WA-CITYFROM, WA-COUNT.
ENDSELECT.
Regards,
Susmitha -
Need Help With SQL GROUP BY and DISTINCT
I am working on a project and need to display the total of each order based on the order id. For instance I want to display the order id, customer id, order date, and then the extension price (ol_quantity * inv_price).
I would then like a total displayed for order # 1 and then move on to order #2.
Here is my SQL code :
SELECT DISTINCT orders.o_id, customer.c_id, inv_price * ol_quantity
FROM orders, customer, inventory, order_line
GROUP BY orders.o_id, customer.c_id, inv_price, ol_quantity
ORDER BY orders.o_id;
When my code is run it displays the order id, customer id and inv_price * quantity (extension price) but no order total for the order number and a new group is not started when a new order number is started....they are all clumped together.
Any help is greatly appreciated!!Hi,
user12036843 wrote:
I am working on a project and need to display the total of each order based on the order id. For instance I want to display the order id, customer id, order date, and then the extension price (ol_quantity * inv_price).
I would then like a total displayed for order # 1 and then move on to order #2.
Here is my SQL code :
SELECT DISTINCT orders.o_id, customer.c_id, inv_price * ol_quantity
FROM orders, customer, inventory, order_line
GROUP BY orders.o_id, customer.c_id, inv_price, ol_quantity
ORDER BY orders.o_id;
When my code is run it displays the order id, customer id and inv_price * quantity (extension price) but no order total for the order number and a new group is not started when a new order number is started....they are all clumped together.
Any help is greatly appreciated!!Sorry, it's unclear what you want.
Whenever you post a question, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only), and the results you want from that data.
Explain, using specific examples, how you get those results from that data.
Always say what version of Oracle you're using.
Do you want the output to contain one row for each row in the table, plus an extra row for each distinct order, showing something about the order as a whole (e.g., total inv_price or average extension_price)? If so, you need GROUP BY ROLLUP or GROUP BY GROUPING SETS .
If you want one row of output for each row of the table, but you want to include something that reflects the group as a whole (again, e.g, total inv_prive or average extension_pcie), then you can us analytic functions. (Most of the aggregate functions, such as SUM and AVG have analytic counterparts that can get the same results without collapsing the result set down to one row per group.)
Here's an example of how to use GROUP BY GROUPING SETS.
Way we're interested in employees' salary and commission from the scott.emp table:
SELECT deptno
, ename
, sal
, comm
FROM scott.emp
ORDER BY deptno
, ename
;Output:
` DEPTNO ENAME SAL COMM
10 CLARK 2450
10 KING 5000
10 MILLER 1300
20 ADAMS 1100
20 FORD 3000
20 JONES 2975
20 SCOTT 3000
20 SMITH 800
30 ALLEN 1600 300
30 BLAKE 2850
30 JAMES 950
30 MARTIN 1250 1400
30 TURNER 1500 0
30 WARD 1250 500Now say we want to add the total income (sal + comm, or just sal if there is no comm) to each row, and also to add a row for each department showing the total sal, comm and income in that department, like this:
` DEPTNO ENAME SAL COMM INCOME
10 CLARK 2450 2450
10 KING 5000 5000
10 MILLER 1300 1300
10 8750 8750
20 ADAMS 1100 1100
20 FORD 3000 3000
20 JONES 2975 2975
20 SCOTT 3000 3000
20 SMITH 800 800
20 10875 10875
30 ALLEN 1600 300 1900
30 BLAKE 2850 2850
30 JAMES 950 950
30 MARTIN 1250 1400 2650
30 TURNER 1500 0 1500
30 WARD 1250 500 1750
30 9400 2200 11600(This relies on the fact that ename is unique.) Getting those results is pretty easy, using GROUPING SETS:
SELECT deptno
, ename
, SUM (sal) AS sal
, SUM (comm) AS comm
, SUM ( sal
+ NVL (comm, 0)
) AS income
FROM scott.emp
GROUP BY GROUPING SETS ( (deptno)
, (deptno, ename)
ORDER BY deptno
, ename
;Notice that we're displaying SUM (sal) on each row. Most of the rows in the output are "groups" consisting of only one row from the table, so the SUM (sa) for that goup will be the sal for the one row in the group.
Edited by: Frank Kulash on Nov 23, 2011 2:03 PM
Added GROUPING SET example -
Sales,Production and Stock in a single query
Hi gurus,
My scenario is this:
I want to create a sales report i.e. productwise sales report with the key figures,sales quantity,production quantity and stock quantity.On a daily basis.
can anyone guide me which are the cube and datasouce i need to use to get these values.
And also how to link those cubes to make this single report.
Thanks & Regards
RaguHi Ragu,
Its quiet wild question.
If you going for the activation of fresh Data Targets, check the BI Content for the KFs (Sales Quantity,Production Quantity,Stock Quantity)
<b>PP:</b> http://help.sap.com/saphelp_nw04/helpdata/en/af/dda937dac70003e10000009b38f8cf/frameset.htm
<b>Stock</b>
This can be achieved by the Stock Movements Cube:
http://help.sap.com/saphelp_nw04/helpdata/en/42/5959394ddcdd46bc73ea9b58930a4e/frameset.htm
<b>Sales</b>
This can be achieved from Sales Overview Cube
http://help.sap.com/saphelp_nw04/helpdata/en/71/1769372b2b7d20e10000009b38f842/frameset.htm
You will have to go for a MultiProvider will this three infoproviders.
Regards
Happy Tony -
I need to remove a duplicate records, due to certain circumstances, I can not apply Distinct in the SQL statement, noticed that Group by can used to eliminate duplicate rows from a result set. My questions : is the GROUP BY guaranteed to return every row to be unique ?
: Any bad ideas of Using GROUP BY as a synonym for DISTINCT ?
Thanks
Edited by: user11432758 on 12-Mar-2012 01:00user11432758 wrote:
I need to remove a duplicate records, due to certain circumstances, I can not apply Distinct in the SQL statement, noticed that Group by can used to eliminate duplicate rows from a result set. My questions : is the GROUP BY guaranteed to return every row to be unique ?
: Any bad ideas of Using GROUP BY as a synonym for DISTINCT ?
ThanksYes. The problem is that DISTINCT is a very bad idea in the first place. In 95% of the reasons it is wrong. Often when somebody uses DISTINCT that just hides deeper problems like a wrong or missing join condition. Just replaceing DISTINCT with GROUP BY will not solve the underlying issue (if there is one). But you might be one of the 5% where a distinct is needed. But in such a case there would be no reason to replace it with a group by.
Your case might be one where a SUBquery is better then a join.
Tell us what table creates the duplicated rows. i don't understand your FK relationships yet.
I also noticed that you join ACCOUNT.*Account*ID = CUSTOMER.*Customer*ID. Is this right?
Edited by: Sven W. on Mar 12, 2012 8:10 PM -
Group by clause and having clause in select
hi frnds
plz give me some information of group by and having clause used in select statement with example
thanksThe Open SQL statement for reading data from database tables is:
SELECT <result>
INTO <target>
FROM <source>
[WHERE <condition>]
[GROUP BY <fields>]
[HAVING <cond>]
[ORDER BY <fields>].
The SELECT statement is divided into a series of simple clauses, each of which has a different part to play in selecting, placing, and arranging the data from the database.
You can only use the HAVING clause in conjunction with the GROUP BY clause.
To select line groups, use:
SELECT <lines> <s1> [AS <a1>] <s2> [AS <a2>] ...
<agg> <sm> [AS <am>] <agg> <sn> [AS <an>] ...
GROUP BY <s1> <s2> ....
HAVING <cond>.
The conditions <cond> that you can use in the HAVING clause are the same as those in the SELECT clause, with the restrictions that you can only use columns from the SELECT clause, and not all of the columns from the database tables in the FROM clause. If you use an invalid column, a runtime error results.
On the other hand, you can enter aggregate expressions for all columns read from the database table that do not appear in the GROUP BY clause. This means that you can use aggregate expressions, even if they do not appear in the SELECT clause. You cannot use aggregate expressions in the conditions in the WHERE clause.
As in the WHERE clause, you can specify the conditions in the HAVING clause as the contents of an internal table with line type C and length 72.
Example
DATA WA TYPE SFLIGHT.
SELECT CONNID
INTO WA-CONNID
FROM SFLIGHT
WHERE CARRID = 'LH'
GROUP BY CONNID
HAVING SUM( SEATSOCC ) > 300.
WRITE: / WA-CARRID, WA-CONNID.
ENDSELECT.
This example selects groups of lines from database table SFLIGHT with the value LH for CARRID and identical values of CONNID. The groups are then restricted further by the condition that the sum of the contents of the column SEATSOCC for a group must be greater than 300.
The <b>GROUP BY</b> clause summarizes several lines from the database table into a single line of the selection.
The GROUP BY clause allows you to summarize lines that have the same content in particular columns. Aggregate functions are applied to the other columns. You can specify the columns in the GROUP BY clause either statically or dynamically.
Specifying Columns Statically
To specify the columns in the GROUP BY clause statically, use:
SELECT <lines> <s1> [AS <a 1>] <s 2> [AS <a 2>] ...
<agg> <sm> [AS <a m>] <agg> <s n> [AS <a n>] ...
GROUP BY <s1> <s 2> ....
To use the GROUP BY clause, you must specify all of the relevant columns in the SELECT clause. In the GROUP BY clause, you list the field names of the columns whose contents must be the same. You can only use the field names as they appear in the database table. Alias names from the SELECT clause are not allowed.
All columns of the SELECT clause that are not listed in the GROUP BY clause must be included in aggregate functions. This defines how the contents of these columns is calculated when the lines are summarized.
Specifying Columns Dynamically
To specify the columns in the GROUP BY clause dynamically, use:
... GROUP BY (<itab>) ...
where <itab> is an internal table with line type C and maximum length 72 characters containing the column names <s 1 > <s 2 > .....
Example
DATA: CARRID TYPE SFLIGHT-CARRID,
MINIMUM TYPE P DECIMALS 2,
MAXIMUM TYPE P DECIMALS 2.
SELECT CARRID MIN( PRICE ) MAX( PRICE )
INTO (CARRID, MINIMUM, MAXIMUM)
FROM SFLIGHT
GROUP BY CARRID.
WRITE: / CARRID, MINIMUM, MAXIMUM.
ENDSELECT.
regards
vinod -
How to use SEM_RELATED & SEM_MATCH in a single query
Hi,
I am trying to combine RDF and RDBMS data using SEM_RELATED.
Below sample is working fine but the requirement is i have to add few more conditions in SEM_MATCH
Please suggest me how to combine sem_match and sem_related in a single query.
Please provide me the example which use SEM_MATCH and SEM_RELATED in a single query.
SELECT distinct dg_term_property.CONTEXT_NM FROM dg_term_property,dg_term
WHERE SEM_RELATED ('<http://www.cs.com/mdm/data_glossary#Facilities>',
'<http://www.w3.org/2000/01/rdf-schema#subClassOf>',
'<http://www.cs.com/mdm/data_glossary#Reference_Data_Classes>',
sem_models('GSR_PR_CURR'), sem_rulebases('owlprime')) = 1
and DG_TERM.TERM_NM=DG_TERM_PROPERTY.TERM_NM;
Let me know if you need any other details.
Regards,
Kavitha.Hi Kavitha,
I am not sure what exactly you are trying to accomplish with this query but the use of the SEM_RELATED is incorrect. To fulfill your requirement most likely you may not even need to combine SEM_RELATED with SEM_MATCH. Actually those two are not built to be used together.
Take a look at the SEM_RELATED documentation and see if you can use it to get the results you need. The example that you are providing is not using the SEM_RELATED correctly.
Here is the documentation:
http://docs.oracle.com/cd/E11882_01/appdev.112/e25609/owl_concepts.htm#CHDJBGFI
Go to:
2.3 Using Semantic Operators to Query Relational Data
Regards!
Jorge
Edited by: jbarba on Aug 20, 2012 10:20 AM
Edited by: jbarba on Aug 20, 2012 10:21 AM -
Select top row in Single Query?
Hi
Can somebody help me to write a query to get the first row after order by clause using single query alone.
Example:
I can write following query to select first row
select * from (selec * from t order by col1) where rownum = 1;
But here I should not use inline view to get the result. Because my original requirement needs to use this query in select list and it needs to use a column (of a table from the FROM clause) in the where clause of inline query. Because there is restriction that we can not use the column (of a table from the FROM clause) more than one level of inline query.
Please help me.Raghav.786 wrote:
Hi
Can somebody help me to write a query to get the first row after order by clause using single query alone.
Example:
I can write following query to select first row
select * from (selec * from t order by col1) where rownum = 1;
But here I should not use inline view to get the result. Because my original requirement needs to use this query in select list and it needs to use a column (of a table from the FROM clause) in the where clause of inline query. Because there is restriction that we can not use the column (of a table from the FROM clause) more than one level of inline query.
Please help me.
What Oracle version are you?
If you have 12c you can use
select col1,...
from t
order by col1
fetch first 1 row only;
If less than 12c, you have can't do it without a subquery.
What are you actually trying to do? Read Re: 2. How do I ask a question on the forums?
and follow the advice there by giving example create table and insert sample data statements and
explaining clearly what you are trying to do. Then we can help more. -
Selecting data from single table with different condition in single query
Hi everybody...
I have one table with col1, col2, col3, col4, col5... as columns.
I want to select col1, col2, col3 with condition (x=y and a=b and c=d)
I want to select col4, col5 with condition (x=y and a=b and m=n )
in single query...
Thanx for ur helpGiven this data set...
SQL> select * from oddity
2 /
COL1 COL2 COL3 COL4 COL5 A X C M
1 2 3 4 5 B Y M
1 2 3 4 5 A Y C N
1 2 3 4 5 A Y D M
1 2 3 4 5 A Y D N
1 2 3 4 5 B Y D N
1 2 3 4 5 B Y D U
6 rows selected.
SQL>The following query meets the requirements. Of course, the requirements as stated are incomplete. I ahave assumed that we select all five columns if C=D andM=N.
SQL> SELECT decode(c, 'D', col1, '0') AS col1
2 , decode(c, 'D', col2, '0') AS col2
3 , decode(c, 'D', col3, '0') AS col3
4 , decode(m, 'N', col4, '-8') AS col4
5 , decode(m, 'N', col5, '-8') AS col5
6 FROM oddity
7 WHERE a = 'B'
8 AND x = 'Y'
9 /
COL1 COL2 COL3 COL4 COL5
0 0 0 -8 -8
1 2 3 4 5
1 2 3 -8 -8
SQL> Cheers, APC -
How to read the child elements in single query
Hi
How to read the child elements under 'alternateIdentifiers' and 'matchEntityBasic' in a single query followiing xml content.xml content is of xmltype
I/p doc
<UPDATES>
<matchEntity>
<sourceUpdateId>SAMSUNG</sourceUpdateId>
<matchEntityId>861873</matchEntityId>
<alternateIdentifiers>
<sourceUpdateId>SAMSUNG</sourceUpdateId>
<schemeCode>SMG</schemeCode>
<effectiveDate>2012-01-16</effectiveDate>
</alternateIdentifiers>
<alternateIdentifiers>
<sourceUpdateId>SAMSUNG</sourceUpdateId>
<schemeCode>TEBBGL</schemeCode>
<effectiveDate>2012-01-16</effectiveDate>
</alternateIdentifiers>
<matchEntityBasic>
<sourceUpdateId>SAMSUNG</sourceUpdateId>
<marketExchangeCode>XASE</marketExchangeCode>
</matchEntityBasic>
</matchEntity>
</UPDATES>
o/p
sourceUpdateId schemeCode effectiveDate marketExchangeCode
SAMSUNG SMG 2012-01-16 XASE
SAMSUNG TEBBGL 2012-01-16
Oracle Database 11g Enterprise Edition Release 11.2.0.2.0 - 64bit Production
i tried the query but not working
SELECT sourceUpdateId ,schemeCode ,effectiveDate ,marketExchangeCode FROM message pl,XMLTABLE ('/UPDATES/matchEntity/alternateIdentifiers'
PASSING pl.messagetext
COLUMNS sourceUpdateId VARCHAR2 (20) PATH sourceUpdateId,
schemeCode VARCHAR2 (20) PATH 'schemeCode',
effectiveDate DATE PATH 'effectiveDate',
marketExchangeCode VARCHAR2 (20) PATH './matchEntityBasic/marketExchangeCode'
) x
iam not retriving marketExchangeCode with the following query
marketExchangeCode VARCHAR2 (20) PATH './matchEntityBasic/marketExchangeCode'
thanksThe problem is that "matchEntityBasic" is not a child of "alternateIdentifiers", so this :
./matchEntityBasic/marketExchangeCodepoints to nothing.
To display both values in the same query, you'll need a two-level approach.
For example :
SQL> SELECT x2.sourceUpdateId
2 , x2.schemeCode
3 , x2.effectiveDate
4 , x1.marketExchangeCode
5 FROM message pl
6 , XMLTable(
7 '/UPDATES/matchEntity'
8 passing pl.messagetext
9 columns marketExchangeCode VARCHAR2(20) PATH 'matchEntityBasic/marketExchangeCode'
10 , alternateIds XMLType PATH 'alternateIdentifiers'
11 ) x1
12 , XMLTable(
13 '/alternateIdentifiers'
14 passing x1.alternateIds
15 columns sourceUpdateId VARCHAR2(20) PATH 'sourceUpdateId'
16 , schemeCode VARCHAR2(20) PATH 'schemeCode'
17 , effectiveDate DATE PATH 'effectiveDate'
18 ) x2
19 ;
SOURCEUPDATEID SCHEMECODE EFFECTIVEDATE MARKETEXCHANGECODE
SAMSUNG SMG 16/01/2012 XASE
SAMSUNG TEBBGL 16/01/2012 XASE
Or the shorter version :
SQL> SELECT x.sourceUpdateId
2 , x.schemeCode
3 , x.effectiveDate
4 , x.marketExchangeCode
5 FROM message pl
6 , XMLTable(
7 'for $i in /UPDATES/matchEntity
8 return
9 for $j in $i/alternateIdentifiers
10 return element r { $j/child::*, $i/matchEntityBasic/marketExchangeCode }'
11 passing pl.messagetext
12 columns sourceUpdateId VARCHAR2(20) PATH 'sourceUpdateId'
13 , schemeCode VARCHAR2(20) PATH 'schemeCode'
14 , effectiveDate DATE PATH 'effectiveDate'
15 , marketExchangeCode VARCHAR2(20) PATH 'marketExchangeCode'
16 ) x
17 ;
SOURCEUPDATEID SCHEMECODE EFFECTIVEDATE MARKETEXCHANGECODE
SAMSUNG SMG 16/01/2012 XASE
SAMSUNG TEBBGL 16/01/2012 XASE -
Distinct clause and query performance
Friends,
I have a query which returns results in 40 seconds without distinct clause and when I add distinct clause it takes over 2 hours.
I have verified following -
1. indexes/table statistics are up to date.
2. columns that are used in where clause but are not indexed have upto date column statistics
Any idea what could be the reason, explain plan shows that distinct clause has a very expensive cost.
Thanks
Query and explain plan is below
SELECT
DISTINCT -- with distinct 2hrs + and without 40 seconds
quote_by_dst.qte_hdr_stat_cd, quote_by_dst.qte_ln_cond_cd,
product.prod_nm, product.prod_id,
cs_ship_by_dst.bto_ds_cac_ownr_ud,
quote_by_dst.qte_csup_csup_am, cs_ship_by_dst.bto_ds_cac_nm,
product.spl_sht_nm,
product.prod_blg_un_fac_um
|| ' '
|| product.prod_blg_um
|| ' '
|| product.prod_stck_um,
product.prod_blg_um, quote_by_dst.qte_ln_brk_1_blg_uom_am,
quote_by_dst.qte_csup_avg_cst_am,
quote_by_dst.qte_csup_rev_gm_pct_am,
quote_by_dst.qte_csup_avg_cst_am, cs_ship_by_dst.bto_id,
cs_ship_by_dst.bto_ds_cac_cd,
cs_ship_by_dst.bto_ds_cac_cd
|| product.prod_id
|| cs_ship_by_dst.bto_id
FROM infowhse.quote_by_dst4 quote_by_dst,
infowhse.product,
infowhse.cs_ship_by_dst4 cs_ship_by_dst,
infowhse.department
WHERE (quote_by_dst.dpt_cd = department.dpt_cd)
AND (quote_by_dst.cus_dpt_id = cs_ship_by_dst.cus_dpt_id)
AND (product.prod_id = quote_by_dst.prod_id)
AND ( ( quote_by_dst.qte_ln_cond_cd = 'E'
OR quote_by_dst.qte_ln_cond_cd = 'C'
AND quote_by_dst.qte_hdr_stat_cd = 'A'
AND ((cs_ship_by_dst.bto_cust_type_cd) = '01')
AND cs_ship_by_dst.bto_ds_cac_ownr_ud = 'EHOC'
AND department.dpt_cd > '0.00'
)Explain plan
Plan
SELECT STATEMENT CHOOSECost: 911,832,256 Bytes: 433,941,639,459 Cardinality: 2,729,192,701
15 SORT UNIQUE Cost: 911,832,256 Bytes: 433,941,639,459 Cardinality: 2,729,192,701
14 NESTED LOOPS Cost: 68,705 Bytes: 433,941,639,459 Cardinality: 2,729,192,701
12 HASH JOIN Cost: 68,705 Bytes: 425,754,061,356 Cardinality: 2,729,192,701
1 INDEX FAST FULL SCAN NON-UNIQUE INFOWHSE.DST_SEC_DST_SEC_DST_CD_IX Cost: 25 Bytes: 922,700 Cardinality: 184,540
11 HASH JOIN Cost: 16,179 Bytes: 1,199,209,082 Cardinality: 7,941,782
2 INDEX FAST FULL SCAN NON-UNIQUE INFOWHSE.DST_SEC_DST_SEC_DST_CD_IX Cost: 25 Bytes: 922,700 Cardinality: 184,540
10 HASH JOIN Cost: 15,879 Bytes: 3,374,060 Cardinality: 23,110
8 HASH JOIN Cost: 15,200 Bytes: 2,981,190 Cardinality: 23,110
6 HASH JOIN Cost: 13,113 Bytes: 1,779,470 Cardinality: 23,110
3 TABLE ACCESS FULL INFOWHSE.CUSTOMER_SHIP Cost: 5,640 Bytes: 42,372 Cardinality: 1,177
5 PARTITION RANGE ALL Partition #: 11 Partitions accessed #1 - #12
4 TABLE ACCESS FULL INFOWHSE.QUOTE Cost: 7,328 Bytes: 38,826,590 Cardinality: 946,990 Partition #: 11 Partitions accessed #1 - #12
7 TABLE ACCESS FULL INFOWHSE.PRODUCT Cost: 1,542 Bytes: 9,246,640 Cardinality: 177,820
9 INDEX FAST FULL SCAN NON-UNIQUE INFOWHSE.CUST_SHIP_SLSDST_DTP_SICALL_IX Cost: 185 Bytes: 9,878,411 Cardinality: 581,083
13 INDEX UNIQUE SCAN UNIQUE INFOWHSE.DEPARTMENT_PK Bytes: 3 Cardinality: 1This might be more useful.
Query is still running.
There is heavy wait time for scattered file read.
Results from
SELECT * FROM V$SESSION_WAIT WHERE SID = 48;
SID SEQ# EVENT P1TEXT P1 P1RAW P2TEXT P2 P2RAW P3TEXT P3 P3RAW WAIT_TIME SECONDS_IN_WAIT STATE
48 6865 db file scattered read file# 108 000000000000006C block# 1593370000000000026E69 blocks 32 0000000000000020 2 30 WAITED KNOWN TIME
SELECT * FROM V$SESSION_EVENT WHERE SID = 48;
SID EVENT TOTAL_WAITS TOTAL_TIMEOUTS TIME_WAITED AVERAGE_WAIT MAX_WAIT TIME_WAITED_MICRO
48 log file sync 1 0 0 0 0 563
48 db file sequential read 11 0 0 0 0 243
48 db file scattered read 6820 0 330 0 7 3296557
48 SQL*Net message to client 19 0 0 0 0 23
48 SQL*Net message from client 18 0 128 7 127 1281912 Sorry for long post. -
Problem with performance of a query having order by, distinct clause
Hi,
I have a problem with queries having order by, distinct clause.
While its executing its taking lot of time. With DBMS_PROFILER identified the queries taking long time.
The table is having approximately 70 million rows.
Problem -1
select * from table_name order by col1;
select distinct col1,col2 from table_name;
Here i am having 2 solutions request to let me know whether i am right if not suggest me right solution.
Solution1:
Max parallel servers is 8.
select /* + parallel(table_name,8) */ * from table_name order by col1;
select /* + parallel(table_name,8) */ distinct col1, col2 from table_name ;
Solution-2:
select /* + first_rows */ * from table_name order by col1;
select /* + first_rows */ distinct col1, col2 from table_name ;
Problem-2
I am having a query with where condition on columns.
Select * from table_name where col1='value1' and col2!='value2';
Index created on col1 and col2.
As we no that not equal won't use index as it is a composite index it should use the lead column. but its not using the index.
Should i forcibly use index with hint or suggest me better solution.
Any help really appreciated.
Thanks in advanceunique wrote:
The table is having approximately 70 million rows.
select * from table_name order by col1;Do you really want 70,000,000 rows from your table without any restrictions ? And furthermore ordered output ? I honestly understand the slowness of that query.
Here i am having 2 solutions request to let me know whether i am right if not suggest me right solution.Who knows if you choosed the right solution. I would suggest to reconsider your query and the need of 70,000,000 returned rows.
Problem-2
I am having a query with where condition on columns.
Select * from table_name where col1='value1' and col2!='value2';Please, provide the explain plan, eventually the tkprof output could also help. And tables descirption AND indexes description.
And OS and Oracle version.
Nicolas. -
Distinct data from different columns of a table-Single query
I have a table with different columns. Each of these columns have entries. A particular column, say, a column called name can have same entries more than one time. Likewise other columns can also have same entries more than once. My requirement is to have distinct entries from each of these columns using a single query, such that , for eg; the name column will contain the name George only once on retrieval. Place column will have the place Newyork only once...like that...but Newyork and newyork should be treated different(likewise in other columns also ie; case sensitive). I want to retrieve the above said using a single query from a table. Kindly help.
Regards,
AneesYou're asking a SQL question in a JDBC forum. Look for a SQL forum. The website of the database manfactuer may have a SQL forum/mailinglist.
Maybe you are looking for
-
Cannot delete organization OIM 9.1.0.2 BP09
I created organization in OIM through admin console. I tried to delete it but without success. The status is changed to "deleted" but it is still there. Is there a way to delete it permanently?
-
The screen on my MacBook goes black often. I can still see a faint image of what's on the screen, and can only get it to illuminate by moving it back and forth. What could the issue be? How can it be fixed?
-
Hi Michael, I read your comments on RFC_READ_TABLE. Have a query here, I am using that FM to read data from table EDID4(IDOC data table), and fields I am chosing are DOCNUM and SDATA which are definitely needed. The where clause is also take care of
-
Change the Condition base value in a Condition type.
Hi Experts, I have a problem because I need to change the condition base value for a condition type. This condition base is calculated as a result of other condition types in the list of pricing Elements. I would need to change the base in order to s
-
Hi, How to create an output file by using an integration script to view the source files ? Thanks, Ravi.