Showing posts with label SQL. Show all posts
Showing posts with label SQL. Show all posts

Monday, 10 April 2023

Defragmentation Implementation in ODI

Defragmentation Implementation in ODI:

Execute below Code in database to create tables:

create table bi11g_dw.defragment_table as

select owner, table_name,sum(BLOCKS) S,'N' as flag

FROM ALL_TABLES

where owner in ('BI11G_DW', 'BI12C_BIA_ODIREPO','STG') and

(ROUND(((BLOCKS*16/1024)-(NUM_ROWS*AVG_ROW_LEN/1024/1024)),2)/ROUND(((BLOCKS*16/1024)),2))*100 >20 and

--table_name not like '%CFG%' and avg_row_len <> '0' group by owner, table_name order by s ASC;

------------------------------------------------------------------------------------------------------------

create table bi11g_dw.defragment_ind_table as select a.owner, a.table_name, b.index_name, 'N' as FLAG from bi11g_dw.defragment_table a, all_indexes b where a.table_name=b.table_name and a.owner=b.owner;

-----------------------------------------------------------------------------------------

 CREATE TABLE "BI11G_DW"."DEFRAGMENT_TMP" 

   ( "TABLE_NAME" VARCHAR2(50 BYTE)

   )

------------------------------------------------------------------------------------------

ODI Proc code:

-------------------

step 1:

update bi11g_dw.defragment_table  set flag='N';

Step2:

DECLARE

    CUR1 SYS_REFCURSOR;

    CUR2 SYS_REFCURSOR;

    V_TABLENAME VARCHAR2(50);

    V_INDEXNAME VARCHAR2(50);

    V_OWNER VARCHAR2(50);

    BEGIN

      OPEN CUR1 FOR

        select owner,table_name from bi11g_dw.defragment_table WHERE FLAG='N' order by s ASC;

      LOOP

        FETCH CUR1 INTO V_OWNER,V_TABLENAME;

        EXIT WHEN CUR1%NOTFOUND;

        EXECUTE IMMEDIATE'TRUNCATE TABLE bi11g_dw.defragment_tmp';

        insert into  bi11g_dw.defragment_tmp values (V_TABLENAME);

      EXECUTE IMMEDIATE 'ALTER TABLE '||V_OWNER||'.'||V_TABLENAME||' MOVE';

          OPEN CUR2 FOR SELECT OWNER,TABLE_NAME, INDEX_NAME FROM bi11g_dw.defragment_ind_table WHERE TABLE_NAME = V_TABLENAME;

          LOOP

            FETCH CUR2 INTO V_OWNER,V_TABLENAME,V_INDEXNAME;

            EXIT WHEN CUR2%NOTFOUND;

            EXECUTE IMMEDIATE'TRUNCATE TABLE bi11g_dw.defragment_tmp';

        insert into  bi11g_dw.defragment_tmp values (V_TABLENAME);

             EXECUTE IMMEDIATE 'ALTER INDEX '||V_OWNER||'.'||V_INDEXNAME||' REBUILD ONLINE';

             UPDATE bi11g_dw.defragment_ind_table SET FLAG='Y' WHERE TABLE_NAME=V_TABLENAME AND INDEX_NAME=V_INDEXNAME;

             commit;

            END LOOP;

         dbms_stats.gather_table_stats(ownname => V_OWNER, tabname =>V_TABLENAME, estimate_percent =>DBMS_STATS.AUTO_SAMPLE_SIZE, method_opt => 'FOR ALL COLUMNS SIZE AUTO');

      UPDATE bi11g_dw.defragment_table SET FLAG='Y' WHERE TABLE_NAME=V_TABLENAME;

      COMMIT;

       END LOOP;

       END;



ODI Proc2:

---------

update Bi11G_DW.defragment_table set flag='E' where table_name in (select * from Bi11G_DW.defragment_tmp)

How to check table space in database

 Query : To check tablespace in database 

