Vous êtes sur la page 1sur 20

Oracle SQL Queries User Creation/Deletion/Modification & Granting Permission to the user ---------------------------------------------------------------------1.

Create user sdemo identified by sdemo123 - Creating New User in Oracle. 2.Grant connect,resource,dba to sdemo - Giving Permission to the newly created u ser.Permissions are Connect,Resource,DBA. 3.Grant Select on emptest to sdemo - Giving Access permission to other user's ta bles. ex: Select * from sdemo.emptest. 4.Grant Select,Insert,update on T1 to Sdemo - Giving Access permission to other user's table with Select,Insert & Update Permission. 5.Revoke connect,resource,dba from sdemo - Removing Permission to the specified user. 6.Alter user sdemo identified by pass - Changing Password for the user. 7.Drop user sdemo - Removing the user from the oracle. 8.Select * from all_users - Shows all the users in the oracle. 9.Alter user demo account lock - locking the user. 10.Alter user demo account unlock - Unlocking the user. 11.Alter user demo identified by demo123 account unlock - Change Password of a l ocked account. 12.Select * From v$locked_object - Shows all users locking & unlocking status. or Select * from dba_users. 13.Select user from dual - Shows current logged user. 14.Grant connect,resource,dba to user1,user2 - Granting permissions to more than one users. 15.Grant select on tabledemo to user1 with grant option - User1 has got Select p ermission of tabledemo table and he can give select permission to other users. 16.SELECT GRANTEE, OWNER, GRANTOR, PRIVILEGE, GRANTABLE FROM DBA_TAB_PRIVS WHERE TABLE_NAME = 'tabledemo' and OWNER = 'system' - Shows current user's privilegas . 17.Select * from user_users - To view account lock open status. Oracle Table Creation/Deletion/Modification/updation. ----------------------------------------------------18. Create Table T1 - New Table Creation. ( Empno Number, Empname Varchar2(20), DOB Date, Remarks Varchar2(20)

) 19. Create Table T2 as Select * from T1 - Creating Table from existing table. 20. Create Table T3 as Select * from T2 where 1=2 - Creating table structure fro m existing table. 21. Select * from user_tables - Shows all the tables of current user. 22. Select * from user_objects where object_type='TABLE' - shows all the tables of current user. 23. Desc T1 - To View the Structure of the table. 24. Select * from tab - Shows all objects like tables,views,sysnonyms,index. 25. Drop Table T3 - Removing Table. 26. Alter table t1 add ( Salary number(6,2)) - New Column addition. 27. Alter table t1 drop column remarks - Removing Columns. 28. Alter table t1 rename column salary to basicsalary - Renaming column. 29. Rename t1 to sunoidatable - Renaming table. 30. Insert into t2 values(1000,'ab','03-Mar-2010','sss',333) - Inserting the row s into the table. 31. Insert into t2 values(2000,Null,'04-Mar-2011','eee',444) - Assigning Null va lue for unknown value column. 32. Insert into t2(empno,empname,remarks,salary) values (3000,'ss','dd',4000) Assigning Column Values for Specific Columns. 33. Insert into tj select * from t2 - Copying All the columns value from existin g table to new table. 34. Insert into tk(empno,empname) (select Empno,empname from t2) - Copying Speci fic columns' value from existing table. 35. Update tk set salary=2000 where empno=1000 - Updating specific rows based on condition. 36. Delete from tk where empno=2000 - Removing Specific Rows. 37. Delete from tk - Deleting all Rows but can rollback the deleted rows. 38. Truncate Table tk - Deleting all rows but can not rollback. 39. update t1 set salary=salary+1000 - update the rows(records) with arithmetic opeators(+,-,/,*). Constraints in Oracle ( Not Null,Unique,Primary key,Foreign Key,Default,Check) -------------------------------------------------------------------------------40. Create Table NTS - Not Null Constraint at Column Level.

