SQL Queries

Embed Size (px)

DESCRIPTION

Find All types of Oracle SQL Queries

Citation preview

select to_char(sysdate,'ddth Yyyysp') from dual; select to_char(sysdate,'fmmonth,yyyyspth') from dual; select first_name,last_name, to_char(hire_date,'fmDay, " the " fmddth " of " fmM onth, Yyyysp "."') START_DATE from employees where upper(to_char(hire_date,'FMDAY'))='SATURDAY'; select select select select select select select select to_date('25-dec-2010') from dual; to_date('25-DEC') from dual;--encounter an error to_date('25-DEC','DD-MON') from dual; to_date('25-dec-2010 18:03:45','dd-mon-yyyy HH24:MI:SS')from dual; to_date('25-dec-2010 18/03/45','dd-mon-yyyy hh24/MI/ss') from dual; to_date('25-dec-2010 18/03/45','dd-mon-yyyy hh24:MI:ss') from dual; to_date('25-dec-10','fxDD-MON-YYYY') from dual;--generates an error to_date('25-dec-2010','fxDD-MON-YYYY') from dual;select first_name,last_name,hire_date from employees where hire_date>to_char('01/12/2000') order by hire_date; select first_name from employees where to_char(hire_date,'dd-mon')=to_char(sysdate,'dd-mon'); select to_number('$1,000.55') FROM dual;--generates error select to_number('$1,000.55','$999,999.99') from dual; select first_name,phone_number,to_number(substr(phone_number,5),'999.9999')*1000 0 LOCAL_NUMBER from employees where department_id=30; select to_number(123.45,'999.9') from dual; select to_char(123.45,'999.9') FROM dual; select length(to_char(to_date('28/10/09','dd/mm/rr'),'fmMonth')) from dual; select to_char(salary,'$99,999') salary from employees; select to_char(salary,'$99G999') salary from employees; select '$'||substr(salary,1,mod(length(salary),3))||','||substr(salary,mod(lengt h(salary),3)+1) from employees; select nvl(1234) from dual;--generates error select nvl(null,1234) from dual; select nvl(substr('abc',4),'No Substring exist!') from dual; select Last_name, salary, commission_pct, (nvl(commission_pct,0)*salary+100) "Mo nthly Commission" from employees where last_name like 'E%'; select Last_name,salary, commission_pct, commission_pct*100+1000 Montly_Salary from employees where last_name like 'E%'; select nvl2(1234,1,'Not Null') from dual;--generates error select nvl2(null,124,4231) from dual;select nvl2(124,135,4) from dual; select nvl2(substr('abc',2),'Not bc','No Substring.') from dual; select nullif(123,123) from dual; select nullif(124,123) from dual; select nullif(234,233+1) from dual; select nullif('24-JUL-2009','24-JUL-09') from dual; -- the two strings above are not same be carefull that those are consodered as s tring not date select nullif(to_date('24-JUL-2009'),to_date('24-JUL-09')) from dual; select last_name,salary,commission_pct, nvl2(commission_pct,'Commission Earner','Not a Commission Earner') Employee_type from employees where last_name like 'G%'; select first_name,last_name,email, nvl2(nullif(substr(first_name,1,1)||upper(last_name), email),'Email does not mat ch Pattern','Match Found!') pattern from employees where length(first_name)=4; SELECT first_name,last_name, Department_id, nvl2(nullif(length(first_name),length(last_name)),'Different Length','Same Lengt h') Name_lengths from employees where department_id=100; select coalesce(null,null,null) from dual; select coalesce(null,null,null,'a string') from dual; select coalesce(substr('abc',4),'Not bc','No substring') from dual; select coalesce(state_province,postal_code,city),postal_code,state_province,city from locations where country_id in ('UK','IT','JP'); SELECT decode(1234,123,'123 is a match.') from dual; select decode(1234,123,'123 is a match.','123 is not a Match.') from dual; select decode('search','comp1','true1','comp2','true2','search','true3', substr('2search',2,6),'true4','false') from dual; select distinct country_id,decode(country_id,'DR','Southern Hemisphere','AU','So uthern Hemisphere' ,'Northern Hemisphere') Hemisphere from countries order by hemisphere; select case substr('1234',1,3) when '134' then '134 is a Match.' when '124' then '124 is a Match.' when concat('1','23') then concat('1','23') || ' is a Match.' else 'No match found!' end from dual; select last_name,hire_date,trunc(months_between(sysdate,hire_date)/12) Years, trunc(months_between(sysdate,hire_date)/60) "Years Divide by 5", case trunc(months_between(sysdate,hire_date)/60) when 0 then 'Intern' when 1 then 'Junior'when 3 then 'Senior' when 2 then 'Intermediate' else 'Furniture' end Loyalty from employees where department_id in (60,10,30); select last_name,hire_date,trunc(months_between(sysdate,hire_date)/12) years, trunc(months_between(sysdate,hire_date)/60) "Year Divide by 5", case when trunc(months_between(sysdate,hire_date)/60) (select avg(salary) from employees); select p.last_name,p.department_id from employees p where p.salary < (select avg(s.salary) from employees s where s.department_id= p.department_id); select last_name from employees where salary > ( select salary from employees where last_name = 'Tobias') order by last_name; select last_name from employees where salary > ( select salary from employees where last_name = 'Taylor') order by last_name;--Generates an error -- following two queries are the solution for above problem select last_name from employees where salary > all( select salary from employees where last_name = 'Taylor') order by last_name; select last_name from employees where salary > ( select max(salary) from employees where last_name = 'Taylor') order BY last_name; select select select select last_name from employees where manager_id in ( employee_id from employees where department_id in ( department_id from departments where location_id in( location_id from locations where country_id = 'UK')));select job_title from jobs natural join employees group by job_title having avg(salary)=(select max(avg(salary))from employees group by job_id); select last_name from employees where salary>all( select salary from employees where department_id=80); --OR-select last_name from employees where salary>( select max(salary) from employees where department_id=80); select last_name from employees where department_id = ( select department_id from departments where department_name='&Department_Name'); -- Better than above -select last_name from employees where department_id = ( select department_id from departments where upper(department_name) like upper('% &department_name%')); -- Better than above --select last_name from employees WHERE department_id in ( select department_id from departments where upper(department_name) like upper('% &department_name%')); -- Alternative -select last_name,department_name from employees join departments on employees.de partment_id=departments.department_id where departments.department_id in ( select department_id from departments where upper(department_name) like upper('% &department_name%')); select employee_id from employees where salary < all (select salary from employe es wheredepartment_id=10); select employee_id from employees where salary < (select min(salary) from employ ees where department_id=10); select employee_id from employees where salary not >= any (select salary from em ployees where department_id=10);-- generates an error select employee_id from employees e join departments d on e.department_id= d.department_id where e.salary < (select min(salary) from employees) and d.department_id=10; -- no result select last_name from employees where salary > any (select salary from employees where last_name='Taylor') order by last_name; select last_name from employees where salary not < (select min(salary) from employees where last_name='Taylor') order by last_name;-- generates error select region_name from regions; select region_name from regions union select region_name from regions; select region_name from regions union all select region_name from regions; select region_name from regions union all select region_name from regions order by region_name; select region_name from regions intersect select region_name from regions; select region_name from regions minus select region_name from regions; create table old_dept(deptno number,dname char(20),dated date); create table new_dept(dept_id number(38),dname varchar2(14), started timestamp(6 )); insert insert insert insert into into into into old_dept old_dept new_dept new_dept values(10,'Accounts',sysdate); values(20,'Support',sysdate); values(10,'Accounts',sysdate); values(30,'Admin',sysdate);SELECT * from old_dept union all select * from new_dept; select * from old_dept union select * from new_dept; select deptno,trim(dname),trunc(dated) from old_dept union select dept_id,trim(dname),trunc(started) FROM new_dept; select * from old_dept intersect select * from new_dept; select deptno,trim(dname),trunc(dated) from old_dept intersect select dept_id,trim(dname),trunc(started) from new_dept; select * FROM old_dept minus select * from new_dept; select dept_id,trim(dname),trunc(started) FROM new_dept minus select deptno,trim(dname),trunc(dated) from old_dept;select department_id,count(1) from employees where department_id in (20,30,40) group by department_id; select * from regions; insert into regions values(101,'Great Britain'); insert into regions values(&regionid,'&regnName'); insert into regions values((select max(region_id)+1 from regions),'Oceania'); select * from regions; commit; create table emp_no_name (department_id NUMBER(4), job_id VARCHAR2(10), salary number(8,2), commission_pct number(2,2), hire_date date); create table emp_non_sales ( employee_id number(6), department_id number(4), salary number(8,2), hire_date date); create table emp_sales ( employee_id number(6), salary number(8,2), commission_pct number(2,2), hire_date date); insert all when 1=1 then into emp_no_name (department_id,job_id,salary,commission_pct,hire_date) values (department_id,job_id,salary,commission_pct,hire_date) when department_id 80 then into emp_non_sales (employee_id,department_id,salary,hire_date) values (employee_id,department_id,salary,hire_date) when department_id = 80 then into emp_sales (employee_id,salary,commission_pct,hire_date) values (employee_id,salary,commission_pct,hire_date) select employee_id,department_id,job_id,salary,commission_pct,hire_date from employees; select * from emp_no_name; select * from emp_non_sales; select * from emp_sales; update employees set salary=10000 where employee_id=206; update employees set salary=salary*1.1 where last_name='Cambrault'; update employees set salary=salary*1.1 where department_id in ( select department_id from departments where department_name like '%&Which_Dept%' );update employees set department_id=80,commission_pct=( select min(commission_pct) from employees where department_id=80) where employee_id=206; update regions set region_name='Scandinavia' where region_id =101; update regions set region_name='Iberia' where region_id>100; update regions set region_id=region_id+(select max(region_id) from regions) where region_id in (select region_id from regions where region_id>100); select * from regions; commit; delete from regions where region_id=204; DELETE FROM regions; delete from regions where region_id in ( select region_id from regions where region_name='Iberia'); select * from regions; commit; select * from regions; insert into regions values(100,'UK'); select * from regions; commit; select * from regions; rollback; select * from regions; delete from regions where region_id=100; select * from regions; commit; select * from regions; create table tab(col varchar(10)); INSERT INTO TAB VALUES('one'); savepoint first; INSERT INTO TAB VALUES('two'); savepoint second; INSERT INTO TAB VALUES('three'); rollback to savepoint second; rollback to savepoint first; commit; delete from tab; rollback;select * from tab; select object_type from user_object group by object_type; select object_type from all_objects group by object_type; create table "tab"(col varchar2(4)); create table "with space"("-hyphen" date); insert into "with space" values(sysdate); select "-hyphen" from "with space"; select distinct owner from all_objects; select object_type,count(*) from user_objects group by object_type; select table_name,cluster_name,iot_type from user_tables; describe regions; select column_name,data_type,nullable from user_tab_columns where table_name='REGIONS'; create table typcst(d_col date,n_col number(4,2),c_col varchar2(20)); insert into typcst values(to_date('30-08-99'),to_number('20.209'),'Inserted corr ectly'); insert into typcst values('23-08-98',44.3,'Casted automatically'); select * from typcst; desc employees; desc departments; select column_name, data_type, nullable, data_length, data_precision, data_scale from user_tab_columns where table_name='EMPLOYEES'; create table emp_dept as select first_name||' '||last_name ename, department_name dNAME,round(sysdate-hire_date+1) services from employees natural join departments order by dname,ename; select * from emp_dept where rownum < 4; alter table emp_dept drop unused columns; alter table emp_dept rename column services to no_of_days; select * from emp_dept where rownum < 6; alter table emp_dept read write; insert into emps select employee_id,last_name,salary,department_id from employee s; commit; create table dept(deptno number(2,0) constraint dept_deptno_pk primary key constraint dept_deptno_ck check (deptno between 10 and 90), dname varchar2(20) constraint dept_dname_nn not null); create table emp_cpy( empno number(4,0) constraint emp_c_empno_pk primary key, ename varchar2(20) constraint emp_c_ename_nn not null, mgr number (4,0) constraint emp_c_mgr_fk references emp_cpy (empno), dob date, hiredate date, deptno number(2,0) constraint emp_c_deptno_fk references dept(deptno) on delete set null, email varchar2(30) constraint emp_c_email_uk unique, constraint emp_c_hiredate_chk check (hiredate >= dob + 365*16), constraint emp_c_email_chk check ((instr(email,'@') > 0) and (instr(email,'.') > 0))); create table emp as select employee_id empno, last_name ename, department_id deptno from employees; create table dept as select department_id deptno, department_name dname from departments; alter table emp add constraint emp_pk primary key (empno); alter table dept add constraint dept_pk primary key (deptno); alter table emp add constraint dept_fk foreign key (deptno) references dept on delete set null; insert into dept values(10,'New Department');//generates err insert into emp values(9999,'New emp',99);//generates err truncate table dept;//generates err drop table emp; drop table dept; create view hr.emp_fin as select hire_date,job_id,salary, commission_pct,department_id from employees; select * from emp_fin; select department_name,sum(salary) from departments natural join emp_fin GROUP by department_name; create view dept_dal as select department_name,sum(salary) total_sal from departments left outer join employees using(department_id) group by department_name order by department_name; select * from dept_dal order by total_sal; create or replace view emp_dept as select /*+USE_HASH (EMPLOYEES DEPARTMENTS)*/ department_name,last_name from departments natural join employees; select * from emp_dept; create or replace view loc1800 as select department_id,department_name,location_id from departments where location_id=1800 with check option; insert into loc1800 values(99,'QA',2100);create force view ex_staff as select employee_id,last_name,left_date from employees where left_date is not null; --generates warning select * from user_objects where object_type='VIEW'; select * from ex_staff; -- generates error alter table employees add left_date date; select * from ex_staff; alter view ex_staff compile; drop view ex_staff; alter table employees drop column left_date; desc employees; create view emp_anon_v as select hire_date,job_id,salary,commission_pct,department_id from employees; create view dept_anon_v as select department_id,department_name,location_id from departments; create view dept_sum_v as select e.department_id,count(1) staff,sum(e.salary) salaries, d.department_name from emp_anon_v e join dept_anon_v d on e.department_id=d.department_id group by e.department_id,d.department_name; select * from dept_sum_v; insert into dept_anon_v values(99,'TMP_DEPT',1800); select * from dept_anon_v; select * from departments where department_id=99; insert into emp_anon_v values(sysdate,'AC_MGR',10000,0,99);--generates an error update emp_anon_v set salary=salary*1.1; select * from employees; rollback; select max(avg_sal) from (select avg(salary) avg_sal from employees group by dep artment_id); select max(salaries/staff) from dept_sum_v; select * from hr.employees; create synonym emp_p_syn for employees; select * from emp_p_syn;drop synonym emp_p_syn; create synonym emp_s for emp_anon_v; create synonym dept_s for dept_anon_v; create synonym deptsum_s for dept_sum_v; desc emp_anon_v; desc emp_s; select * from deptsum_s; insert into dept_s values(99,'Temp Dept',1800); insert into emp_s values(sysdate,'AC_MGR',10000,0,99); update emp_s set salary=salary*1.1; select * from emp_s; rollback; select max(salaries/staff) from deptsum_s; drop view emp_anon_v; select * from dept_sum_v; alter view dept_sum_v compile; drop view dept_anon_v; drop view dept_sum_v; select * from emp_s; alter synonym emp_s compile; drop synonym emp_s; drop synonym dept_s; drop synonym deptsum_s; create table orders(order_number number(4) primary key,order_date date,customer_ no number(4)); create table order_lines(order_number number(4) references orders,line_number nu mber(4), item_number number(4),quantity number(4,1)); create sequence order_seq start with 10; create sequence line_seq start with 10; INSERT INTO orders VALUES(order_seq.nextval,sysdate,1000 ); insert into order_lines values(order_seq.currval,line_seq.nextval,111,1); insert into order_lines values(order_seq.currval,line_seq.nextval,222,2); commit; select * from orders; select * from order_lines; insert into orders values(order_seq.nextval,sysdate,1002); rollback; insert into orders values(order_seq.nextval,sysdate,1003); select * from orders; alter sequence order_seq cache 100;drop drop drop dropsequence order_seq; sequence line_seq; table order_lines; table orders;create sequence seq1 start with 10 nocache maxvalue 15 cycle; select seq1.nextval from dual; select seq1.nextval from dual; create table seqtest(c1 number,c2 varchar2(10)); alter table seqtest add constraint seqtest_pk primary key(c1); CREATE sequence seqtest_pk_s; -- execute in session A insert into seqtest values(seqtest_pk_s.nextval,'First'); commit; --execute in session B insert into seqtest values(seqtest_pk_s.nextval,'Second'); -- execute in session A insert into seqtest values(seqtest_pk_s.nextval,'Third'); commit; select * from seqtest; --execute in session B select * from seqtest; rollback; select * from seqtest; drop sequence seqtest_pk_s; drop sequence seq1; drop table seqtest; select * from regions; select rowid,region_id,region_name from regions; select * from regions where rowid='AAAR5YAAFAAAACPAAC'; select count(*) from employees where last_name between 'A%' and 'Z%'; create table dept(deptno number,dname varchar2(20)); create table emp(empno number,surname varchar2(10),forename varchar2(10), dob date,deptno number); create unique index dept_i1 on dept(deptno); create unique index emp_i1 on emp(empno); create index empi2 on emp(surname,forename); create bitmap index emp_i3 on emp(deptno); alter table dept add constraint dept_pk primary key(deptno); alter table emp add constraint emp_pk primary key(empno); alter table emp add constraint emp_fk foreign key(deptno) references dept; drop index empi2; create index empi2 on emp(surname,forename,dob); drop index emp_i3; drop index empi2; drop index emp_i1;--generates error alter table emp drop constraint emp_pk; drop index emp_i1; drop table emp; drop table dept; drop index dept_i1;--generates errorcreate table emps as select * from employees; desc emps; create unique index emp_empid_i on emps(employee_id); insert into emps(employee_id,last_name,email,hire_date,job_id) values(198,'Watson','[email protected]',sysdate,'IT_PROG');--generates error create index emps_name_i on emps(first_name,last_name); create index emps_tel_i on emps(phone_number); create bitmap index emps_mgr_i on emps(manager_id); create bitmap index emps_dept_i on emps(department_id); alter table emps add constraint emps_empid_pk primary key(employee_id); alter table emps add constraint emps_email_uk unique(email); alter table emps add constraint emps_phone_uk unique(phone_number); select index_name,index_type,uniqueness from user_indexes where table_name='EMPS'; drop table emps; select index_name from user_indexes where table_name='EMPS';