select t.tablespace,  t.totalspace as " Totalspace(MB)",
     round((t.totalspace-nvl(fs.freespace,0)),2) as "Used Space(MB)",
     nvl(fs.freespace,0) as "Freespace(MB)",
     round(((t.totalspace-nvl(fs.freespace,0))/t.totalspace)*100,2) as "%Used",
     round((nvl(fs.freespace,0)/t.totalspace)*100,2) as "% Free",
     us.USERNAME
     from
     (select round(sum(d.bytes)/(1024*1024)) as totalspace,d.tablespace_name tablespace
     from dba_data_files d
     group by d.tablespace_name) t,
     (select round(sum(f.bytes)/(1024*1024)) as freespace,f.tablespace_name tablespace
     from dba_free_space f
     group by f.tablespace_name) fs,
     (  SELECT USERNAME ,default_tablespace FROM  dba_users)  us     where t.tablespace=fs.tablespace (+)   AND t.tablespace(+) = us.default_tablespace
     order by "% Free";

Saturday, 28 May 2022

Get results for all tables row count in schema and truncate all tables at a time in schema

get results for all tables row count in schema

---------------------------------------------------

SET SERVEROUTPUT ON;

DECLARE 

VAL NUMBER;

BEGIN

for i in (SELECT table_name FROM all_tables WHERE owner = 'Ora_Schema' and table_name like '%GL%')

LOOP

EXECUTE IMMEDIATE 'SELECT count(*) from Ora_Schema.' || i.table_name INTO VAL;

DBMS_OUTPUT.PUT_LINE(i.table_name || ' | ' || VAL);

END LOOP;

END;


truncate all tables at a time in schema

---------------------------------------------------


set serveroutput on;

begin

for t1 in (SELECT table_name FROM all_tables WHERE owner = 'Orc_schema' and table_name in ('GL_LEDGERS','GL_CALENDARS')) loop

    begin

       ----- dbms_output.put_line('truncate table '||t1.table_name || ';');    

        execute immediate ('truncate table '||t1.table_name);

    end;

end loop;

end;


Monday, 25 April 2022

get/extract char , date , numeric values from varchar column

requirement:

amount column having numeric data , char data and date also

So char /date data into one column and numeric (+ve, -ve ) values in another column

use below query to acheive that:

select

case when  trim(TRANSLATE(replace(substr(amount_in_char,0,1),'-','')||substr(amount_in_char,2), '0123456789,.', ' ')) is not null 

then amount_in_char end getchardtae,

case  when trim(TRANSLATE(replace(substr(amount_in_char,0,1),'-','')||substr(amount_in_char,2), '0123456789,.', ' ')) is  null 

then amount_in_char end getnum,

amount_in_char original from w_plan_fs; 








Tuesday, 19 April 2022

Find out the long running queries/locked objects in database

 Use below queries

check the odi session id status in database


Example:

 select * from GV$SESSION WHERE ACTION LIKE '%21622%'; (odi session id)

SELECT * FROM V$SESSION_LONGOPS WHERE SID=1392;

SELECT * FROM V$SESSION WHERE SEQ#='9383';ACTION LIKE '%21622%';

SELECT SQL_FULLTEXT ,LOCKED_TOTAL,SQL_ID FROM GV$SQL WHERE SQL_ID='383g771j';

SELECT * FROM GV$SQL;

alter system kill session '648,51886' IMMEDIATE

select username, status from v$session where SID=12;

Wednesday, 30 November 2016

SQL important queries?

1.   Select FIRST n records from a table ( in dynamically)?
select * from employees where rownum <= &n;

Note: '&' used for Dynamic pompt , enter the value in dynamically. when runs the query , it wil ask enter n value. It also called temporary & substitution varaible.  If enter 1 value , we wil get single row data. If you want fisrt 50 rows ,we have to enter n value is 50.

For Ex: without enter 'n' value then use
Ø  select * from employees where rownum <= 1
Ø  select * from employees where rownum <= 50;
Ø  SELECT * FROM (select * from employees ORDER BY employee_id) abc WHERE rownum <= 5 ORDER BY rownum asc;

2.  Select LAST n records from a table
(select * from employees )
minus
( select * from employees where rownum <= (select count(*) - &n from employees));

3.   In employees table add comm+sal as total sal  ?
select ename,(sal+nvl(comm,0)) as totalsal from employees;
Note:.NVL() to convert a null value to another value. NVL(x, value) returns value if x is null; otherwise x is returns.