( empno number Constraint FF not null, empname varchar2(20) ) 41.Create Table NTG - Unique Constraint means column value should be unique. ( empno number constraint k unique, empname varchar2(20) ) 42.Create Table pkc - (Primary Key=Unique+Not Null) Note: primary key in column level. ( empno number constraint sk Primary key, empname varchar2(20) ) 43.Create Table pkcd - Primary key in Table Level. ( empno number, empname varchar2(20), constraint sks Primary key (empno,empname) ) 44.Create table Pk - Shows Primary & Foreign Key relationship and Creation metho d. ( Empno Number, Ename varchar2(20), DOB Date, Salary number, remarks varchar2(20), Constraint il primary key(empno) ) Create table fk ( empno number, dept varchar2(20), Constraint oo foreign key (empno) references pk(empno) ) 45.Create Table DT - Assigning Default Value to the column level while creatin g table. ( Empno Number, Empname Varchar2(20), DOB Date, Salary Number default '5000', Remarks varchar2(29) ) 46.Create Table UU - Adding Column's value with check condition. ( Empno Number,

Empname Varchar2(20) check (empname like ('M%')), DOB Date, Salary Number default '5000', Remarks varchar2(29) ) 47.Create Table UUss - Multiple Check Condition with constraint name. ( Empno Number, Empname Varchar2(20), DOB Date, Salary Number default '5000', Remarks varchar2(29), Constraint us check (empname like ('M%') and Empno>0) ) 48.Select * from user_constraints - Shows all the constraints. 49.Alter table UUss drop constraint us - Removes Constraints. 50.Alter table uuss add constraint ii primary key(empno) - Adding Constraints to specific column for existing tables. 51.Create Table UN - Multiple Constraints for the same Column. ( Empno Number Not Null Unique, Empname Varchar2(20) ) 52.Create Table kk - Assigning Primary & Foreign Key Constraint at Table Level. ( Empno Number Not Null, Empname Varchar2(20), DOB Date, Salary Number, Remarks Varchar2(20), Constraint Pkk Primary Key(Empno), Constraint FKK Foreign Key(empno) References uuss(empno) ) 53.Create Table TDS - Assigning Sysdate as a default Hire_Date column. ( Empno Number Not Null, Empname Varchar2(20), Hire_Date Date default sysdate, Salary Number, Remarks Varchar2(20), Constraint Pkkss Primary Key(Empno), Constraint FKKss Foreign Key(empno) References uuss(empno) )

Select Statements format -------------------------54.Select * from jj - Shows all rows of the table. 55.Select Employee_id,Last_name,Job_id,Salary from jj - Shows Specific Columns.

56.Select * from jj where Salary>2000 - Selecting Rows with Condition.we can giv e the condition like <,>,<=,>=,<> etc. 57.Select * from jj where Salary>2000 And Salary<4000 - Selecting Rows with AND/ OR/NOT COnditions. 58.Select * from jj where Salary is null - Select rows with salary is null colum n. 59.Select * from jj where Salary is not null - Select rows with salary is not nu ll column. 60.Select count(*) from jj - gives count of records. 61.Select count(1) from jj - gives count of records.Note: Suggested Method. 62.Select sysdate from dual - Shows current system date and time. 63.Select Employee_id,First_name || ' - ' ||Last_name Empname,JOb_id,Salary from jj - Joining two columns using || Symbol. 64.Select Employee_id Empno,Email Emailaddress,JOB_Id JObno from jj - Giving Col umn level alias. 65.Select Employee_id Empno,Email Emailaddress,JOB_Id JObno from jj Employees Table Level Alias. here we changed the table name jj to employees. 66.Select * from jj where first_name like 'S%' - Gives first_name starting with S letter. 67.Select * from jj where first_name like 'L__' - Gives first_name Starting with L and remaining two letter firstname only. 68.Select * from jj where ( first_name like 'S%' and Salary > 2000) - Gives valu es with mulitiple condition. 69.Select Employee_id,First_name ||'-'|| Last_Name Empname,Salary,(Salary*12) Bo nus from jj - Doing Calculation in Select clause in column level. 70.Select Phone_Number,Hire_date from (Select * from jj where first_name like 'S %') - Select query working as a table in another select. 71.Select Employee_id,First_name ||'-'|| Last_Name Empname,(Select sysdate from dual) Current_date from jj - Select inside select. 72.Select Employee_id,First_name ||'-'|| Last_Name as Empname from jj - Giving C olumn Level alias name using as. Sorting Columns ----------------73.Select * from jj order by Salary - Ascending order of the salary column. 74.Select * from jj order by 8 - Ascending order of the 8th column. 75.Select * from jj where salary>2000 order by salary desc - Descending order of the salary column. 76.Select * from jj where salary>2000 order by salary desc,First_Name - Sorting Order of the multiple Columns.

