General SQL Scripts

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 10

General SQL Scripts

Sample SQL matrix report

SELECT job,
sum(decode(deptno,10,sal))
sum(decode(deptno,20,sal))
sum(decode(deptno,30,sal))
sum(decode(deptno,40,sal))
FROM scott.emp
GROUP BY job

DEPT10,
DEPT20,
DEPT30,
DEPT40

/
-----------

Sample output:
JOB
DEPT10
DEPT20
DEPT30
DEPT40
--------- ---------- ---------- ---------- ---------ANALYST
6000
CLERK
1300
1900
950
MANAGER
2450
2975
2850
PRESIDENT
5000
SALESMAN
5600

Lookup Oracle error messages

set serveroutput on
set veri off feed off
prompt Lookup Oracle error messages:
prompt
prompt Please enter error numbers as negatives. E.g. -1
prompt
exec dbms_output.put_line('==> '||sqlerrm( &errno ) );
set veri on feed on
undef errno

Display Database version, installed options and port string

set head off feed off pages 0 serveroutput on


col banner format a72 wrap

select banner
from
sys.v_$version;
select '
With the '||parameter||' option'
from
sys.v_$option
where value = 'TRUE';
select '
The '||parameter||' option is not installed'
from
sys.v_$option
where value <> 'TRUE';
begin
dbms_output.put_line('Port String: '||dbms_utility.port_string);
end;
/
set head on feed on

"Who am I" script

set termout off


store set store rep
set head off
set pause off
set termout on
select 'User: '|| user || ' on database ' || global_name,
' (term='||USERENV('TERMINAL')||
', audsid='||USERENV('SESSIONID')||')' as MYCONTEXT
from
global_name;
@store
set termout on

Select the Nth highest value from a table

select level, max('col_name') from my_table


where level = '&n'
connect by prior ('col_name') > 'col_name')
group by level;
-- Example :
--

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

Given a table called emp with the following columns:


id
number
name varchar2(20)
sal number
For the second highest salary:
select level, max(sal) from emp
where level=2
connect by prior sal > sal
group by level

Select the Nth lowest value from a table

select level, min('col_name') from my_table


where level = '&n'
connect by prior ('col_name') < 'col_name')
group by level;

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

Example:
Given a table called emp with the following columns:
id
number
name varchar2(20)
sal number
For the second lowest salary:
select level, min(sal) from emp
where level=2
connect by prior sal < sal
group by level

Demonstrate default column values

-- drop table x
-- /
create table x (a char, b number default 99999, c date, d varchar2(6))

/
alter table x modify (c date default sysdate)
/
insert into x(a, d) values ('a', 'qwerty')
/
select * from x
/
--- Expected output:
--- A
B C
D
-- - ---------- ----------- ------- a
99999 25-APR-2001 qwerty
-

Display table and column comments

set pages 50000


set null 'No Comments'
tti 'Table Comments'
col comments format a29 wrap word
select * from user_tab_comments;
tti 'Column Comments'
col comments format a18 wrap word
break on table_name skip 1
select * from user_col_comments;
clear break
set null ''
set pages 23

Pass application info through to the Oracle RDBMS

-- The following code tells the database what the application is up to:

begin
dbms_application_info.set_client_info('BANCS application info');
dbms_application_info.set_module('BANCS XYZ module', 'BANCS action
name');
end;
/
-- Retrieve application info from the database:
select module, action, client_info
from
sys.v_$session where audsid = USERENV('SESSIONID')
/
select sql_text
from
sys.v_$sqlarea
where module = 'BANCS XYZ module'
and action = 'BANCS action name'
/

SQL*Plus Help script

select info
from
system.help
where upper(topic)=upper('&1')
/

Test for Leap Years

select year,
decode( mod(year, 4), 0,
decode( mod(year, 400), 0, 'Leap Year',
decode( mod(year, 100), 0, 'Not a Leap Year', 'Leap Year')
), 'Not a Leap Year'
) as leap_year_indicator
from
my_table
/

Spell out numbers to words

select decode( sign( &num ), -1, 'Negative ', 0, 'Zero', NULL ) ||

Demonstrate simple encoding and decoding of messages

SELECT TRANSLATE(
'HELLO WORLD',
-- Message to encode
'ABCDEFGHIJKLMNOPQRSTUVWXYZ ',
'1234567890!@#$%^&*()-=_+;,.') ENCODED_MESSAGE
FROM DUAL
/
SELECT TRANSLATE(
'85@@%._%*@4',
-- Message to decode
'1234567890!@#$%^&*()-=_+;,.',
'ABCDEFGHIJKLMNOPQRSTUVWXYZ ') DECODED_MESSAGE
FROM DUAL
/

Count the number of rows for ALL tables in current schema

decode( sign( abs(&num) ), +1,


to_char( to_date( abs(&num),'J'),'Jsp') )
from dual
/

set termout off echo off feed off trimspool on head off pages 0
spool countall.tmp
select 'SELECT count(*), '''||table_name||''' from '||table_name||';'
from
user_tables
/
spool off
set termout on
@@countall.tmp
set head on feed on

Demonstrate Oracle database types and object tables

drop type employee_typ;


create type employee_typ as object (
empno NUMBER,
emp_name varchar2(30),
hiredate date,
member function days_at_company return NUMBER,
pragma restrict_references(days_at_company, WNDS)
)
/
create type body employee_tye is
begin
member function days_at_company return number is
begin
return (SYSDATE-hiredate);
end;
end;
/
show errors
drop type department_typ;
create type department_typ as object (
deptno NUMBER(5),
manager ref employee_typ
)
/
select * from user_types
where predefined = 'NO';
-- Create a object table
create table emp1 as employee_typ;
create table employee (emp_no NUMBER, emp employee_typ);
insert into employee values (1, employee_typ(1, 'Frank Naude',
SYSDATE));
commit;
select * from employee;
select x.emp.emp_name from employee x;

Demonstrate VARRAY database types

CREATE OR REPLACE TYPE vcarray AS VARRAY(10) OF VARCHAR2(128);


/
CREATE TABLE varray_table (id number, col1 vcarray);
INSERT INTO varray_table VALUES (1, vcarray('A'));
INSERT INTO varray_table VALUES (2, vcarray('B', 'C'));
INSERT INTO varray_table VALUES (3, vcarray('D', 'E', 'F'));
SELECT * FROM varray_table;
SELECT * FROM USER_VARRAYS;
-- SELECT * FROM USER_SEGMENTS;
-- Unnesting the collection:
select t1.id, t2.COLUMN_VALUE
from
varray_table t1, TABLE(t1.col1) t2
/
-- Use PL/SQL to access the varray...
set serveroutput on
declare
v_vcarray vcarray;
begin
for c1 in (select * from varray_table) loop
dbms_output.put_line('Row fetched...');
FOR i IN c1.col1.FIRST..c1.col1.LAST LOOP
dbms_output.put_line('...property fetched: '|| c1.col1(i));
END LOOP;
end loop;
end;
/
-- Clean-up...
DROP TABLE varray_table;
DROP TYPE vcarray;

Demonstrate Oracle temporary tables

drop table x
/
create global temporary table x (a date)
on commit delete rows
-- Delete rows after commit
-- on commit preserve rows
-- Delete rows after exit session
/
select table_name, temporary, duration

from
where
/

user_tables
table_name = 'X'

insert into x values (sysdate);


select * from x;
commit;
-- Inserted rows are missing after commit
select * from x;

Convert LONG data types to LOBs

create table old_long_table(c1 number, c2 long);


insert into old_long_table values (1, 'LONG data to convert to CLOB');
create table new_lob_table(c1 number, c2 clob);
-- Use TO_LOB function to convert LONG to LOB...
insert into new_lob_table
select c1, to_lob(c2) from old_long_table;
-- Note: the same procdure can be used to convert LONG RAW datatypes to
BLOBs.

Delete duplicate values from a table

DELETE FROM my_table


WHERE ROWID NOT IN (SELECT MIN(ROWID)
FROM my_table
GROUP BY delete_col_name);
-- Example :
--- Given a table called emp with the following columns:
-id
number
-name varchar2(20)
-sal number
--- To delete the duplicate values:

--- DELETE FROM emp


-- WHERE ROWID NOT IN (SELECT MIN(ROWID) FROM emp GROUP BY id);
--- COMMIT;
--

You might also like