4.  How can I create an empty table emp1 with same structure as employees ?
Create table emp1 as select * from employees where 1=2.
Note: Here Structure only created ,no rows displayed

5.  How can I create an table emp2 with same structure as employees ?
Create table emp2 as select * from employees
Note:Here create the table with Structure and table . Hence structure with table data rows displayed

6. If there are two tables emp1 and emp2, and both have common record. How can I fetch all the recods but common records only once?
  • (Select * from employees1) union (Select * from employees2) 
  • (Select * from employees1) Intersect (Select * from employees2)
  • Select * from employees1 a ,employees2 b where a.employees1=b.employees1
  •  Select * from employees1 a inner join employees2 b on  a.employees1=b.employees2

7. How can I retrive all records of emp1 those should not present in emp2?
(Select * from emp1) Minus (Select * from emp2)

8. How to get nth max salaries ?(highest salary)?
select distinct hire_date ,salary from employees a where &n =
(select count(distinct salary) from employees b where a.salary >= b.salary);

Note : without using 'n' , we can get max salary -Different alternative solutions are
  • select distinct hire_date ,salary from employees a where 57 =  (select count(distinct salary) from emp2 b where a.salary >= b.salary);
  • select  max(salary) , max( hire_date)  from employees
  • select count(distinct salary), max(salary) , max( hire_date) from employees
9. List dept no., Dept name for all the departments in which there are no employees in the department?

  • select * from dept where department_id not in (select department_id from employees);
  • select * from dept a where not exists (select * from employees b where a.department_id = b.department_id);
  • select * from employees a, dept b where a.department_id(+) = b.department_id and employee_id is null;
10. How to delete duplicate rows in a table?
  • delete from employees a where rowid != (select max(rowid) from employees b where  a.employee_id=b.employee_id);
  • DELETE FROM employees WHERE rowid not in (SELECT MIN(rowid) FROM employees GROUP BY employee_id);
Note : checking for duplicates
SELECT  employee_id , COUNT(employee_id) nr FROM    employees GROUP BY employee_id HAVING  COUNT(employee_id) > 1


11. Display the names of employees who are working in the company for the past 5 years?
  •  select fisrt_name,hire_date from employees where sysdate-hire_date > 5*365;
  • select first_name from employees where to_char(sysdate,'YYYY')-to_char(hire_date,'YYYY')>=5;
  • SELECT employee_id, last_name, hire_date, MONTHS_BETWEEN(SYSDATE, hire_date) "number of months employed" FROM employees WHERE MONTHS_BETWEEN(SYSDATE, hire_date) >= 60;
  •  select first_name from employees where hire_date < add_months(sysdate,-60);


12.Display the names of employees working in department number 10 or 20 or 40 and working as CLERKS,SALESMAN or ANALYST?


select first_name, job_id from employees where department_id in(10,20,40) and job_id in(CLERKS ', SALESMAN ', ANALYST ');

13.List the emps who joined in any year but not belongs to the month of March?
  •     select * from employees where  to_char (hire_date,’MON’) not in (‘MAR’);  (OR)
  •    select * from employees where to_char (hire_date,’MON’)  !=  ‘MAR’; (OR)
  •    select * from employees where to_char(hire_date,’MONTH’) not like ‘MAR%’ ;  (OR)
  •    select * from employees where to_char(hire_date,’MON’)  <> ‘MAR’;
14.List the Empno, Ename, Sal, Dname of all the ‘MGRS’ and ‘ANALYST’ working in New York, Dallas with an exp more than 7 years without receiving the Comm asc order of Loc?


select e.empno,e.ename,e.deptno,e.sal,d.loc from emp e ,dept d
where e.deptno = d.deptno and d.loc in ('NEW YORK','DALLAS') and
e.job_id in ('MGRS',ANALYST) and  (months_between(sysdate,e.hire_date)/12)>7  and  e.commission_pct is null

End-to-End Databricks S3 Workflow: Connect, Create Tables, Archive, and Move Files

End-to-End Databricks S3 Workflow: Connect, Create Tables, Archive, and Move Files Introduction An end-to-end Databricks S3 pipeline ofte...