Aggregate Functions (Min,Max,Sum,Count,Avg) ---------------------------------------------77.Select min(Salary) from jj - returns minimum of the salary. 78.Select max(Salary) from jj - returns maximum of the salary. 79.Select sum(Salary) from jj - returns sum of the salary. 80.Select Count(Salary) from jj - returns count of the salary. 81.Select avg(Salary) from jj - returns average of the salary. Dual Table ----------82.Select 76+80 from dual - we can do arithmetic operation using dual table. Numeric Functions -----------------83.Select abs(-1) from dual - gives absolute value means only positive value. 84.Select ceil(156.87) from dual - result 157. 85.Select ceil(156.17) from dual - result 157. 86.Select ceil(156.00) from dual - result 156. 87.Select ceil(156.50) from dual - result 157. 88.Select ceil(156.1) from dual - result 157. 89.Select ceil(-156.87) from dual - result -156. 90.Select floor(156.87) from dual - result 156. 91.Select floor(156.17) from dual - result 156. 92.Select floor(156.00) from dual - result 156. 93.Select floor(156.50) from dual - result 156. 94.Select floor(156.1) from dual - result 156. 95.Select floor(-156.87) from dual - result -157. 96.Select trunc(156.87,1) from dual - result 156.8 97.Select trunc(156.17,2) from dual - result 156.17. 98.Select trunc(156.00,3) from dual - result 156. 99.Select trunc(156.1250,3) from dual - result 156.125

100.Select trunc(156.1,0) from dual - result 156. 101.Select trunc(-156.87,1) from dual - result -156.8. 102.Select trunc(-156.87,-1) from dual - result -150. 103.Select round(156.87,1) from dual - result 156.9 104.Select round(156.177,2) from dual - result 156.18. 105.Select round(156.00,3) from dual - result 156. 106.Select round(156.1250,3) from dual - result 156.125 107.Select round(156.1,0) from dual - result 156. 108.Select round(-156.87,1) from dual - result -156.9. 109.Select round(-156.87,-1) from dual - result -160. Text Functions -------------110.Select lower('WELCOME') from dual - result - welcome. 111.Select upper('Welcome') from dual - result - WELCOME. 112.Select initcap('welcome') from dual - result - Welcome. 113.Select ltrim(' welcome') from dual - result removing left side spaces. 114.Select Rtrim('welcome 115.Select trim(' welcome ') from dual - Result removing right side spaces. ') from dual - Result removes spaces on both sides.

116.Select substr('Welcome',3,3) from dual - Result - lco. 117.Select length('Welcome') from dual - Result 7. 118.Select lpad('Welcome',20,'*') from dual - Result *************Welcome. 119.Select Rpad('Welcome',20,'*') from dual - Result Welcome*************. Date Functions -------------120. Select trunc(sysdate) from dual - Displays only current system date without time. 121. Select trunc(add_months(sysdate,3)) from dual - Adding 3 months from sysdat e. 122. Select months_between(sysdate,'30-Mar-2012') from dual - Returns months bet ween. 123. Select round(to_date('22-MAR-03'),'YEAR') FROM DUAL - Result 1/1/2003. Not e: if month is greater than 6 then it return next year else current year. 124. Select round(to_date('22-Aug-03'),'YEAR') FROM DUAL - Result 1/1/2004.

