I have to write an sql query in oracle 11g for the following scenario.
I have a table customers. It has three columns customer_id,cust_cat and cust_deterioration_date. customer_id is the primary key.
customers
(customer_id varchar2(20),
cust_cat varchar2(1),
cust_deterioration_date date
);
I have another table Accounts. It has 4 columns loan_account_number,product_code,account_deterioration_date,customer_id. loan_account_number is the primary key.
Accounts
(loan_account_number varchar2(20),
product_code varchar2(4),
account_deterioration_date date,
customer_id varchar2(20)
)
I have to select the customers who has loan accounts having product code as 9213 or 9450 in the accounts table and whose cust_cat is 'G'.
If such a customer has multiple loan accounts with product code 9213 or 9450,and Only if the account_deterioration_date for all those loan accounts are null,I should update cust_deterioration_date in customers table as null.
Here is my query to select the reuired customers.
SELECT UNIQUE s1.customer_no
FROM accounts a1
,customers s1
WHERE a1.customer_id = s1.customer_no
AND NVL(s1.cust_cat,
'G') = 'G'
AND a1.product_code IN ('9213',
'9450')
AND a1.account_deterioration_date IS NULL
AND NOT EXISTS (SELECT 1
FROM accounts a
WHERE a.customer_id = s1.customer_no
AND a.account_deterioration_date IS NOT NULL
AND a.product_code IN ('9213',
'9450'))
This query is fetching the required result but at the cost of performance. Is there any better way to achieve this functionality?
Thanks in advance
from accounts join customers on ...) a long time ago. As to performance: an index onaccount(product_code, customer_id)and a function index oncustomers( nvl(cust_cat,'G') )might help.