SQL Query Performance needed.
Hi All,
I am getting performance issue with my below sql query. When I fired it, It is taking 823.438 seconds, but when I ran query in, it is taking 8.578 seconds, and query after in is taking 7.579 seconds.
SELECT BAL.L_ID, BAL.L_TYPE, BAL.L_NAME, BAL.NATURAL_ACCOUNT,
BAL.LOCATION, BAL.PRODUCT, BAL.INTERCOMPANY, BAL.FUTURE1, BAL.FUTURE2, BAL.CURRENCY, BAL.AMOUNT_PTD, BAL.AMOUNT_YTD, BAL.CREATION_DATE,
BAL.CREATED_BY, BAL.LAST_UPDATE_DATE, BAL.LAST_UPDATED_BY, BAL.STATUS, BAL.ANET_STATUS, BAL.COG_STATUS, BAL.comb_id, BAL.MESSAGE,
SEG.SEGMENT_DESCRIPTION FROM ACC_SEGMENTS_V_TST SEG , ACC_BALANCE_STG BAL where BAL.NATURAL_ACCOUNT = SEG.SEGMENT_VALUE AND SEG.SEGMENT_COLUMN = 'SEGMENT99' AND BAL.ACCOUNTING_PERIOD = 'MAY-10' and BAL.comb_id
in
(select comb_id from
(select comb_id, rownum r from
(select distinct(comb_id),LAST_UPDATE_DATE from ACC_BALANCE_STG where accounting_period='MAY-10' order by LAST_UPDATE_DATE )
where rownum <=100) where r >0)
Please help me in fine tuning above. I am using Oracle 10g database. There are total of 8000 records. Let me know if any other info required.
Thanks in advance.
In recent versions of Oracle an EXISTS predicate should produce the same execution plan as the corresponding IN clause.
Follow the advice in the tuning threads as suggested by SomeoneElse.
It looks to me like you could avoid the double pass on ACC_BALANCE_STG by using an analytical function like ROW_NUMBER() and then joining to ACC_SEGMENTS_V_TST SEG, maybe using subquery refactoring to make it look nicer.
e.g. something like (untested)
WITH subq_bal as
((SELECT *
FROM (SELECT BAL.L_ID, BAL.L_TYPE, BAL.L_NAME, BAL.NATURAL_ACCOUNT,
BAL.LOCATION, BAL.PRODUCT, BAL.INTERCOMPANY, BAL.FUTURE1, BAL.FUTURE2,
BAL.CURRENCY, BAL.AMOUNT_PTD, BAL.AMOUNT_YTD, BAL.CREATION_DATE,
BAL.CREATED_BY, BAL.LAST_UPDATE_DATE, BAL.LAST_UPDATED_BY, BAL.STATUS, BAL.ANET_STATUS,
BAL.COG_STATUS, BAL.comb_id, BAL.MESSAGE,
ROW_NUMBER() OVER (ORDER BY LAST_UPDATE_DATE) rn
FROM acc_balance_stg
WHERE accounting_period='MAY-10')
WHERE rn <= 100)
SELECT *
FROM subq_bal bal
, acc_Segments_v_tst seg
where BAL.NATURAL_ACCOUNT = SEG.SEGMENT_VALUE
AND SEG.SEGMENT_COLUMN = 'SEGMENT99';However, the parentheses you use around comb_id make me question what your intention is here in the subquery?
Do you have multiple rows in ACC_BALANCE_STG for the same comb_id and last_update_date?
If so you may want to do a MAX on last_update_date, group by comb_id before doing the analytic restriction.
Edited by: DomBrooks on Jun 16, 2010 5:56 PM
Similar Messages
-
Sql query performance need to get improved
hi all..
i got performnace issue with my sp where i used 3 cte's.. i'm posting my code.please help me how can i improve the performance of query
i created non-clustered indexes for tables based on the keys with which the tables are joined..
USE [OPTM]
GO
/****** Object: StoredProcedure [dbo].[GetSample] Script Date: 01/07/2014 10:29:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[GetSample]
@StartDate DateTime,
@EndDate DateTime,
@Portfolio int,
@Program int,
@Project int
AS
Date Author Purpose
06/11/2012 Ajeesh.C To get the Workitem details for the Scope Workitem Green chart Report.
06/11/2012 Shinoj.P T-SQL re-structuring.
Testing :
exec [dbo].[GetSample] '01/01/2013','12/31/2013',-1,-1,-1
exec [dbo].[GetSample] '01/01/2013','12/31/2013',16,24,199
exec [dbo].[GetSample] '11/01/2013','12/31/2013',-1,-1,703
exec [dbo].[GetSample] '11/01/2012','11/30/2012',8,-1,-1
select * from tb_Portfolio
BEGIN
DECLARE @Scope nvarchar(250),@ScopeID int,@ProjectID int,@WorkItem nvarchar(250),@ProgramID int, @PortfolioID int;
-------Added 3 columns(StatusID,Status,TaskID)--------
CREATE TABLE #GrnChartTempTable
AllocationDate datetime NULL,
Division nvarchar(50) NULL,
DivisionID int NULL,
ResourceName nvarchar(250) NULL,
ResourceEmailID nvarchar(max) NULL,
ResourceID int NULL,
Project nvarchar(250) NULL,
ProjectID int NULL,
Scope nvarchar(MAX) NULL,
ScopeID int NULL,
WorkItem nvarchar(MAX) NULL,
TaskStartDate datetime NULL,
TaskEndDate datetime NULL,
ProgramID int NULL,
Program nvarchar(250) NULL,
PortfolioID int NULL,
Portfolio nvarchar(250) NULL,
StatusID int NULL,
Status nvarchar(50) NULL,
TaskID int null,
EstimateHrs nvarchar(250) NULL,
ScopeEstimateHrs int NULL,
Allocated int NOT NULL
WITH Datematrix(AllocationDate)
As
SELECT @StartDate AS AllocationDate
UNION ALL
SELECT DATEADD(D,1,AllocationDate) AS AllocationDate
FROM Datematrix WHERE AllocationDate<@EndDate
Allocation (Division,DivisionID,ResourceName,ResourceEmailID,ResourceID,Project
,ProjectID,Scope,ScopeID,WorkItem,TaskStartDate,TaskEndDate
,ProgramID ,Program,PortfolioID ,Portfolio,StatusID,Status,TaskID,EstimateHrs,ScopeEstimateHrs)
AS
SELECT
DIV.Division
,RES.DivisionID
,RES.ResourceName
,ResourceEmailID = STUFF((
SELECT COALESCE( ', ' + CONVERT(VARCHAR,RES.Email1), '')
FROM dbo.TasksResource TSKRES WITH(NOLOCK) LEFT OUTER JOIN
dbo.tb_Resource RES WITH(NOLOCK) ON RES.UID = TSKRES.ResourceID
WHERE TSKRES.TaskID = TSK.TaskID
FOR XML PATH('')), 1, 1, '')
,RES.UID ResourceID
,PRJ.Project + ' (' + CONVERT(VARCHAR(15),PRJ.StartDate,101) +' - ' + CONVERT(VARCHAR(15),PRJ.EndDate,101) + ')' as Project
,PRJ.UID ProjectID
,SCP.Title Scope
,SCP.ScopeID
,TSK.Title WorkItem
,TSK.StartDate TaskStartDate
,TSK.EndDate TaskEndDate
,PRJ.ProgramID
,PR.Program
,PR.PortfolioID
,PF.Portfolio
,TSK.StatusID
,ST.Status
,TSK.TaskID
,TSK.EstimateHrs
,(isnull(SCP.EstimateARCH,0) + isnull(SCP.EstimateBA,0) + isnull(SCP.EstimateDev,0) + isnull(SCP.EstimatePM,0) + isnull(SCP.EstimateQA,0) + isnull(SCP.EstimateRM,0)) as ScopeEstimateHrs
--SCP.EstimateARCH + SCP.EstimateBA +SCP.EstimateDev +SCP.EstimatePM +SCP.EstimateQA +SCP.EstimateRM as ScopeEstimateHrs
FROM Tasks TSK WITH(NOLOCK)
INNER JOIN dbo.Scope SCP WITH(NOLOCK) ON TSK.ScopeID = SCP.ScopeID
INNER JOIN dbo.tb_Project PRJ WITH(NOLOCK)ON TSK.ProjectID = PRJ.UID
INNER JOIN dbo.tb_Program PR WITH(NOLOCK) ON PR.UID=PRJ.ProgramID
INNER JOIN dbo.tb_Portfolio PF WITH(NOLOCK)ON PF.UID=PR.PortfolioID
LEFT OUTER JOIN dbo.TasksResource TSKRES WITH(NOLOCK)ON TSKRES.TaskID = TSK.TaskID
LEFT OUTER JOIN dbo.tb_Resource RES WITH(NOLOCK) ON RES.UID = TSKRES.ResourceID
LEFT JOIN dbo.tb_Division DIV WITH(NOLOCK) ON RES.DivisionID = DIV.UID
LEFT JOIN dbo.tb_Status ST WITH(NOLOCK) ON TSK.StatusID=ST.UID /*relating with the high level work items */
WHERE (PRJ.UID = @Project OR @Project = -1)
AND (PRJ.ProgramID = @Program OR @Program = -1)
AND (PRJ.PortfolioID =@Portfolio OR @Portfolio = -1)
MainData (AllocationDate,Division,DivisionID,ResourceName,ResourceEmailID,ResourceID,Project,ProjectID
,Scope,ScopeID,WorkItem,TaskStartDate,TaskEndDate
,ProgramID ,Program,PortfolioID ,Portfolio,StatusID,Status,TaskID,EstimateHrs,ScopeEstimateHrs,Allocated)
AS
( SELECT
Datematrix.*
,Allocation.*
,CASE WHEN ISDATE(TaskStartDate)=1 THEN 1 ELSE 0 END AS Allocated
FROM Datematrix FULL OUTER JOIN Allocation
ON ( Datematrix.AllocationDate>= Allocation.TaskStartDate
AND Datematrix.AllocationDate<=Allocation.TaskEndDate
INSERT INTO #GrnChartTempTable
SELECT * FROM MainData
OPTION (MAXRECURSION 0);
SELECT TOP 1 @Scope=Scope,@ScopeID=ScopeID, @ProjectID=ProjectID
,@WorkItem=WorkItem,@ProgramID=ProgramID,@PortfolioID=PortfolioID
FROM #GrnChartTempTable WHERE Scope IS NOT NULL AND ISDATE(AllocationDate)=1 ORDER BY Scope ;
SELECT AllocationDate,Division,DivisionID
,ResourceName,ResourceEmailID,ResourceID,Project
,ISNULL(ProjectID,@ProjectID) ProjectID
,ISNULL(Scope,@Scope) Scope
,ISNULL(ScopeID,@ScopeID) ScopeID
,ISNULL(WorkItem,@WorkItem) WorkItem
,TaskStartDate,TaskEndDate
,ISNULL(ProgramID ,@ProgramID) ProgramID
,Program
,ISNULL(PortfolioID,@PortfolioID) PortfolioID
,Portfolio,StatusID,Status,TaskID,EstimateHrs,isnull(ScopeEstimateHrs,0)ScopeEstimateHrs,Allocated
FROM #GrnChartTempTable MainData
WHERE ISDATE(MainData.AllocationDate)=1
AND ISNULL(Scope,@Scope) IS NOT NULL
--WHERE FinalData.Scope IS NOT NULL
END
this is my code pls help..
luckyYou need to focus on optimizing your code by looking at the logic and removing any extraneous rows that you do not need - stop depending on the optimizer to do your work.
You have the following in multiple lines: ISDATE(AllocationDate)=1
Look at your final resultset. You do not want any other rows (where isdate() <> 1) so stop selecting them in the first place. In addition, you are using a full outer join in the first query that uses this logic. Since you do not qualify
your columns with the tablename (or alias - which is a best practice), I cannot say if the isdate logic negates the full outer join - but I suspect it might. I also question the logic behind the assignment of the local variables and their use in the
final query. You could remove the separate assignment query (and the variables) by simply moving that query into a derived table (or cte) of the final query. That might not be a significant improvement (you did not give any indications about the size
of the various queries) but I think it is simpler, more resilient, more obvious. I also question the reasoning behind the use of a full outer join.
Why do you left join to dbo.tb_Status? Does not every task have a status?
You join to the TaskResource and tb_Resource tables multiple times (in the Allocation cte) - and it appears that there is a 1/m relationship between task and this joined resultset. Yet the primary query of the Allocation cte does no aggregation.
That is concerning, but I don't know your data so perhaps this is correct. OTH, perhaps it depends on an assumption and your existing data has not yet violated that assumption.
But these are only guesses. As Erland indicates, optimzing requires knowledge of the tables, the data, your business logic, etc. -
SQL query performance issues.
Hi All,
I worked on the query a month ago and the fix worked for me in test intance but failed in production. Following is the URL for the previous thread.
SQL query performance issues.
Following is the tkprof file.
CURSOR_ID:76 LENGTH:2383 ADDRESS:f6b40ab0 HASH_VALUE:2459471753 OPTIMIZER_GOAL:ALL_ROWS USER_ID:443 (APPS)
insert into cos_temp(
TRX_DATE, DEPT, PRODUCT_LINE, PART_NUMBER,
CUSTOMER_NUMBER, QUANTITY_SOLD, ORDER_NUMBER,
INVOICE_NUMBER, EXT_SALES, EXT_COS,
GROSS_PROFIT, ACCT_DATE,
SHIPMENT_TYPE,
FROM_ORGANIZATION_ID,
FROM_ORGANIZATION_CODE)
select a.trx_date,
g.segment5 dept,
g.segment4 prd,
m.segment1 part,
d.customer_number customer,
b.quantity_invoiced units,
-- substr(a.sales_order,1,6) order#,
substr(ltrim(b.interface_line_attribute1),1,10) order#,
a.trx_number invoice,
(b.quantity_invoiced * b.unit_selling_price) sales,
(b.quantity_invoiced * nvl(price.operand,0)) cos,
(b.quantity_invoiced * b.unit_selling_price) -
(b.quantity_invoiced * nvl(price.operand,0)) profit,
to_char(to_date('2010/02/28 00:00:00','yyyy/mm/dd HH24:MI:SS'),'DD-MON-RR') acct_date,
'DRP',
l.ship_from_org_id,
p.organization_code
from ra_customers d,
gl_code_combinations g,
mtl_system_items m,
ra_cust_trx_line_gl_dist c,
ra_customer_trx_lines b,
ra_customer_trx_all a,
apps.oe_order_lines l,
apps.HR_ORGANIZATION_INFORMATION i,
apps.MTL_INTERCOMPANY_PARAMETERS inter,
apps.HZ_CUST_SITE_USES_ALL site,
apps.qp_list_lines_v price,
apps.mtl_parameters p
where a.trx_date between to_date('2010/02/01 00:00:00','yyyy/mm/dd HH24:MI:SS')
and to_date('2010/02/28 00:00:00','yyyy/mm/dd HH24:MI:SS')+0.9999
and a.batch_source_id = 1001 -- Sales order shipped other OU
and a.complete_flag = 'Y'
and a.customer_trx_id = b.customer_trx_id
and b.customer_trx_line_id = c.customer_trx_line_id
and a.sold_to_customer_id = d.customer_id
and b.inventory_item_id = m.inventory_item_id
and m.organization_id
= decode(substr(g.segment4,1,2),'01',5004,'03',5004,
'02',5003,'00',5001,5002)
and nvl(m.item_type,'0') <> '111'
and c.code_combination_id = g.code_combination_id+0
and l.line_id = b.interface_line_attribute6
and i.organization_id = l.ship_from_org_id
and p.organization_id = l.ship_from_org_id
and i.org_information3 <> '5108'
and inter.ship_organization_id = i.org_information3
and inter.sell_organization_id = '5108'
and inter.customer_site_id = site.site_use_id
and site.price_list_id = price.list_header_id
and product_attr_value = to_char(m.inventory_item_id)
call count cpu elapsed disk query current rows misses
Parse 1 0.47 0.56 11 197 0 0 1
Execute 1 3733.40 3739.40 34893 519962154 11 188 0
total 2 3733.87 3739.97 34904 519962351 11 188 1
| Rows Row Source Operation
| ------------ ---------------------------------------------------
| 188 HASH JOIN (cr=519962149 pr=34889 pw=0 time=2607.35)
| 741 .TABLE ACCESS BY INDEX ROWID QP_PRICING_ATTRIBUTES (cr=519939426 pr=34889 pw=0 time=2457.32)
| 254644500 ..NESTED LOOPS (cr=519939265 pr=34777 pw=0 time=3819.67)
| 254643758 ...NESTED LOOPS (cr=8921833 pr=29939 pw=0 time=1274.41)
| 741 ....NESTED LOOPS (cr=50042 pr=7230 pw=0 time=11.37)
| 741 .....NESTED LOOPS (cr=48558 pr=7229 pw=0 time=11.35)
| 741 ......NESTED LOOPS (cr=47815 pr=7223 pw=0 time=11.32)
| 3237 .......NESTED LOOPS (cr=41339 pr=7223 pw=0 time=12.42)
| 3237 ........NESTED LOOPS (cr=38100 pr=7223 pw=0 time=12.39)
| 3237 .........NESTED LOOPS (cr=28296 pr=7139 pw=0 time=12.29)
| 1027 ..........NESTED LOOPS (cr=17656 pr=4471 pw=0 time=3.81)
| 1027 ...........NESTED LOOPS (cr=13537 pr=4404 pw=0 time=3.30)
| 486 ............NESTED LOOPS (cr=10873 pr=4240 pw=0 time=0.04)
| 486 .............NESTED LOOPS (cr=10385 pr=4240 pw=0 time=0.03)
| 486 ..............TABLE ACCESS BY INDEX ROWID RA_CUSTOMER_TRX_ALL (cr=9411 pr=4240 pw=0 time=0.02)
| 75253 ...............INDEX RANGE SCAN RA_CUSTOMER_TRX_N5 (cr=403 pr=285 pw=0 time=0.38)
| 486 ..............TABLE ACCESS BY INDEX ROWID HZ_CUST_ACCOUNTS (cr=974 pr=0 pw=0 time=0.01)
| 486 ...............INDEX UNIQUE SCAN HZ_CUST_ACCOUNTS_U1 (cr=488 pr=0 pw=0 time=0.01)
| 486 .............INDEX UNIQUE SCAN HZ_PARTIES_U1 (cr=488 pr=0 pw=0 time=0.01)
| 1027 ............TABLE ACCESS BY INDEX ROWID RA_CUSTOMER_TRX_LINES_ALL (cr=2664 pr=164 pw=0 time=1.95)
| 2063 .............INDEX RANGE SCAN RA_CUSTOMER_TRX_LINES_N2 (cr=1474 pr=28 pw=0 time=0.22)
| 1027 ...........TABLE ACCESS BY INDEX ROWID RA_CUST_TRX_LINE_GL_DIST_ALL (cr=4119 pr=67 pw=0 time=0.54)
| 1027 ............INDEX RANGE SCAN RA_CUST_TRX_LINE_GL_DIST_N1 (cr=3092 pr=31 pw=0 time=0.20)
| 3237 ..........TABLE ACCESS BY INDEX ROWID MTL_SYSTEM_ITEMS_B (cr=10640 pr=2668 pw=0 time=15.35)
| 3237 ...........INDEX RANGE SCAN MTL_SYSTEM_ITEMS_B_U1 (cr=2062 pr=40 pw=0 time=0.33)
| 3237 .........TABLE ACCESS BY INDEX ROWID OE_ORDER_LINES_ALL (cr=9804 pr=84 pw=0 time=0.77)
| 3237 ..........INDEX UNIQUE SCAN OE_ORDER_LINES_U1 (cr=6476 pr=47 pw=0 time=0.43)
| 3237 ........TABLE ACCESS BY INDEX ROWID MTL_PARAMETERS (cr=3239 pr=0 pw=0 time=0.04)
| 3237 .........INDEX UNIQUE SCAN MTL_PARAMETERS_U1 (cr=2 pr=0 pw=0 time=0.01)
| 741 .......TABLE ACCESS BY INDEX ROWID HR_ORGANIZATION_INFORMATION (cr=6476 pr=0 pw=0 time=0.10)
| 6474 ........INDEX RANGE SCAN HR_ORGANIZATION_INFORMATIO_FK2 (cr=3239 pr=0 pw=0 time=0.03)Please help.
Regards
Ashish| 254644500 ..NESTED LOOPS (cr=519939265 pr=34777 pw=0 time=3819.67)
| 254643758 ...NESTED LOOPS (cr=8921833 pr=29939 pw=0 time=1274.41)There is no way the optimizer should choose to process that many rows using nested loops.
Either the statistics are not up to date, the data values are skewed or you have some optimizer parameter set to none default to force index access.
Please post explain plan and optimizer* parameter settings. -
How does Index fragmentation and statistics affect the sql query performance
Hi,
How does Index fragmentation and statistics affect the sql query performance
Thanks
Shashikala
ShashikalaHow does Index fragmentation and statistics affect the sql query performance
Very simple answer, outdated statistics will lead optimizer to create bad plans which in turn will require more resources and this will impact performance. If index is fragmented ( mainly clustered index,holds true for Non clustred as well) time spent in finding
the value will be more as query would have to search fragmented index to look for data, additional spaces will increase search time.
Please mark this reply as the answer or vote as helpful, as appropriate, to make it useful for other readers
My TechNet Wiki Articles -
What SQL query I need for this?
I need to execute a SQL query but I don't know how.
To illustrate it, please take a look at some example data:
ARTICLEID SOLDON
1 2005-12-31
1 2005-11-31
1 2005-10-31
1 2005-09-31
1 2005-08-31
1 2005-07-31
1 2005-06-31
1 2005-05-31
1 2005-04-31
1 2005-03-31
1 2005-02-31
1 2005-01-31
1 2004-12-31
1 2004-11-31
2 2005-12-31
2 2005-11-31
2 2005-10-31
2 2005-09-31 This is a piece of the sales data for the articles (sales history).
Lets assume that today is the date 2005-12-31.
Two requirements for the query:
1. Get the sales data for the last 12 months.
2. Get only the sales data for articles where there is sales data since at least 6 months.
The result in my example should look like this:
ARTICLEID SOLDON
1 2005-12-31
1 2005-11-31
1 2005-10-31
1 2005-09-31
1 2005-08-31
1 2005-07-31
1 2005-06-31
1 2005-05-31
1 2005-04-31
1 2005-03-31
1 2005-02-31
1 2005-01-31 What is the SQL which I need to accomplish this query?To get all the information from the last 12 months
you will have to use date manipulation.
SELECT add_months(sysdate, -12) from
dual;This gives you the date 12 months ago.
So you will have to select your date between then and
the current date.If I do this I will get this data:
ARTICLEID SOLDON
1 2005-12-31
1 2005-11-31
1 2005-10-31
1 2005-09-31
1 2005-08-31
1 2005-07-31
1 2005-06-31
1 2005-05-31
1 2005-04-31
1 2005-03-31
1 2005-02-31
1 2005-01-31
2 2005-12-31
2 2005-11-31
2 2005-10-31
2 2005-09-31 But I want this data:
ARTICLEID SOLDON
1 2005-12-31
1 2005-11-31
1 2005-10-31
1 2005-09-31
1 2005-08-31
1 2005-07-31
1 2005-06-31
1 2005-05-31
1 2005-04-31
1 2005-03-31
1 2005-02-31
1 2005-01-31 I am no native English speaker. What didn't you understand in the two requirements?
Here are my two requirements for the query:
1. Get the sales data for the last 12 months.
2. But get ONLY the sales data for articles where there is sales data since AT LEAST 6 months.
The result can contain as many IDs as you want if the two requirements are met. Its not a trivial SQL statement for me. Please remember that the above data are only for illustration. They are just an example.
There should be a SQL statement for this.
Please tell me if you don't understand my problem. I will try to explain it in a better way if I can. -
Hi There,
We have a sql query that runs between 2 databases on the same machine, the sql takes about 2 mins and returns about 6400 rows. When the process started running we used to see results in about 13 secs, now it's taking almost 2 mins for the same data set. We have updated the stats (table and index) but to no use. I've been trying to get the execution plan to see if there is anything abnormal going on but as the core of the sql is done remotely, we haven't been able to get much out of it.
Here is the sql:
SELECT
--/*+ DRIVING_SITE(var) ALL_ROWS */
ventity_id, ar_action_performed, action_date,
'ventity_ar' ar_tab
FROM (SELECT var.ventity_id, var.ar_action_performed, var.action_date,
var.familyname_id, var.status, var.isprotected,
var.dateofbirth, var.gender, var.sindigits,
LAG (var.familyname_id) OVER (PARTITION BY var.ventity_id ORDER BY action_date)
lag_familyname_id,
LAG (var.status) OVER (PARTITION BY var.ventity_id ORDER BY action_date)
lag_status,
LAG (var.isprotected) OVER (PARTITION BY var.ventity_id ORDER BY action_date)
lag_isprotected,
LAG (var.dateofbirth) OVER (PARTITION BY var.ventity_id ORDER BY action_date)
lag_dateofbirth,
LAG (var.gender) OVER (PARTITION BY var.ventity_id ORDER BY action_date)
lag_gender,
LAG (var.sindigits) OVER (PARTITION BY var.ventity_id ORDER BY action_date)
lag_sindigits
FROM cpp_schema.ventity_ar@CdpP var,
-- reduce the set to ventity_id that had a change within the time frame,
-- and filter out RETRIEVEs as they do not signal change
(SELECT DISTINCT ventity_id
FROM cpp_schema.ventity_ar@CdpP
WHERE action_date BETWEEN '01-MAR-10' AND '10-APR-10'
AND ar_action_performed <> 'RTRV') m
WHERE var.action_date <= '10-APR-10'
AND var.ventity_id = m.ventity_id
AND var.ar_action_performed <> 'RTRV') mm
WHERE action_date BETWEEN '01-MAR-10' AND '10-APR-10'
-- most of the columns from the data table allow nulls
AND ( (NVL (familyname_id, 0) <> NVL (lag_familyname_id, 0))
OR (NVL (status, 'x') <> NVL (lag_status, 'x'))
OR (NVL (isprotected, 2) <> NVL (lag_isprotected, 2))
OR (NVL (dateofbirth, TO_DATE ('15000101', 'yyyymmdd')) <>
NVL (lag_dateofbirth, TO_DATE ('15000101', 'yyyymmdd'))
OR (NVL (gender, 'x') <> NVL (lag_gender, 'x'))
OR (NVL (sindigits, 'x') <> NVL (lag_sindigits, 'x'))
ORDER BY ventity_id, action_date DESC
6401 rows selected.
Elapsed: 00:01:47.03
Execution Plan
Plan hash value: 3953446945
| Id | Operation | Name | Rows | Bytes |TempSpc| Cost (%CPU)| Time | Inst |IN-OUT|
| 0 | SELECT STATEMENT | | 12M| 1575M| | 661K (1)| 02:12:22 | | |
| 1 | SORT ORDER BY | | 12M| 1575M| 2041M| 661K (1)| 02:12:22 | | |
|* 2 | VIEW | | 12M| 1575M| | 291K (2)| 00:58:13 | | |
| 3 | REMOTE | | | | | | | CCP01 | R->S |
2 - filter("action_date">='01_MAR-10' AND "action_date"<='10-APR-10' AND
(NVL("FAMILYNAME_id",0)<>NVL("LAG_FAMILYNAME_id",0) OR
NVL("STATUS",'x')<>NVL("LAG_STATUS",'x') OR NVL("ISPROTECTED",2)<>NVL("LAG_ISPROTECTED",2
) OR NVL("DATEOFBIRTH",TO_DATE(' 1500-01-01 00:00:00', 'syyyy-mm-dd
hh24:mi:ss'))<>NVL("LAG_DATEOFBIRTH",TO_DATE(' 1500-01-01 00:00:00', 'syyyy-mm-dd
hh24:mi:ss')) OR NVL("GENDER",'x')<>NVL("LAG_GENDER",'x') OR
NVL("SINDIGITS",'x')<>NVL("LAG_SINDIGITS",'x')))
Remote SQL Information (identified by operation id):
3 - EXPLAIN PLAN SET STATEMENT_ID='PLUS4294967295' INTO PLAN_TABLE@! FOR SELECT
"A2"."ventity_id","A2"."AR_ACTION_PERFORMED","A2"."action_date","A2"."FAMILYNAME_id","A2"
."STATUS","A2"."ISPROTECTED","A2"."DATEOFBIRTH","A2"."GENDER","A2"."SINDIGITS",DECODE(COU
NT(*) OVER ( PARTITION BY "A2"."ventity_id" ORDER BY "A2"."action_date" ROWS BETWEEN 1
PRECEDING AND 1 PRECEDING ),1,FIRST_VALUE("A2"."FAMILYNAME_id") OVER ( PARTITION BY
"A2"."ventity_id" ORDER BY "A2"."action_date" ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING
),NULL),DECODE(COUNT(*) OVER ( PARTITION BY "A2"."ventity_id" ORDER BY
"A2"."action_date" ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING ),1,FIRST_VALUE("A2"."STATUS")
OVER ( PARTITION BY "A2"."ventity_id" ORDER BY "A2"."action_date" ROWS BETWEEN 1
PRECEDING AND 1 PRECEDING ),NULL),DECODE(COUNT(*) OVER ( PARTITION BY
"A2"."ventity_id" ORDER BY "A2"."action_date" ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING
),1,FIRST_VALUE("A2"."ISPROTECTED") OVER ( PARTITION BY "A2"."ventity_id" ORDER BY
"A2"."action_date" ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING ),NULL),DECODE(COUNT(*) OVER (
PARTITION BY "A2"."ventity_id" ORDER BY "A2"."action_date" ROWS BETWEEN 1 PRECEDING
AND 1 PRECEDING ),1,FIRST_VALUE("A2"."DATEOFBIRTH") OVER ( PARTITION BY
"A2"."ventity_id" ORDER BY "A2"."action_date" ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING
),NULL),DECODE(COUNT(*) OVER ( PARTITION BY "A2"."ventity_id" ORDER BY
"A2"."action_date" ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING ),1,FIRST_VALUE("A2"."GENDER")
OVER ( PARTITION BY "A2"."ventity_id" ORDER BY "A2"."action_date" ROWS BETWEEN 1
PRECEDING AND 1 PRECEDING ),NULL),DECODE(COUNT(*) OVER ( PARTITION BY
"A2"."ventity_id" ORDER BY "A2"."action_date" ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING
),1,FIRST_VALUE("A2"."SINDIGITS") OVER ( PARTITION BY "A2"."ventity_id" ORDER BY
"A2"."action_date" ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING ),NULL) FROM
"CPP_SCHEMA"."ventity_AR" "A2", (SELECT DISTINCT "A3"."ventity_id"
"ventity_id" FROM "CPP_SCHEMA"."ventity_AR" "A3" WHERE
"A3"."action_date">='01_MAR-10' AND "A3"."action_date"<='10-APR-10' AND
"A3"."AR_ACTION_PERFORMED"<>'RETRIEVE' AND TO_DATE('01_MAR-10')<=TO_DATE('10-APR-10'))
"A1" WHERE "A2"."action_date"<='10-APR-10' AND "A2"."ventity_id"="A1"."ventity_id"
AND "A2"."AR_ACTION_PERFORMED"<>'RETRIEVE' (accessing 'EBCP01.EBC.GOV.BC.CA' )Your advise and/or help is highly appreciated.
THanks
Edited by: rsar001 on Apr 20, 2010 6:57 AMMaybe I'm missing something but this subquery seems inefficient:
SELECT var.ventity_id, var.ar_action_performed, var.action_date,
var.familyname_id, var.status, var.isprotected,
var.dateofbirth, var.gender, var.sindigits,
LAG (var.familyname_id) OVER (PARTITION BY var.ventity_id ORDER BY action_date)
lag_familyname_id,
LAG (var.status) OVER (PARTITION BY var.ventity_id ORDER BY action_date)
lag_status,
LAG (var.isprotected) OVER (PARTITION BY var.ventity_id ORDER BY action_date)
lag_isprotected,
LAG (var.dateofbirth) OVER (PARTITION BY var.ventity_id ORDER BY action_date)
lag_dateofbirth,
LAG (var.gender) OVER (PARTITION BY var.ventity_id ORDER BY action_date)
lag_gender,
LAG (var.sindigits) OVER (PARTITION BY var.ventity_id ORDER BY action_date)
lag_sindigits
FROM cpp_schema.ventity_ar@CdpP var,
-- reduce the set to ventity_id that had a change within the time frame,
-- and filter out RETRIEVEs as they do not signal change
(SELECT DISTINCT ventity_id
FROM cpp_schema.ventity_ar@CdpP
WHERE action_date BETWEEN '01-MAR-10' AND '10-APR-10'
AND ar_action_performed <> 'RTRV') m
WHERE var.action_date <= '10-APR-10'
AND var.ventity_id = m.ventity_id
AND var.ar_action_performed != 'RTRV'I don't think accessing the VENTITY_AR table twice is helping you here. The comments looks like you want to restrict the set of VENTITY_IDs but if you look at the plan it is not happening. The plan is reading them from the index and joining against the full VENTITY_AR table anyways. I recommend you consolidate it into something like this:
SELECT var.ventity_id
, var.ar_action_performed
, var.action_date
, var.familyname_id
, var.status
, var.isprotected
, var.dateofbirth
, var.gender
, var.sindigits
, LAG (var.familyname_id) OVER (PARTITION BY var.ventity_id ORDER BY action_date) AS lag_familyname_id
, LAG (var.status) OVER (PARTITION BY var.ventity_id ORDER BY action_date) AS lag_status
, LAG (var.isprotected) OVER (PARTITION BY var.ventity_id ORDER BY action_date) AS lag_isprotected
, LAG (var.dateofbirth) OVER (PARTITION BY var.ventity_id ORDER BY action_date) AS lag_dateofbirth
, LAG (var.gender) OVER (PARTITION BY var.ventity_id ORDER BY action_date) AS lag_gender
, LAG (var.sindigits) OVER (PARTITION BY var.ventity_id ORDER BY action_date) AS lag_sindigits
FROM cpp_schema.ventity_ar@CdpP var
WHERE var.action_date BETWEEN TO_DATE('01-MAR-10','DD-MON-YY') AND TO_DATE('10-APR-10','DD-MON-YY')
AND var.ar_action_performed != 'RTRV'It may then be useful to put an index on (ACTION_DATE,AR_ACTION_PERFORMED) if one doesn't already exist.
*::EDIT::*
I noticed the large amount of NVL calls in your outer query. These NVLs could possibly be eliminated if you use the optional second and third arguments of the LAG analytical function. I'm not sure if this would improve performance but it may make the query more readable and maintainable.
HTH!
Edited by: Centinul on Apr 20, 2010 10:50 AM -
How to compare same SQL query performance in different DB servers.
We have Production and Validation Environment of Oracle11g DB on two Solaris OSs.
H/W and DB,etc configurations of two Oracle DBs are almost same in PROD and VAL.
But we detected large SQL query performace difference in PROD DB and VAL DB in same SQL query.
I would like to find and solve the cause of this situation.
How could I do that ?
I plan to compare SQL execution plan in PROD and VAL DB and index fragmentations.
Before that I thought I need to keep same condition of DB statistics information in PROD and VAL DB.
So, I plan to execute alter system FLUSH BUFFER_CACHE;
But I am worring about bad effects of alter system FLUSH BUFFER_CACHE; to end users
If we did alter system FLUSH BUFFER_CACHE; and got execution plan of that SQL query in the time end users do not use that system ,
there is not large bad effect to end users after those operations?
Could you please let me know the recomendation to compare SQL query performace ?Thank you.
I got AWR report for only VAL DB server but it looks strange.
Is there any thing wrong in DB or how to get AWR report ?
Host Name
Platform
CPUs
Cores
Sockets
Memory (GB)
xxxx
Solaris[tm] OE (64-bit)
.00
Snap Id
Snap Time
Sessions
Cursors/Session
Begin Snap:
xxxx
13-Apr-15 04:00:04
End Snap:
xxxx
14-Apr-15 04:00:22
Elapsed:
1,440.30 (mins)
DB Time:
0.00 (mins)
Report Summary
Cache Sizes
Begin
End
Buffer Cache:
M
M
Std Block Size:
K
Shared Pool Size:
0M
0M
Log Buffer:
K
Load Profile
Per Second
Per Transaction
Per Exec
Per Call
DB Time(s):
0.0
0.0
0.00
0.00
DB CPU(s):
0.0
0.0
0.00
0.00
Redo size:
Logical reads:
0.0
1.0
Block changes:
0.0
1.0
Physical reads:
0.0
1.0
Physical writes:
0.0
1.0
User calls:
0.0
1.0
Parses:
0.0
1.0
Hard parses:
W/A MB processed:
16.7
1,442,472.0
Logons:
Executes:
0.0
1.0
Rollbacks:
Transactions:
0.0
Instance Efficiency Percentages (Target 100%)
Buffer Nowait %:
Redo NoWait %:
Buffer Hit %:
In-memory Sort %:
Library Hit %:
96.69
Soft Parse %:
Execute to Parse %:
0.00
Latch Hit %:
Parse CPU to Parse Elapsd %:
% Non-Parse CPU:
Shared Pool Statistics
Begin
End
Memory Usage %:
% SQL with executions>1:
34.82
48.31
% Memory for SQL w/exec>1:
63.66
73.05
Top 5 Timed Foreground Events
Event
Waits
Time(s)
Avg wait (ms)
% DB time
Wait Class
DB CPU
0
100.00
Host CPU (CPUs: Cores: Sockets: )
Load Average Begin
Load Average End
%User
%System
%WIO
%Idle
Instance CPU
%Total CPU
%Busy CPU
%DB time waiting for CPU (Resource Manager)
Memory Statistics
Begin
End
Host Mem (MB):
SGA use (MB):
46,336.0
46,336.0
PGA use (MB):
713.6
662.6
% Host Mem used for SGA+PGA:
Time Model Statistics
No data exists for this section of the report.
Back to Wait Events Statistics
Back to Top
Operating System Statistics
No data exists for this section of the report.
Back to Wait Events Statistics
Back to Top
Operating System Statistics - Detail
No data exists for this section of the report.
Back to Wait Events Statistics
Back to Top
Foreground Wait Class
s - second, ms - millisecond - 1000th of a second
ordered by wait time desc, waits desc
%Timeouts: value of 0 indicates value was < .5%. Value of null is truly 0
Captured Time accounts for % of Total DB time .00 (s)
Total FG Wait Time: (s) DB CPU time: .00 (s)
Wait Class
Waits
%Time -outs
Total Wait Time (s)
Avg wait (ms)
%DB time
DB CPU
0
100.00
Back to Wait Events Statistics
Back to Top
Foreground Wait Events
No data exists for this section of the report.
Back to Wait Events Statistics
Back to Top
Background Wait Events
ordered by wait time desc, waits desc (idle events last)
Only events with Total Wait Time (s) >= .001 are shown
%Timeouts: value of 0 indicates value was < .5%. Value of null is truly 0
Event
Waits
%Time -outs
Total Wait Time (s)
Avg wait (ms)
Waits /txn
% bg time
log file parallel write
527,034
0
2,209
4
527,034.00
db file parallel write
381,966
0
249
1
381,966.00
os thread startup
2,650
0
151
57
2,650.00
latch: messages
125,526
0
89
1
125,526.00
control file sequential read
148,662
0
54
0
148,662.00
control file parallel write
41,935
0
28
1
41,935.00
Log archive I/O
5,070
0
14
3
5,070.00
Disk file operations I/O
8,091
0
10
1
8,091.00
log file sequential read
3,024
0
6
2
3,024.00
db file sequential read
1,299
0
2
2
1,299.00
latch: shared pool
722
0
1
1
722.00
enq: CF - contention
4
0
1
208
4.00
reliable message
1,316
0
1
1
1,316.00
log file sync
71
0
1
9
71.00
enq: CR - block range reuse ckpt
36
0
0
13
36.00
enq: JS - queue lock
459
0
0
1
459.00
log file single write
414
0
0
1
414.00
enq: PR - contention
5
0
0
57
5.00
asynch descriptor resize
67,076
100
0
0
67,076.00
LGWR wait for redo copy
5,184
0
0
0
5,184.00
rdbms ipc reply
1,234
0
0
0
1,234.00
ADR block file read
384
0
0
0
384.00
SQL*Net message to client
189,490
0
0
0
189,490.00
latch free
559
0
0
0
559.00
db file scattered read
17
0
0
6
17.00
resmgr:internal state change
1
100
0
100
1.00
direct path read
301
0
0
0
301.00
enq: RO - fast object reuse
35
0
0
2
35.00
direct path write
122
0
0
1
122.00
latch: cache buffers chains
260
0
0
0
260.00
db file parallel read
1
0
0
41
1.00
ADR file lock
144
0
0
0
144.00
latch: redo writing
55
0
0
1
55.00
ADR block file write
120
0
0
0
120.00
wait list latch free
2
0
0
10
2.00
latch: cache buffers lru chain
44
0
0
0
44.00
buffer busy waits
3
0
0
2
3.00
latch: call allocation
57
0
0
0
57.00
SQL*Net more data to client
55
0
0
0
55.00
ARCH wait for archivelog lock
78
0
0
0
78.00
rdbms ipc message
3,157,653
40
4,058,370
1285
3,157,653.00
Streams AQ: qmn slave idle wait
11,826
0
172,828
14614
11,826.00
DIAG idle wait
170,978
100
172,681
1010
170,978.00
dispatcher timer
1,440
100
86,417
60012
1,440.00
Streams AQ: qmn coordinator idle wait
6,479
48
86,413
13337
6,479.00
shared server idle wait
2,879
100
86,401
30011
2,879.00
Space Manager: slave idle wait
17,258
100
86,324
5002
17,258.00
pmon timer
46,489
62
86,252
1855
46,489.00
smon timer
361
66
86,145
238628
361.00
VKRM Idle
1
0
14,401
14400820
1.00
SQL*Net message from client
253,909
0
419
2
253,909.00
class slave wait
379
0
0
0
379.00
Back to Wait Events Statistics
Back to Top
Wait Event Histogram
No data exists for this section of the report.
Back to Wait Events Statistics
Back to Top
Wait Event Histogram Detail (64 msec to 2 sec)
No data exists for this section of the report.
Back to Wait Events Statistics
Back to Top
Wait Event Histogram Detail (4 sec to 2 min)
No data exists for this section of the report.
Back to Wait Events Statistics
Back to Top
Wait Event Histogram Detail (4 min to 1 hr)
No data exists for this section of the report.
Back to Wait Events Statistics
Back to Top
Service Statistics
No data exists for this section of the report.
Back to Wait Events Statistics
Back to Top
Service Wait Class Stats
No data exists for this section of the report.
Back to Wait Events Statistics
Back to Top
SQL Statistics
SQL ordered by Elapsed Time
SQL ordered by CPU Time
SQL ordered by User I/O Wait Time
SQL ordered by Gets
SQL ordered by Reads
SQL ordered by Physical Reads (UnOptimized)
SQL ordered by Executions
SQL ordered by Parse Calls
SQL ordered by Sharable Memory
SQL ordered by Version Count
Complete List of SQL Text
Back to Top
SQL ordered by Elapsed Time
No data exists for this section of the report.
Back to SQL Statistics
Back to Top
SQL ordered by CPU Time
No data exists for this section of the report.
Back to SQL Statistics
Back to Top
SQL ordered by User I/O Wait Time
No data exists for this section of the report.
Back to SQL Statistics
Back to Top
SQL ordered by Gets
No data exists for this section of the report.
Back to SQL Statistics
Back to Top
SQL ordered by Reads
No data exists for this section of the report.
Back to SQL Statistics
Back to Top
SQL ordered by Physical Reads (UnOptimized)
No data exists for this section of the report.
Back to SQL Statistics
Back to Top
SQL ordered by Executions
No data exists for this section of the report.
Back to SQL Statistics
Back to Top
SQL ordered by Parse Calls
No data exists for this section of the report.
Back to SQL Statistics
Back to Top
SQL ordered by Sharable Memory
No data exists for this section of the report.
Back to SQL Statistics
Back to Top
SQL ordered by Version Count
No data exists for this section of the report.
Back to SQL Statistics
Back to Top
Complete List of SQL Text
No data exists for this section of the report.
Back to SQL Statistics
Back to Top
Instance Activity Statistics
Instance Activity Stats
Instance Activity Stats - Absolute Values
Instance Activity Stats - Thread Activity
Back to Top
Instance Activity Stats
No data exists for this section of the report.
Back to Instance Activity Statistics
Back to Top
Instance Activity Stats - Absolute Values
No data exists for this section of the report.
Back to Instance Activity Statistics
Back to Top
Instance Activity Stats - Thread Activity
Statistics identified by '(derived)' come from sources other than SYSSTAT
Statistic
Total
per Hour
log switches (derived)
69
2.87
Back to Instance Activity Statistics
Back to Top
IO Stats
IOStat by Function summary
IOStat by Filetype summary
IOStat by Function/Filetype summary
Tablespace IO Stats
File IO Stats
Back to Top
IOStat by Function summary
'Data' columns suffixed with M,G,T,P are in multiples of 1024 other columns suffixed with K,M,G,T,P are in multiples of 1000
ordered by (Data Read + Write) desc
Function Name
Reads: Data
Reqs per sec
Data per sec
Writes: Data
Reqs per sec
Data per sec
Waits: Count
Avg Tm(ms)
Others
28.8G
20.55
.340727
16.7G
2.65
.198442
1803K
0.01
Direct Reads
43.6G
57.09
.517021
411M
0.59
.004755
0
LGWR
19M
0.02
.000219
41.9G
21.87
.496493
2760
0.08
Direct Writes
16M
0.00
.000185
8.9G
1.77
.105927
0
DBWR
0M
0.00
0M
6.7G
4.42
.079670
0
Buffer Cache Reads
3.1G
3.67
.037318
0M
0.00
0M
260.1K
3.96
TOTAL:
75.6G
81.33
.895473
74.7G
31.31
.885290
2065.8K
0.51
Back to IO Stats
Back to Top
IOStat by Filetype summary
'Data' columns suffixed with M,G,T,P are in multiples of 1024 other columns suffixed with K,M,G,T,P are in multiples of 1000
Small Read and Large Read are average service times, in milliseconds
Ordered by (Data Read + Write) desc
Filetype Name
Reads: Data
Reqs per sec
Data per sec
Writes: Data
Reqs per sec
Data per sec
Small Read
Large Read
Data File
53.2G
78.33
.630701
8.9G
7.04
.105197
0.37
21.51
Log File
13.9G
0.18
.164213
41.9G
21.85
.496123
0.02
2.93
Archive Log
0M
0.00
0M
13.9G
0.16
.164213
Temp File
5.6G
0.67
.066213
8.1G
0.80
.096496
5.33
3713.27
Control File
2.9G
2.16
.034333
2G
1.46
.023247
0.05
19.98 -
Speed up SQL Query performance
Hi,
I am having a SQL query which has got some inner joins between tables.
In this query i will be selecting values from set of values obtained by going through all rows in a table.
I am using a inner join between two tables to achive this purpose.
But, as the table which i go through all rows is extremely big it takes lot of time to go through all rows and the query slows down.
Is there any other way by which i can speed up query.This is the out put of my test plan.
Please suggest which one needs to be improved.
PLAN_TABLE_OUTPUT
Plan hash value: 3453987661
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
| 0 | SELECT STATEMENT | | 3 | 1002 | 3920 (1)| 00:00:48 |
| 1 | SORT ORDER BY | | 3 | 1002 | 3920 (1)| 00:00:48 |
|* 2 | TABLE ACCESS BY INDEX ROWID | AS_EVENT_CHR_DATA | 1 | 17 | 4 (0)| 00:00:01 |
| 3 | NESTED LOOPS | | 3 | 1002 | 3919 (1)| 00:00:48 |
|* 4 | HASH JOIN | | 3 | 951 | 3907 (1)| 00:00:47 |
|* 5 | TABLE ACCESS FULL | EV_CHR_DATA_TYPE | 1 | 46 | 2 (0)| 00:00:01 |
| 6 | TABLE ACCESS BY INDEX ROWID | AS_EVENT_CHR_DATA | 702 | 50544 | 3883 (1)| 00:00:47 |
| 7 | NESTED LOOPS | | 348 | 94308 | 3904 (1)| 00:00:47 |
| 8 | NESTED LOOPS | | 1 | 199 | 21 (5)| 00:00:01 |
| 9 | NESTED LOOPS | | 1 | 174 | 20 (5)| 00:00:01 |
|* 10 | HASH JOIN | | 1 | 127 | 18 (6)| 00:00:01 |
| 11 | NESTED LOOPS | | 1 | 95 | 13 (0)| 00:00:01 |
| 12 | NESTED LOOPS | | 1 | 60 | 12 (0)| 00:00:01 |
| 13 | NESTED LOOPS | | 1 | 33 | 10 (0)| 00:00:01 |
| 14 | TABLE ACCESS BY INDEX ROWID| ASSET | 1 | 21 | 2 (0)| 00:00:01 |
|* 15 | INDEX UNIQUE SCAN | SERIAL_NUMBER_K3 | 1 | | 1 (0)| 00:00:01 |
|* 16 | INDEX FAST FULL SCAN | SYS_C0053318 | 1 | 12 | 8 (0)| 00:00:01 |
| 17 | TABLE ACCESS BY INDEX ROWID | SEGMENT_CHILD | 1 | 27 | 2 (0)| 00:00:01 |
|* 18 | INDEX RANGE SCAN | SYS_C0053319 | 12 | | 1 (0)| 00:00:01 |
| 19 | TABLE ACCESS BY INDEX ROWID | SEGMENT | 1 | 35 | 1 (0)| 00:00:01 |
|* 20 | INDEX UNIQUE SCAN | SYS_C0053318 | 1 | | 0 (0)| 00:00:01 |
|* 21 | TABLE ACCESS FULL | SEGMENT_TYPE | 1 | 32 | 4 (0)| 00:00:01 |
| 22 | TABLE ACCESS BY INDEX ROWID | ASSET_ON_SEGMENT | 1 | 47 | 2 (0)| 00:00:01 |
|* 23 | INDEX RANGE SCAN | ASSET_ON_SEGME_UK8115533871153 | 1 | | 1 (0)| 00:00:01 |
| 24 | TABLE ACCESS BY INDEX ROWID | ASSET | 1 | 25 | 1 (0)| 00:00:01 |
|* 25 | INDEX UNIQUE SCAN | SYS_C0053240 | 1 | | 0 (0)| 00:00:01 |
|* 26 | INDEX RANGE SCAN | AS_EV_CHR_DATA_ASSETPK | 4673 | | 28 (4)| 00:00:01 |
|* 27 | INDEX RANGE SCAN | SYS_C0053249 | 5 | | 2 (0)| 00:00:01 |
Predicate Information (identified by operation id):
2 - filter("PARAMETRIC_TAG_NAME"."DATA_VALUE"='EngineOilConsumption')
4 - access("AS_EVENT_CHR_DATA"."EC_DB_SITE"="EV_CHR_DATA_TYPE"."EC_DB_SITE" AND
"AS_EVENT_CHR_DATA"."EC_DB_ID"="EV_CHR_DATA_TYPE"."EC_DB_ID" AND
"AS_EVENT_CHR_DATA"."EC_TYPE_CODE"="EV_CHR_DATA_TYPE"."EC_TYPE_CODE")
5 - filter("EV_CHR_DATA_TYPE"."NAME"='servicing ptric time unit')
10 - access("OILSEG"."SG_TYPE_CODE"="SEGMENT_TYPE"."SG_TYPE_CODE")
15 - access("ASSET"."SERIAL_NUMBER"='30870')
16 - filter("ASSET"."ASSET_ID"="SEGMENT"."SEGMENT_ID")
18 - access("SEGMENT"."SEGMENT_SITE"="SEGMENT_CHILD"."SEGMENT_SITE" AND
"SEGMENT"."SEGMENT_ID"="SEGMENT_CHILD"."SEGMENT_ID")
20 - access("SEGMENT_CHILD"."CHILD_SG_SITE"="OILSEG"."SEGMENT_SITE" AND
"SEGMENT_CHILD"."CHILD_SG_ID"="OILSEG"."SEGMENT_ID")
21 - filter("SEGMENT_TYPE"."NAME"='Aircraft Equipment Engine Holder')
23 - access("OILSEG"."SEGMENT_ID"="ASSET_ON_SEGMENT"."SEGMENT_ID")
25 - access("ASSET_ON_SEGMENT"."ASSET_ORG_SITE"="OILASSET"."ASSET_ORG_SITE" AND
"ASSET_ON_SEGMENT"."ASSET_ID"="OILASSET"."ASSET_ID")
26 - access("ASSET_ON_SEGMENT"."ASSET_ORG_SITE"="AS_EVENT_CHR_DATA"."ASSET_ORG_SITE" AND
"ASSET_ON_SEGMENT"."ASSET_ID"="AS_EVENT_CHR_DATA"."ASSET_ID")
27 - access("AS_EVENT_CHR_DATA"."AS_EV_ID"="PARAMETRIC_TAG_NAME"."AS_EV_ID") -
T-SQL query performance (CLR func + webservice)
Hi guys
I have CLR function which accepts address as a parameter, calls geocoding webservice and returns some information (coordinates etc.)
I run SQL query
SELECT *FROM T CROSS APPLY CLR_Func(T.Address)F
Table contains 8 million records and obviously query runs very slow.
Do you know any nice way to improve performance in this situation?
Thank you,
MaxNo WHERE condition? SQL Server will call the function 8 million times ....
Best Regards,Uri Dimant SQL Server MVP,
http://sqlblog.com/blogs/uri_dimant/
MS SQL optimization: MS SQL Development and Optimization
MS SQL Consulting:
Large scale of database and data cleansing
Remote DBA Services:
Improves MS SQL Database Performance
SQL Server Integration Services:
Business Intelligence -
SQL query performance question
So I had this long query that looked like this:
SELECT a.BEGIN_DATE, a.END_DATE, a.DEAL_KEY, (select name from ideal dd where a.deal_key = dd.deal_key) DEALNAME, a.deal_term_key
FROM
ideal d, ideal_term a,( select deal_key, deal_term_key, max(createdOn) maxdate from Ideal_term B
where createdOn <= '03-OCT-12 10.03.00 AM' group by deal_key, deal_term_key ) B
WHERE a.begin_date <= '20-MAR-09 01.01.00 AM'
* and a.end_date >= '19-MAR-09 01.00.00 AM'*
* and A.deal_key = b.deal_key*
* and A.deal_term_key = b.deal_term_key*
* and a.createdOn = b.maxdate*
* and d.deal_key = a.deal_key*
* and d.name like 'MVPP1 B'*
order by
* a.begin_date, a.deal_key, a.deal_term_key;*
This performed very poorly for a record in one of the tables that has 43,000+ revisions. It took about 1 minute and 40 seconds. I asked the database guy at my company for help with it and he re-wrote it like so:
SELECT a.BEGIN_DATE, a.END_DATE, a.DEAL_KEY, (select name from ideal dd where a.deal_key = dd.deal_key) DEALNAME, a.deal_term_key
FROM ideal d
INNER JOIN (SELECT deal_key,
deal_term_key,
MAX(createdOn) maxdate
FROM Ideal_term B2
WHERE '03-OCT-12 10.03.00 AM' >= createdOn
GROUP BY deal_key, deal_term_key) B1
ON d.deal_key = B1.deal_key
INNER JOIN ideal_term a
ON B1.deal_key = A.deal_key
AND B1.deal_term_key = A.deal_term_key
AND B1.maxdate = a.createdOn
AND d.deal_key = a.deal_key + 0
WHERE a.begin_date <= '20-MAR-09 01.01.00 AM'
AND a.end_date >= '19-MAR-09 01.00.00 AM'
AND d.name LIKE 'MVPP1 B'
ORDER BY a.begin_date, a.deal_key, a.deal_term_key
this works much better, it only takes 0.13 seconds. I've bee trying to figure out why exaclty his version performs so much better. His only epxlanation was that the "+ 0" in the WHERE clause prevented Oracle from using an index for that column which created a bad plan initially.
I think there has to be more to it than that though. Can someone give me a detailed explanation of why the second version of the query performed so much faster.
Thanks.
Edited by: su**** on Oct 10, 2012 1:31 PMI used Autotrace in SQL developer. Is that sufficient? Here is the Autotrace and Explain for the slow query:
and for the fast query:
I said that I thought there was more to it because when my team members and I looked at the re-worked query the database guy sent us, our initial thoughts were that in the slow query some of the tables didn't have joins and because of that the query formed a Cartesian product and this resulted in a huge 43,000+ rows matrix.
In his version all tables had joins properly defined and in addition he had that +0 which told it to ignore the index for the attribute deal_key of table ideal_term. I spoke with the database guy today and he confirmed our theory. -
I'm having trouble with an SQL query. I've created a simple logon page wherein a user will enter their user name and password. The program will look in an Access database for the user name, sort it by Date/Time modified, and check to see if their password matches the most recent password. Unfortunately, the query returns no results. I'm absolutely certain that I'm doing the query correctly (I've imported it directly from my old VB6 code). Something simple is eluding me. Any help would be appreciated.
private void LogOn() {
//make sure that the user name/password is valid, then load the main menu
try {
//open the database connection
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:LawOffice2000", "", "");
Statement select = con.createStatement();
String strTemp = "Select * From EMPLOYEES Where INITIALS = '" + txtUserName.getText() + "' Order By DATE Desc, TIME Desc";
ResultSet result = select.executeQuery(strTemp);
while(result.next()) {
if (txtPassword.getPassword().toString() == result.getString("Password")) {
MenuMain.main();
else {
System.out.println("Password Bad");
System.out.println(txtUserName.getText());
System.out.println(result.getString("Password"));
break; //exit loop
//close the connection
con.close(); }
catch (Exception e) {
System.out.println("LawOfficeSuite_LogOn: " + e);
return; }
}The problem is here: "txtPassword.getPassword().toString() == result.getString("Password"))"
Don't confuse String's equals() method with the equality operator '=='. The == operator checks that two references refer to the same object. If you want to compare the contents of Strings (whether two strings contain the same characters), use equals(), e.g. if (str1.equals(str2))...
Example:String s1 = "foo";
String s2 = new String("foo");
System.out.println("s1 == s2: " + (s1 == s2)); // false
System.out.println("s1.equals(s2): " + (s1.equals(s2))); // trueFor more information, check out Comparison operators: equals() versus == -
Sql query ..need idea to write complex query
Hi there,
I have assigned the task to write a sql query to get the output as the below stored proc does.
In the proc conditions are given with IF statements. I really dont know how to give all the conditions for the period in a single sql query as I'm not much used to sql quries.
Is anyone could help me?
Any suggestions pls . writing complicated query is nightmare. no idea . if possible help me...
create or replace PROCEDURE vpp_station_summary_report (
in_user_id IN VARCHAR2,
in_report_id IN NUMBER,
in_time_from IN vppstation.avi_status_history.status_eff_date%TYPE,
in_time_to IN vppstation.avi_status_history.status_eff_date%TYPE,
result OUT SYS_REFCURSOR)
AS
CURSOR station_loop IS
SELECT ash.station_id,
ash.avi_id,
ash.state_id,
ash.state_eff_date
FROM vppstation.avi_state_history ash
JOIN vpproadside.vpp_report_stations
ON vpp_report_stations.station_id = ash.station_id
AND vpp_report_stations.vpp_report_seq_number = in_report_id
WHERE ash.state_eff_date BETWEEN in_time_from AND in_time_to
ORDER BY ash.station_id,
ash.avi_id,
ash.state_eff_date,
ash.ash_id;
-- cursor to find the 'entry state' i.e. the state the AVI was in AT the time of
-- in_time_from
CURSOR entry_state (
state_station_id vppstation.avi_state_history.station_id%TYPE,
state_avi_id vppstation.avi_state_history.avi_id%TYPE,
state_state_date vppstation.avi_state_history.state_eff_date%TYPE
IS
SELECT ash.state_id
FROM vppstation.avi_state_history ash
WHERE ash.station_id = state_station_id
AND ash.avi_id = state_avi_id
AND ash.state_eff_date < state_state_date
ORDER BY ash.state_eff_date DESC,
ash.ash_id DESC;
current_station_id vppstation.avi_state_history.station_id%TYPE;
current_avi_id vppstation.avi_state_history.avi_id%TYPE;
current_state_id vppstation.avi_state_history.state_id%TYPE;
current_state_eff_date vppstation.avi_state_history.state_eff_date%TYPE;
period_length NUMBER;
next_station_id vppstation.avi_state_history.station_id%TYPE;
next_avi_id vppstation.avi_state_history.avi_id%TYPE;
next_state_id vppstation.avi_state_history.state_id%TYPE;
next_state_eff_date vppstation.avi_state_history.state_eff_date%TYPE;
station_open_total NUMBER;
station_closed_total NUMBER;
station_all_report_total NUMBER;
current_station_name vpproadside.vpp_station_summary.station_name%TYPE;
state_open vppstation.avi_control_state_code.state_id%TYPE;
state_closed vppstation.avi_control_state_code.state_id%TYPE;
state_all_report vppstation.avi_control_state_code.state_id%TYPE;
BEGIN
SELECT state_id
INTO state_open
FROM vppstation.avi_control_state_code
WHERE state_type = 'E'
AND state_active_ind = 'A';
SELECT state_id
INTO state_closed
FROM vppstation.avi_control_state_code
WHERE state_type = 'D'
AND state_active_ind = 'A';
SELECT state_id
INTO state_all_report
FROM vppstation.avi_control_state_code
WHERE state_type = 'S'
AND state_active_ind = 'A';
current_station_id := -1;
current_avi_id := -1;
current_state_id := state_closed;
current_state_eff_date := in_time_from;
station_open_total := 0.0;
station_closed_total := 0.0;
station_all_report_total := 0.0;
-- for starters - ensure that there is report data for all requested stations...
INSERT INTO vpproadside.vpp_station_summary
vpp_report_seq_number,
station_id,
station_name,
ln_number,
lane_name,
station_open,
station_close,
station_all_report,
station_total
SELECT in_report_id,
vrs.station_id,
si.station_name,
l.ln_number,
l.lane_name,
0.0,
0.0,
0.0,
0.0
FROM vpproadside.vpp_report_stations vrs
LEFT OUTER JOIN vpproadside.stations_installed si
ON si.station_id = vrs.station_id
LEFT OUTER JOIN vppstation.lane_name l
ON l.station_id = vrs.station_id
WHERE vrs.vpp_report_seq_number = in_report_id;
-- loop over state history and update information for all stations found
OPEN station_loop;
LOOP
FETCH station_loop
INTO
next_station_id,
next_avi_id,
next_state_id,
next_state_eff_date;
IF station_loop%NOTFOUND THEN
next_station_id := -1;
next_avi_id := -1;
END IF;
-- if station/avi has changed take the end of the report period
IF (next_station_id <> current_station_id)
OR (next_avi_id <> current_avi_id)
THEN
period_length := in_time_to - current_state_eff_date;
ELSE
-- otherwise the start of the next period marks the end of the current period
period_length := next_state_eff_date - current_state_eff_date;
END IF;
-- if we have a real station id then do some work...
IF (current_station_id <> -1) THEN
-- determine which category the period fits to and apply calculation
IF current_state_id = state_open THEN
station_open_total := station_open_total + period_length - 1;
ELSIF current_state_id = state_closed THEN
station_closed_total := station_closed_total + period_length - 1;
ELSIF current_state_id = state_all_report THEN
station_all_report_total := station_all_report_total + period_length - 1;
ELSE
RAISE_APPLICATION_ERROR(-20111, 'Error: found unknown state code on avi_state_history - ' || current_state_id );
END IF;
-- if the station/avi has changed then commit changes to db
IF (next_station_id <> current_station_id)
OR (next_avi_id <> current_avi_id)
THEN
UPDATE vpproadside.vpp_station_summary
SET
station_open = station_open_total,
station_close = station_closed_total,
station_all_report = station_all_report_total
WHERE vpp_report_seq_number = in_report_id
AND station_id = current_station_id
AND ln_number = current_avi_id;
-- reset counts
station_open_total := 0.0;
station_closed_total := 0.0;
station_all_report_total := 0.0;
END IF;
END IF;
-- if we got past the last record then stop processing
EXIT WHEN station_loop%NOTFOUND;
-- if the station/avi is changing, get the state that was 'current' at in_time_from
IF (next_station_id <> current_station_id)
OR (next_avi_id <> current_avi_id)
THEN
current_state_eff_date := in_time_from;
OPEN entry_state (
next_station_id,
next_avi_id,
in_time_from
FETCH entry_state
INTO current_state_id;
IF entry_state%NOTFOUND THEN
current_state_id := state_closed;
END IF;
CLOSE entry_state;
period_length := next_state_eff_date - current_state_eff_date;
IF current_state_id = state_open THEN
station_open_total := station_open_total + period_length;
ELSIF current_state_id = state_closed THEN
station_closed_total := station_closed_total + period_length;
ELSIF current_state_id = state_all_report THEN
station_all_report_total := station_all_report_total + period_length;
ELSE
RAISE_APPLICATION_ERROR(-20111, 'Error: found unknown state code on avi_state_history - ' || current_state_id );
END IF;
END IF;
current_state_id := next_state_id;
current_state_eff_date := next_state_eff_date;
current_station_id := next_station_id;
current_avi_id := next_avi_id;
END LOOP;
CLOSE station_loop;
-- update the totals for the percentage calculation
UPDATE vpproadside.vpp_station_summary
SET
station_total = station_open + station_close+ station_all_report
WHERE vpp_report_seq_number = in_report_id;
-- 'fix' the totals that are still zero to avoid divide by zero errors...
-- note: all the percentages will still come out as zero since the total
-- was zero
UPDATE vpproadside.vpp_station_summary
SET
station_total = 1.0
WHERE vpp_report_seq_number = in_report_id
AND station_total = 0.0;
OPEN result FOR
SELECT station_name "Site Name",
lane_name "Lane Name",
TO_CHAR((station_open / station_total) * 100.0, 'FM990.0999') || '%' "Open %",
TO_CHAR((station_close / station_total) * 100.0, 'FM990.0999') || '%' "Closed %",
TO_CHAR((station_all_report / station_total) * 100.0, 'FM990.0999') || '%' "All Report %"
FROM vpproadside.vpp_station_summary
WHERE vpp_report_seq_number = in_report_id
ORDER BY UPPER(station_name),
UPPER(lane_name);
DELETE FROM vpproadside.vpp_station_summary
WHERE vpp_report_seq_number = in_report_id;
END;Edited by: Indhu Ram on Mar 10, 2010 9:51 AM
Edited by: Indhu Ram on Mar 10, 2010 9:56 AM
Edited by: Indhu Ram on Mar 10, 2010 10:58 AM
Edited by: Indhu Ram on Mar 10, 2010 11:12 AMExactly dont know what you are asking for but I can suggest you some tips here
- If you want to check the condition in SQL query then you can use CASE statement into select clause i.e.
SELECT CASE when table1.a=table2.b then table1.c else table2.c END, ... more case..., table columns...
FROM table1, table2
WHERE
<some conditions>
- If you want to achive same functionality (SELECT only, not UPDATE/INSERT/DELETE) then you can convert the part of same procedure into function and can use the same function into your query by passing the parameters.
something like this
SELECT function_name(parameter1, parameter2....) from dual
Hope this will help -
Simpler reprsentation to SQL Query is needed
Hi all,
I have this SQL Query working goon on the Database but have some errors with Form developer so can anybody simplify it?
SELECT *
FROM (SELECT COUNT (returned_goods.ID) AS "Max Occurence", products.Name
FROM Returned_Goods
JOIN Products
ON returned_goods.productId = products.Id
GROUP BY returned_goods.productId, products.Name
ORDER BY COUNT (returned_goods.ID) DESC)
WHERE ROWNUM = 1;btw, the error encounter me in Forms appears here if anybody can help: [SQL Code not working in Forms Developer without Functions|http://forums.oracle.com/forums/thread.jspa?threadID=842122&tstart=0]
Thanks in advance :)The simpler SQL Staement is
SELECT *
FROM (SELECT COUNT (returned_goods.ID) AS "Max Occurence", products.Name
FROM returned_goods, products
WHERE
Returned_Goods.ProductId = Products.id
GROUP BY returned_goods.productId, products.Name
ORDER BY COUNT (returned_goods.ID) DESC)
WHERE ROWNUM = 1; -
TDE Table encryption SQL Query performance is very very slow
Hi,
We have done one column encryption for one table using TDE method with no salt option and it got impact the response time of sql query to 32 hours.
Oracle database version is 10.2.0.5
Example like
alter table abc modify (numberx encrypt no salt);
after encryption the SQL execution taking more time and below are the statement for the same.
================================
declare fNumber cardx.numberx%TYPE;
fCount integer :=0;
fserno cardx.serno%TYPE;
fcaccserno cardx.caccserno%TYPE;
ftrxnfeeprofserno cardx.trxnfeeprofserno%TYPE;
fstfinancial cardx.stfinancial%TYPE;
fexpirydate cardx.expirydate%TYPE;
fpreviousexpirydate cardx.previousexpirydate%TYPE;
fexpirydatestatus cardx.expirydatestatus%TYPE;
fblockeddate cardx.blockeddate%TYPE;
fproduct cardx.product%TYPE;
faccstmtsummaryind cardx.accstmtsummaryind%TYPE;
finstitution_id cardx.institution_id%TYPE;
fdefaultaccounttype cardx.defaultaccounttype%TYPE;
flanguagecode cardx.languagecode%TYPE;
froute integer;
begin for i in (select c.numberx from cardx c where c.stgeneral='NORM')
loop select c.serno, c.caccserno, c.trxnfeeprofserno, c.stfinancial, c.expirydate, c.previousexpirydate, c.expirydatestatus, c.blockeddate, c.product, c.accstmtsummaryind, c.institution_id, c.defaultaccounttype, c.languagecode, (select count(*) from caccountrouting ar where ar.cardxserno=c.serno and ar.rtrxntype=ISS_REWARDS.GetRewardTrxnTypeserno) into fserno, fcaccserno, ftrxnfeeprofserno, fstfinancial, fexpirydate, fpreviousexpirydate, fexpirydatestatus, fblockeddate, fproduct, faccstmtsummaryind, finstitution_id, fdefaultaccounttype, flanguagecode, froute from cardx c where c.numberx=i.numberx; fCount := fCount+1; end loop; dbms_output.put_line(fCount); end;
===============================
Any help would be great appreciate
Thanks,
Mohammed.
Edited by: Mohammed Yousuf on Oct 7, 2011 12:47 PMStill, that's not enough evidence to prove that TDE is indeed the culprit. Can you trace the query before and after enabling the TDE using 10046 and post it here.
Aman.... -
UCCX SQL query assistance needed.
Hello,
I am working on a SQL query that does a lookup of the calling number and the last four digits entered by the customer. If I hard code the lastFourGC variable I am able to return a successful result. If I use $lastFourGC I get the following error.
$callingNumber - Is exactly that, the calling number.
$lastFourGC - Is the last four digits collected from the customer.
SELECT * FROM GiftCardFulfillment WHERE Phone=$callingNumber and Right (GiftCard16DigitNumber, 4)=$lastFourGCTanner,
I had tried that with single and double quotes and it didn't work. I did end up getting it to work by rearranging the order. I'm not sure why that worked, but this is what the query looks like now and it works.
SELECT * FROM [leads].[dbo].[GiftCardFulfillment]
WHERE Right (GiftCard16DigitNumber, 4)=$lastFourGC and Phone=$callingNumber
Maybe you are looking for
-
How do i use the airport extreme to extend my wireless network
How do i connected my airport extreme up to my existing network so that it can extend my wireless through out the house ?? Can it be done wirelessly or do i need an ethernet cable thats about 10m ? Keith
-
How to change default value in "Project file" dialog
I'm new to Labview, and I've encountered an example with a dialog that allows to define a path to a file. If I open the properties on the block diagram of this block the name of the block appears to be "Path Properties: Project file:" The default
-
Open LDAP Authenticator Configuration on WLSSP5
I have problems in the open LDAP authenticator configuration on Weblogic Server with Service Pack 5. I have users on OpenLDAP Server that do not belong to any group. My LDIF file contents are as given below. dn: dc=my-domain,dc=com dc: my-domain obje
-
Create pop-up windows in forms 10g
I have an application in which several formal controls are made before insert/update a record. Some of them are blocking, some others arent. Actually, at every constraint violation, a message is displayed with an alert. So, the user may got one or mo
-
I have designed the cross-tab chart report with year at column, member count by risk row and risk level value. I want to hide chart bar if risk level value is less then 3. How can I create that filter/formula in Crystal Reports 2008 ?