125. Select round(to_date('22-Sep-03'),'Q') FROM DUAL - Result 10/1/2003. Note: if Quarter is greater than 45 days then it return next quarter first month else first month of the current quarter. 126. Select round(to_date('22-July-03'),'Q') FROM DUAL - Result 7/1/2003. 127. Select round(to_date('22-AUG-03'),'MONTH') FROM DUAL - Result 9/1/2003. NOTE: if day is greater than 15 days then return first day of next month else fi rst day of current month. 128.Select round(to_date('12-AUG-03'),'MONTH') FROM DUAL - Result 8/1/2003. 129.Select round(to_date('22-AUG-03'),'DDD') FROM DUAL - Result 8/22/2003. - Di splays Current Date. 130.Select round(to_date('12-AUG-03'),'DDD') FROM DUAL - Result 8/12/2003 - Dis plays Current Date. 131.Select round(to_date('1-MAY-2012'),'DAY') FROM DUAL - Result 4/29/2012. Note: if Date belongs Mon to Wed then return previous sunday's date else next su nday's date. 132.Select round(to_date('4-MAY-2012'),'DAY') FROM DUAL - Result 5/6/2012. 133.Select trunc(to_date('14-Aug-03'),'YEAR') FROM DUAL - Result 1/1/2003. - Fir st day of the current year. 134.Select trunc(to_date('14-Aug-03'),'Q') FROM DUAL - Resutl 7/1/2003 - First d ay of the current quarter. 135.Select trunc(to_date('14-Aug-03'),'MONTH') FROM DUAL - First day of the curr ent month. 136.Select trunc(to_date('14-Aug-03'),'DDD') FROM DUAL - Current Date. 137.Select trunc(to_date('14-Aug-03'),'DAY') FROM DUAL - Result : 8/10/2003. ret urn the last sunday's date. 138.Select next_day(sysdate,'TUESDAY') from dual - Result 5/29/2012. 139.Select last_day(to_date('2003/03/15','yyyy/mm/dd')) from dual - Result 3/31/ 2003. Return last day of the specified date. 140.Select salary,to_char(to_date(Salary,'J'),'jsp') from jj - To convert Number to words.Ex: 44 - fourty four. 141.Select To_date('15-Mar-2011','DD-Mon-RRRR') from dual - To Convert Number to Date data format. 142.Select To_char(To_date('15-Mar-2011','DD-Mon-RRRR'),'DD-MM-RRRR') from dual - To Convert Desired Date format like DD-Mon-RRRR ex: 12-JAN-2012. 143.Select to_char(sysdate,'Mon') from dual - To get the month of the current da te. 144.Select extract(YEAR FROM sysdate) from dual - To extract the year/month/day of the current date.

Null Function -------------145.Select Employee_id,First_name,Last_name,nvl(commission_pct,0) test from jj - Nvl() function is used to assign zero value in the null columns. Group by Clause ---------------146.Select Employee_id, First_Name, Last_Name, Sum(Salary) From JJ Group by Employee_id, First_Name, Last_Name Note: While using Group by, all the columns' corresponding alias should be remov ed. Having Clause --------------147.Select Employee_id empno, First_Name gjgjj, Last_Name, Sum(Salary) From JJ Group by Employee_id, First_Name, Last_Name Having Sum(Salary) > 20000 Note: If you need to give condition in group by, you have to put the condition u sing "having" clause. Common Functions ----------------148.Select mod(10,4) from dual - Reminder of the given value. 149.Select distinct(department_id) from jj - return unique distinct values. 150.Select sqrt(salary) from jj - return square root values of salary. 151.Select power(10,2) from dual - return the power value. 152.Select to_number('1000') from dual - Convert Character datatype to number da tatype. 153.Select uid from dual - Shows current user id. 154.Select concat('welcome','god') from dual - Two Strings are concatenated usin g concat(). 155.select translate('welcome','e','b') from dual - To Translate one letter to a nother letter.

Index in SQL -------------156.Create Index demoindex on emp (employee_id) - Index Creation against employe e_id column. 157.Select * from user_indexes - shows all indexes. 158.drop index demoindex - removing index for the tables. 159.Alter index demoindex rename to TN - Renaming existing Indexes. 160.Create index supplier_idx on emp (Upper(first_name)) - we have created an in dex based on uppercase evaluation on the first_name field. 161.alter index supplier_idx rebuild - rebuilding index of the table.note: when a table goes through many changes like insertions,deletions and updates. it is advisable to rebuild indexes based on that table. 162.Create unique index idxx on emptest(empno) - Creating Index and make index o nly based on unique records. Dropping Unused Column on the table -----------------------------------163.Alter table emp set unused column Employee_id - To Set removing column as a unused for deletion. 164.Alter table emp drop unused columns - To remove all unused column of the tab le. Pseudo Columns in SQL ---------------------165.Select rowid as cl,first_name,last_name from emp 166.Select rownum,first_name,last_name from emp Nested Conditions (Decode(),Case when..... ------------------------------------------167.Select First_Name,Last_Name,decode(job_id,'IT_PROG','Sunoida Programmer','AD _PRES','Sunoida President','AD_VP','Sunoida Vice President') Job_Position from e mp - it gives the multiple condition in select statement like if statement in other languages. 168.Select - Multiple condition using Case Statement. First_Name, Last_Name, Case Job_id When 'IT_PROG' Then 'Sunoida Programmer' When 'AD_PRES' Then 'Sunoida President' else 'Sunoida Vice President' end Job_Position From emp Synonym Creation in Oracle SQL --------------------------------

169.Create synonym semp for emp - Creating different name for same table. Note: Synonym can be created Table,Views,Sequence,Stored Procedures & Functions, package,materialized views,user defined objects,java class schema object. 170.Select * from user_synonyms - To View all existing synonyms. 171.Drop synonym semp - To Remove Existing Synonyms. 172.Create or replace synonym sdemo for sample - Recreating Synonym of existing table. 173.rename sdemo to newdemo - Renaming Existing synonym to new synonym name. Comments in Oralce SQL -----------------------174.Select /* This is my first sql statement Designed by s.madheswaran */ Employee_id, First_Name, Last_Name, Salary ----- this is salary column for calculating salary. ---Manager_id - hiding the column for query execution From Emp Sequence Creation ---------------------175.Create Sequence empno_seq Start with 1000 MinValue 1000 Maxvalue 2000 Increment by 1 176.Select * from user_Sequences - to view all the sequences. 177.Drop sequence emps - To Remove Existing Sequences. 178. rename emps to emm - To Rename a Sequences. Enable/Disable Constraints ---------------------------179. Alter table eemp disable constraint tt - To Disable a Constraints of the ta ble. 180. Alter table eemp enable constraint tt - To Enable a Constraints of the tabl e. View Creation ------------181. Create view vemp as select * from emp where salary > 200 - To create a view based on condition. 182. Drop view vemp - To Remove a view. 183. Rename vemp to viewemp - To Rname a view. 184. Select * from user_views - To Display all views.

Set Operators in Oracle ( Union,Union All,Intersect & Minus) ------------------------------------------------------------185. Select * From Tab1 - To Display both tables records with unique rows only. Union Select * From Tab2 186. Select * From Tab1 - To Display both tables records Including duplicate ro ws. Union All Select * From Tab2 187. Select * From Tab1 - To Display only first tables records(These records ar e not there in the second table Tab1-Tab2). Minus Select * From Tab2 188. Select * From Tab1 - To Display both tables common records. Intersect Select * From Tab2 Note: In Set Operators,Both tables' column count should be match. In,Not In & Between ... and Operators --------------------------------------189. Select * from tab1 where salary in (3000,13000) - To List the rows only lis ted in this query. 190. Select * from tab1 where salary not in (3000,13000) - To List the rows not in the list in this query. 191. Select * from tab1 where salary Between 3000 and 13000 - Shows Ranges value s using between clause. Coalesce & To_char function ---------------------------192. Select Empno,Ename,Salary,coalesce(Mobileno,officeno,Homeno) Contact_NO fro m tab1 - Displays the first not null value in the column. 193. Select Empno,ename,to_char(salary,'$99999.99') from tab1 - To format the nu mber like $1987.23. Oracle version and other details ----------------------------------194. Select banner from v$version - To Display about oracle details. Adding Numbers to Null value --------------------------------195. SELECT 100+null Result1, Null + 100 Result2 FROM dual - it gives blank reco rds since adding null with value gives null only. All the tables columns ----------------------196. Select * from user_ind_columns - Shows all the tables and its corresponding

columns. Joins in Oracle SQL (Join,Left Join,Right Join,Full Join,Self & Non equi) -----------------------------------------------------------197.Select - Simple join or Equi join T1.empno, T1.ename, T1.Salary, T2.Deptname From Master T1, Detail T2 Where T1.empno=T2.empno 198. Inner Join using Inner Join Keyword Select T1.empno, T1.ename, T1.Salary, T2.Deptname From Master T1 Inner join Detail T2 on T1.empno=T2.empno 199. Right Outer join Select T1.empno, T1.ename, T1.Salary, T2.Deptname From Master T1, Detail T2 Where T1.empno(+)=T2.empno 200. Left Outer join Select T1.empno, T1.ename, T1.Salary, T2.Deptname From Master T1, Detail T2 Where T1.empno=T2.empno(+) 201.For Full Outer join, we have to use both left and right outer join with unio n operator. Select T1.empno, T1.ename, T1.Salary, T2.Deptname From

Master T1, Detail T2 Where T1.empno=T2.empno(+) union Select T1.empno, T1.ename, T1.Salary, T2.Deptname From Master T1, Detail T2 Where T1.empno(+)=T2.empno 202.Self Join - join within join on the same table. Select T1.Ename, T2.Ename From self T1, self T2 Where T1.Manager_id=T2.empno 203.Non Equi Join - Join without = operator called as non equi join. Select T1.Ename, T2.Ename From self T1, self T2 Where T1.Manager_id<>T2.empno Sub Queries in Oracle ----------------------There are two types of sub queries in oracle, `Single Row Subquery' and 'Multipl e Row Subquery'. Single Row Subqueries: The subquery returns only one row. Use single row compari son operators like =, > etc while doing comparisions. Multiple Row Subqueries: The subquery returns more than one row. Use multiple ro w comparison operators like IN, ANY, ALL in the comparisons. 204. Single Row Subquery using > operator. Select * from t2 where salary > (Select salary from t2 where empno=2000) 205. Single Row Subquery using = operator. Select * from t2 where salary = (Select max(salary) from t2) 206.Multiple Row Subquery using In Operator.

Select * from t2 where salary in (Select max(Salary) from t2 group by dept) 207.Multiple Row Subquery using Not In Operator. Select * from t2 where salary not in (Select max(Salary) from t2 group by dept) 208.Multiple Row Subquery using Any Operator. Select * from t2 where salary < Any (Select Salary from t2 where dept='IT') 209.Multiple Row Subquery using ALL Operator. Select * from t2 where salary > All (Select Salary from t2 where dept='Acct') Correlated Sub Query ---------------------Correlated sub query is used for row by row processing. The sub query is execute d for each row of the main query. 210. Multiple Row Subquery using Exists Operator. SELECT DEPARTMENT_ID, DEPARTMENT_NAME FROM DEPARTMENTS D WHERE EXISTS ( SELECT 1 FROM EMPLOYEES E WHERE E.DEPARTMENT_ID = D.DEPARTMENT_ID) 211. Multiple Row Subquery using Not Exists Operator. SELECT DEPARTMENT_ID, DEPARTMENT_NAME FROM DEPARTMENTS D WHERE NOT EXISTS ( SELECT 1 FROM EMPLOYEES E WHERE E.DEPARTMENT_ID = D.DEPARTMENT_ID) Note: In,All,Any or Some are opertor for multiple row sub query. 212.ROWNUMBER,RANK(),DENSE_RANK() WITH PARTITION BY SELECT d.department_name, e.last_name, e.salary ,ROW_NUMBER() OVER ( PARTITION BY e.department_id ORDER BY e.salary) A S rownumber ,RANK() OVER ( PARTITION BY e.department_id ORDER BY e.salary) AS rank ,DENSE_RANK() OVER ( PARTITION BY e.department_id ORDER BY e.salary) A S drank FROM employees e, departments d WHERE e.department_id = d.department_id AND d.department_id IN ('20','30', '40') ORDER BY d.department_name, e.salary, e.last_name, rank; 213.ROWNUMBER,RANK(),DENSE_RANK() WITHOUT PARTITION BY SELECT empno , sal , RANK() OVER(ORDER BY sal) rank_position

, , FROM

DENSE_RANK() OVER(ORDER BY sal) dense_rank_position ROW_NUMBER() OVER(ORDER BY sal) row_number_position emp

214.Selecting Duplicate Records from the table. 1.Select * from sample where rowid not in ( Select min(rowid) from sample group by empno) 2.Select * from dt where rowid not in (Select min(rowid) from dt group by empno, ename) 3.Select * from dt T1 where rowid > ( Select min(rowid) from dt t2 where t1.empn o=t2.empno and t1.ename=t2.ename) Note: To Remove a Duplicate rows,first we need to decide how many columns' data should be matched. based columns count, we have to specify the joins. 215.To delete 1st row in table. delete from emp where rowid in (Select min(rowid) from emp ); 216.To delete last row in table. delete from emp where rowid in (Select max(rowid) from emp ); 217.Column Level Alias functionality. Select empno eno,ename,Salary from dt where eno=100 - while we running this quer y. we get error because we can not give alias eno=100. it supposed to be empno=1 00. 218.2nd highest salary in the emp table. Select * From ( Select EMPNO,ENAME,Salary,RANK() OVER (ORDER BY SALARY desc) Rank_Status from dt ) Where Rank_Status=2 219.In which year did most people join the company?Display the year and the numb er of employees. Select * From (Select To_char(hiredate,'RRRR') Years,Count(1) ct from emp Group by To_char(hir edate,'RRRR') order by 2 desc) T1 Where rownum=1 220.Suppose there are two tables Employee and Salary_Grade.Salary_Grade contains lowsal,Hisal.We want to fetch all records where sal of employees less than lows al. (Non Equi Join example)

SELECT * FROM EMPLOYEE E, SALARY_GRADE SD WHERE E.SAL<=SD.LOWSAL. 221.In Emp_SAL table there are two columns gross_pay and net_pay. Fetch the reco rds where gross_pay and net_pay are same.(Self Join one more example) SELECT * FROM EMP_SAL E1,EMP_SAL E2 WHERE E1.GROSS_PAY=E2.NET_PAY 222.Selecting the first n rows with Oracle select name, price from items where rownum < 6; Note: we can use rownum=1 or rownum<6 but can not use like rownum=5 or rownum> 4 5 because >,>= are not allowed with a rownum pseudocolumn. 223.To Find the Nth Row of the Record. Select * from (Select rownum as a,empno,ename from dt) where a=3 224.To Display Odd Rows from the table. Select * from dt where rowid in (Select decode(mod(rownum,2),1,rowid,null) from dt) 225.To Display Even Rows from the table. Select * from dt where rowid in (Select decode(mod(rownum,2),0,rowid,null) from dt) 226.Find the 3rd MAX salary in the emp table. Select * from (Select empno,ename,Salary,RANK() OVER (ORDER BY SALARY desc) Rank _Status from dt) T1 where T1.RANK_STATUS=3 227.Creating Virtual view using 'with' clause ---------------------------------------------with ggwith as (Select sum(sal) total_salary from gemp) select empno,ename,sal from gemp,ggwith where sal>total_salary 228.Granting Procedure creation rights to the user. ---------------------------------------------------grant create procedure to username 229.Dropping Procedure ----------------------drop procedure procedurename 230.Compiling View -------------------Alter view emp_view compile; - sometimes we remove the column from base and add ing column again. that time view will create automatically. sometimes we need to compile manually. 231.Function Dropping ---------------------Drop function functionname - To delete existing function.

232.Insert multiple rows of explicit data in one SQL command --------------------------------------------------------------(i) Insert multiple rows of same tables -----------------------------------------insert all into test values(100,'a') into test values(200,'b') into test values(300,'c') into test values(400,'d') Select * from dual; (ii) Insert multiple rows of different tables ----------------------------------------------INSERT ALL INTO suppliers (supplier_id, supplier_name) VALUES (1000, 'IBM') INTO suppliers (supplier_id, supplier_name) VALUES (2000, 'Microsoft') INTO customers (customer_id, customer_name, city) VALUES (999999, 'Anderson C onstruction', 'New York') SELECT * FROM dual; (iii) Unconditional Insert all ---------------------------------Insert all into emp1 values(empid,ename,salary,deptno) into dept1 values(deptno,deptname) Select empid,ename,salary,deptno,deptname from empdet Note: split the records from empdet and insert into emp1 and dept1 tables. (iv) conditional Insert all --------------------------------Insert all when salary > 10000 then into emp1 values(empid,ename,salary,deptno) when deptno <> 30 then into dept1 values(deptno,deptname) Select empid,ename,salary,deptno,deptname from empdet (v) Conditional Insert First ------------------------------Insert first when salary > 10000 then into emp1 values(empid,ename,salary,deptno) when deptno <> 30 then into dept1 values(deptno,deptname) Select empid,ename,salary,deptno,deptname from empdet Note: the row satisfies both conditions salary>50000 and deptid<>40, it will be inserted into the first table only, because the first condition of the when clause satisfied. 233.To retrieve the Oracle instance name, you execute the following SQL statemen t: select sys_context('USERENV','DB_NAME') as Instance from dual;

234. Binary to Number Conversion --------------------------------select bin_to_num(1) from dual 235. Cast Convert one data type to another datatype ---------------------------------------------------select cast( '22-Aug-2003' AS varchar2(30) ) from dual; 236.NVL2 function -----------------syntax: NVL2( string1, value_if_NOT_null, value_if_null ) select supplier_id,NVL2(supplier_desc, supplier_name, supplier_name2) from suppl iers; 237.Removing Package ---------------------drop package packagename 238.To find out the list of packages Select * from user_source where type like 'PA%' 239.To Show the database name. Select name from v$database; 240.TO display all the existing procedures. Select Object_name from dba_objects where object_type='PROCEDURE' 241. How to view the procedure? Select text from dba_source where name='Procedurename' and type='Procedure'; 242. Shows all current pl/sql program errors Select * from user_errors 243. Shows all triggers Select * from user_triggers 244.Dropping Trigger. Drop trigger triggername. 245.Renaming a existing constraint alter table testdemo rename constraint dd to god 246. Merge Statement merge into worker w using ( Select stud,last,first from student) s on (s.stud=w. worker) when matched then update set w.last=s.last,w.first=s.first when not matched then insert(w.worker,w.last,w.first) values (s.stud,s.last,s.first)

247.Nullif Statement ----------------------Note: We want to show NULL if actual sales is equal to sales goal, and show actual sales if the two are different. To do this, we issue the followi ng SQL statement: Select empid,ename,nullif(sales,goal) result from testdemos - both sales,goal ar e same then you can not see the values. if both are different you can see the firstvalue of nullif() function li ke sales. 248.Running Total -------------------Select t1.name, t1.sales, sum(t2.sales) running_total From total_sales t1, total_sales t2 where t1.sales<=t2.sales or (t1.sales=t2.sales and t1.name=t2.name) Group by t1.name, t1.sales order by t1.sales desc, t1.name desc

Vous aimerez peut-être aussi