DATA QUERY LANGUAGE (DQL) COMMANDS IN DBMS INTRODUCTION: SELECT COMMANDS It is used to retrieve information from the table. GLOBAL DATA EXTRACT : To perform a query we use a select command. The query is the request for information. It is the most common database operation used. We can either display all columns in a table or only specify column from the table. Syntax: Select * from tablename; This query selects all rowsfrom the table. THE RETRIEVAL OF SPECIFIC COLUMNS FROM A TABLE: Syntax : Select column_name1, …..,column_namen from table name; ELIMINATION OF DUPLICATES FROM THE SELECT CLAUSE: Syntax: Select DISTINCT col1, col2 from table name;
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
DATA QUERY LANGUAGE (DQL) COMMANDS IN DBMS
INTRODUCTION:
SELECT COMMANDS
It is used to retrieve information from the table.
GLOBAL DATA EXTRACT :
To perform a query we use a select command. The query is the request for information. It is the most common database operation used. We can either display all columns in a table or only specify column from the table.
Syntax:
Select * from tablename;
This query selects all rowsfrom the table.
THE RETRIEVAL OF SPECIFIC COLUMNS FROM A TABLE:
Syntax:
Select column_name1, …..,column_namen from table name;
ELIMINATION OF DUPLICATES FROM THE SELECT CLAUSE:
Syntax:
Select DISTINCT col1, col2 from table name;
DQL SELECTION
Introduction:
The DQL Selection is performed using the following Between…and In Not in Like Relational Operators Logical Operators
DATA QUERY LANGUAGE (DQL) COMMANDS
AIM: To write DQL commands to restrict and retrieve information from the database using various criteria
SELECTING ROWS AND COLUMNS:
1.Write a query to display all columns and rows from ‘departments’ table
SELECT* FROM departments ;
2.Write a query to display all the department _id and location_id from the ‘departments’ table
SELECT dept_id,loc_id FROM departments;
3.Write a query to display all department_id before location_id from the ‘departmets’ table.
SELECT loc_id,dept_id FROM departments;
4.Write a query to display all last_name,hire_date and salary from ‘employees’ table.
SELECT last_name,hire_date,salary FROM employes;
5.Write a query to display all the last_name,job_id,salary and comm_pct from the ‘employees’ table.
SELECT last_name,job_id,salary,comm_pct FROM employees;
SELECTING ROWS USING ARITHMETIC OPERATIONS
6.Write a query to calculate a salary increase of Rs.300/- for all employees and display a new salary + 300 column in the output.
SELECT last_name,salary,salary+300 FROM employees;
7.Write a query to display all the employees last_name,salary and annual compensation as 12multiplied by the monthly salary,plus one time bonus of Rs.1000/-.
SELECT last_name, salary, (12*salary) +1000 FROM employees;
SELECTING ROWS USING COLUMN ALIASES:
8. Write a query to display the last_name,salary,and the scommission percentage of all the employees with aliases name.
SELECT last_name AS Name,salary”salary”,comm_pct comm FROM employees;
9.Write a query to display the last_name,annual salay of all the employees with aliases “Annual salary”.
SELECT last_name,salary AS Annual salary FROM employees;
10.Write a query to concatenate the last_name and job_id of all employees with the aliases “Employees”.
SELECT last_name || job_id AS “Employees” FROM employees;
11.Write a query to concatenate the last_name and job_id of all employees with aliases “Employee details”.also improve the readability of the output.
SELECT last_name || job_id AS “employee details” FROM employees;
SELECTING ROWS WITH NO DUPLICATION USING DISTINCT KEYWORD:
12.Write a query to display the entire department_id without any duplication from the “employees” table.
SELECT DISTINCT dept_id FROM employees;
SELECING ROWS USING WHERE CLAUSE:
13. Write a query to retrieve the last_name,job_id and department_id of all employees whose job_id is ‘SA_REP’.
SELECT last_name,job_id,dept_id FROM departments WHERE job_id=’SA_REP’.
14. Write a query to retrieve the employee_id,last_name,job_id and department_id of all employees whose department_id is 90.
SELECT emp_id,last_name,job_id,dept_id FROM employees WHERE dept_id=’90’;
SELECTING ROWS USING COMPARISON CONDITION:
15. Write a query to retrieve the last_name and salary of all employees whose salary is less then or equal to Rs.3000/-.
SELECT last_name,salary FROM employees WHERE salary <=’3000’;
SELECTING ROWS USING BETWEEN... AND KEYWORD:
16. Write a query to retrieve the last_name,salary of all employees whose salary is between Rs.2500 and Rs.3500.
FROM employees WHERE salary BETWEEN 2500 AND 3500;
SELECTING ROWS USING IN CONDITION:
17. Write a query to retrieve the employee_id,last_name,salary and manager_id of all employees whose manager employee_id is 100,101,201.
SELECT employee_id,name,salary,manager_id FROM employees WHERE manager_id IN(100,101,201);
SELECTING ROWS USING LIKE KEYWORD WITH % AND _ SYMBOLS:
18. Write a query to retrieve the last_name of all employees whose last_name begin with’k’
SELECT last_nameFROM employees WHERE last_name LIKE ‘K%’;
19. Write a query to retrieve the names of all employees where the 3rd letter of the name is an ‘a’.
SELECT first_name FROM employees WHERE first_name LIKE’__a’;
SELECTING ROWS WITH LIKE KEYWOARD USING ESCAPE OPTION:
20. Write a query to retrieve the employee_id,last_name and job_id of all employees whose job employee_id is ‘AD_’ using LIKE with ESCAPE option.
SELECT emp_id,last_name,job_id FROM employees WHERE job_id LIKE ‘%AD\_’’ESCAPE’\’;
SELECTING ROWS USING IS NULL OPERATOR:
21. Write a query to retrieve the last_name,job_id and commission percentage of all employees who are not entitled to get a commission.
SELECT last_name,job_id,comm_pct FROM employees WHERE comm_pct ISNULL;
22. Write a query to retrieve the department_id,department_name and manager_id whose manager_id IS NULL.
SELECT dept_id,dept_name,manager_id FROM employees WHERE manager_id IS NULL;
SELECTING ROWS WITH LOGICAL CONDITION :AND,OR & NOT OPERATOR
23. Write a query to retrieve the employee_id,last_name,job_id and salary of all employees who have a job_title that contains the string ’MAN’ or earn rs.10000/- or more.
SELECT employee_id,last_name,job_id,salary FROM employees WHERE salary >=10000 OR job_id<LIKE’%MAN%’;
24. Write a query to retrieve the employe_id,name,job_id and salary of all employees who have job_title that contains the string ‘MAN’ and earn Rs.10000/- or more.
SELECT employee_id,last_name,job_id,salary FROM employees WHERE salary >= 10000 AND job_id LIKE ‘%MAN%;
25. Write a query to retrieve the last_name and salary of all employees whose salary is not between Rs.10000/- and 15,000/-
SELECT last_name,salary FROM employees WHERE salary NOT BETWEEN 10000 AND 15000;
26. Write a query to retrieve the last_name,job_id and salary of all employees if an employee is a ‘president’ or a ‘sales representative’,and if the employee earn more than Rs.15000/-.
SELECT last_name,job_id,salary FROM employees WHERE job_id=’AD_PRES’ OR job_id=’SA_REP’ AND salary >15000;
27. Write a query to retrieve the last_name and salary of all employees who earn between Rs.5000/- and Rs.12000/- and are in department 20 or 50.
SELECT last_name,salary FROM employees WHERE salary BETWEEN ‘5000’ AND ‘12000’ AND (dept_id=’20’ OR dept_id=’50’);
SELECTING ROWS USING ORDER BY CLAUSE WITH ASC AND DESC KEYWORD:
28. Write a query to retrieve the last_name,job_id,department_id and hire_date of all employees and sort the result by hired employees.
SELECT last_name,job_id,department_id,hire_date FROM employees ORDER BY hire_date;
29. Write a query to retrieve the last_name,job_id,department_id and hire_date of employees and sort the result by the most recently hired employees.
SELECT last_name,job_id,dept_id,hire_date FROM employees ORDER BY hire_date DESC;
30. Write a query to retrieve the last_name,job_id,hire_date of all employees hired between February 20,2008 and may1,2008.
SELECT last_name,job_id,hire_date FROM employees WHERE hire_date BETWEEN ’20-feb-08’ AND ‘1-may-08’;
31. Write a query to retrieve the last_name,salary and commission for all employees who earn commissions and sort the result in descending order of salary and commission percentage.
SELECT last_name,salary,comm_pct FROM employees WHERE comm_pct IS NOT NULL ORDER BY salary DESC comm_pct;
32. Write a query to retrieve the last_name and hire_date of every employee who was hired in 1997.
SELECT last_name,hire_date FROM employees WHERE hire_date LIKE ’%97%’;
SINGLE ROW FUNCTIONS
AIM: To write a DQL commands to restrict and retrieves information from the database using various single row functions.
SELECTING ROWS USING CASE-MANIPULATION FUNCTIONS:UPPER,LOWER,INITCAP
1.Write a query to display the last name and job title of all employees in the following format.
Emloyee DetailsThe job id for KUMAR is ad_vp
SELECT ‘The job id for’|| UPPER(last_name)|| LOWER(job_id) AS “Employee Details” FROM employees;
2. Write a query to display the employee id, last name, department id of all employees whose last name is ‘higgins’.
SELECT emp_id, last_name , dept_id FROM employees WHERE last_name=’Higgins’;
3. Write a query to display the employee id , last namejob title of all employees whose job title is starts with capital letter following small letters.
SELECT emp_id, last_name, job_id FROM employees WHERE job_id=INIT CAP(job_id);
SELECTING ROWS USING CHARACTER –MANIPULATION FUNCTIONS:CONCAT, SUBSTR, LENGTH ,INSTR,LPAD,RPAD,TRIM AND REPLACE
4.write a query to display the employee id , first and last names joined together and job title for all employees who have the string REP contained in the job id starting at the fourth position of the job title.
SELECT emp_id,CONCAT(first_name,last_name) AS NAME,job_id FROM employees WHERE SUBSTR(job_id,4)=’REP’;
5.Write a query to display the employee id ,last name ,length of the employee last_name,job title for all employees who have the string PROG contained in the job id starting at the third position of the job title.
SELECT emp_id, last_name, length(last_name), job_id FROM employees WHERE SUBSTR(job_id.4)=’PROG’;
6. Write a query to display the employee id , last name and the numeric position of the letter ‘a’ in the last name for all employes whose last names end with an ‘r’
SELECT emp_id, last_name INSTR (last_name,’a’) FROM employees WHERE last_name LIKE ‘%r’;
7. Write a query to diplay the salary value as right justified for a length 10 of all employees.
SELECT RPAD (select,10,’*’) FROM employees;
8. Write a query the salary value as left justified for a length 10 of all employees.
SELECT LPAD (salary,10,’*’) FROM employees;
9.Write a query to trim and display the letter ‘H’ from the Hello World’
SELECT TRIM (‘H’ FROM ‘HELLO WORLD’) FROM DUAL;
SELECTING ROWS USING NUMBER FUNCTIONS FROM DUAL TABLE:
ROUND, TRUNCATE AND MOD
10. Write a query to round the value 45.923 into 45.92’46 and 50.
SELECT ROUND (45.923) ,ROUND (45.923’0),ROUND(45.923,-1) FROM DUAL ;
11. Write a query to truncate the value 45.923 into 45.92’45 AND 0.
12.Write a query to display last name, salary and calculate the remainder of the salary after divinding it by RS. 5000/- for all employees whose job title is ‘SA_REP’.
SELECT last_name, salary,MOD (salary,5000) FROM employees WHERE job_id=’SA_REP’;
SELECTING ROWS WITH DATE FUNCTIONS:MONTHS_BETWEEN, ADD_MONTHS,NETX_DAY,LAST_DAY, ROUND, TRUNCATE
13. Write a query to display system date. Label the column “System Date”.
SELECT SYSDATE AS “ system date” FROM DUAL;
14. Write a query to display last name and the number of weeks employed for all employees in the department 90. Label the column “Weeks”.
SELECT last_name,(SYSDATE-hire_date)/7 AS “weeks” FROM employees WHERE dept_id =90;
15. Write a query to display the employee id , hire date and number of months employed of all employees. Label the column “Tenure”.
SELECT emp_id , hire_date, MONTHS_BETWEEN (SYS DATE,hire_date) AS “TENURE” FROM employees;
16.Write a query to display the employee id,hire date,current date and six months review date from the current date f all employees, Label the column “Review”.
SELECT emp_id, hire_date,sysdate,ADD_MONTHS(SYSDATE,B) AS” REVIEW FROM employees;
17. Write a query to display the employe id , hire date and first Friday after hire date of all employees fewer than 20 months.
SELECT emp_id ,hire_date,NEXT_DAY (hire_date,’FRIDAY’ ) FROM employees WHERE MOTHS_BETWEEN(sysdate,hiredate)/20;
18.Write a query to display the employee id,hire date and last day of hire month for all employees fewer than 36 months.
SELECT emp_id,hire_date, LAST_DAY(hire_date) FROM employees WHERE MONTHS_BETWEEN (sysdate,hire_date)/36;
19. Write a query to display the system date and round it to month.
SELECT SYSDATE, ROUND (SYSDATE,’year’) FROM DUAL;
20. Write a query to display the system date and truncate it to year. SELECT SYSDATE , TRUNC(SYSDATE, ‘year’) FROM DUAL;
21. Write a query to display the employee id , the hire date and start month using round and truncate functions of all employees whose hired date started in 2007.
SELECT emp_id , hire_date ROUND(hire_date,month) trunk(hire_date,month) FROM employees WHERE hire_date LIKE ‘%2007’;
SELECTING ROWS WITH DATA CONVERSION FUNCTIONS:TO_CHAR, TO_NUMBER, TO_DATE
22. Write a query to display the system date and date in the following format:‘DD/MON/YYYY’. Label the column date.
SELECT sysdate, TO_CHAR(sysdate,’DD/MON/YYYY’) AS “DATE” FROM DUAL;
23.Write a query to display the system date and year to be spelled out. Lable the column year.
SELECT sysdate, TO_CHAR(sysdate,’year’) AS “year” FROM DUAL;
25. Write a query to display the system date, full name of the month, three-letter abbreviation of the day of week . Label the columns Month and Day.
SELECT sysdate,TO_CHAR(sysdate,’MONTH’) AS”MONTH”, TO_CHAR(sysdat,’DAY’) As ‘ DAY’ ROM DUAL;
26. Write a query to display the employe id ,hired date and month on which the employee started. Label the column MONTH_HIRED of all employees whose last_name is ‘Kumar’.
SELECT emp_id,hire_date, TO_CHAR(hire_date,’MONTH’) AS “ MONTH_HIRED” FROM employees WHERE last_name=’Kumar’;
27. Write a query to display the last name,hire date, and day of the week on which the employee started . Label the column DAY. Order the results by the day of the week starting with Monday.
SELECT last_name , hire_date, TO_CHAR(hire_date,’DAY’) AS “DAY” FROM employees ORDER BY day;
28. Write a query to display the salary of all employees in the following format: $6000.00
SELECT TO_CHAR(salary,’$99,999.00’) SALARY FROM employees;
29. Write a query to convert the character string ‘01/jan/2008’ to a date format.
SELECT TO_DATE (‘01/JAN/2008’,DD-MON-YY’) FROM DUAL;
30.Wite a query to display last_name and employees hired prior to 1999.Hint : Use the RR format in TO_DATE function
SELECT last_name,TO_CHAR(hire_date,’DD-MON-YYYY’) FROM employees WHERE hire_date<TO_DATE(’01-JAN-99’,’DD-MON-RR’);
SELECTING ROWS WITH GENERAL FUNCTIONS: NVL,NVL2,NULLIF, COALESCE
31. Write a query to display the last name and manager id of all employees, also replace the null value of manager id with a text string ‘ No manager’.
SELECT last_name,NVL(TO_CHAR(manager_id), NO manager’) FROM employees;
32. Write a query to display last name and commission of all employees. If an employee does not earn commission, put the value 0. Label the column “ commission”
SELECT last_name, NVL(TO_char (comm._pct),’ZERO’) AS “COMMISSION” FROM employees;
33. Write a query to display the last name , salary,commission percentage of all employees , and if commission percentage is detected , then return string ‘Salary + Commission’ else return ‘Salary’ as aliass “ Income” whose department id is 50 and 80.
SELECT last_name,salary, comm._pct,NVL2(comm._pct,’Salary + commission’, ‘salary’) AS ‘Income’ FROM employees WHERE department id IN (50,80);
34. Write a query to display the first name ,length of the first name, last name, length of the last name and if length of both first and last name are equal, then return null else return length of the first name of all employees.
SELECT first_name , LENGTH(first_name)”expr1”,last_name LENGTH(last_name)”expr2”, NULLIF (LENGTH(last_name)) “Result” FROM employees;
35. Write a query to display the last name, commission percentage or manager id or *** based on the following conditions and order the result by commission. Label the column “ commission”a. If the employee earns commission, then commission percentage should be shown.b. If the employee does not earn commission , hen the manager id should be shown.c. If the employee does not earn comm.. and have no manager , then display ***(3 star)
SELECT last_name, COALESCE (comm._pct, manager_id,’***’) AS “Commission” FROM employees ORDER BY comm._pct;
SELECTING ROWS USING CONDITIONAL EXPRESSIONS:CASE, DECODE
36. Write a query to display the last name, job id, salary and revised salary in whole number based on the following condition of all employees. Label the column “Revised Salary”.a. If the employee’s job id is ‘IT_PROG’, then the salary increase is 10%.b. If the employee’s job id is ST_CLERK’, then the salary increase is 15%.c. If the employee’s job id is ‘SA_REP’, then the salary increase is 20%.
SELECT last_name,job_id,salary, CASE job_id WHEN ‘IT_PROG’ THEN 1.10*salary
WHEN ‘ST_CLERK’ THEN 1.15 * salaryWHEN ‘SA_REP’ THEN 1.20 * salary
ELSE salary END “revise Salary” FROM employees;
37. Write a query to display the last name, job id , salary and revised salary in whole number based on the following condition of all employees. Label the column “ Revised salary”. a. If the employee’s job id is ‘IT_PROG’, then the salary increase is 10%.b. If the employee’s job id is ST_CLERK’, then the salary increase is 15%.c. If the employee’s job id is ‘SA_REP’, then the salary increase is 20%.
38. Write a query to display the last name, salary and the applicable tax rate for each employee in department 80. Label the column “Tax Rate”.Hint: Divide the salary by RS.2000/- Based on the remainder assign tax rate.
To write DDL commands to create alter, delete, rename and truncate the various tables and create constraint to column.
DATA DEFINITION LANGUAGE (DDL):
Data definition language consists of five operations. They are
Create Alter Drop Truncate Rename
SYNTAX FOR THE OPERATIONS OF DDL:
CREATE:
CREATE TABLE TABLENAME {column name1 data type……………
………………column name n data type};
ALTER:
ALTER TABLE TABLENAME ADD {column name1 data type};
(OR)
ALTER TABLE TABLENAME MODIFY {column name2 data type};
DROP:
DROP TABLE TABLENAME;
TRUNCATE:
TRUNCATE TABLE TABLENAME;
RENAME:
RENAME old name TO new name;
TABLE CREATION AND ADDING CONSTRAINTS:
1.Write a query to create ‘countries’ table and verify it.Table description:
Country_id char(2) primary key constraint at table valueCountry_name varchar2(40) not nullRegion_id number foreign key constraint to ‘regions’ table at table
level
CREATE TABLE countries (Country_id CHAR(2),Country_name VARCHAR2(40) NOT NULL,Regions_id NUMBER,CONSTRAINT count_id_pk PRIMARY KEY (country_id),CONSTRAINT reg_id_fk FOREIGN KEY (region_id) REFERENCES regions(region_id));
Verify by: DESC countries;
2.Write a query to crate ‘locations’ table and verify it.Table description:
Loc_id number(4) primary key constraint at column levelStreet_add varchar2(40)Postal_code varchar2(12)City varchar2(30) not nullState_prov varchar2(25)Country_id char(2) foreign key to constraint to ‘countries’ table at column level
2.Write a query to create ‘students’ table and verify it.Table description:
Roll_no number(4)Name varchar2(20) not nullContact_no number(10)Mark1 number(3)Mark2 number(3)Mark3 number(3)
CREATE TABLE students (Roll_no NUMBER(4),
Name VARCHAR2(20) NOT NULL,Contact_no NUMBER(10),Mark1 NUMBER(3),Mark2 NUMBER(3),Mark3 NUMBER(3)):
Verify by: DESC students;
TABLE ALTERATION: ADD and MODIFY A COLUMN
1.Write a query to alter ‘students’ table to add ‘mark4’ and ‘mark5’ columns and verify it.Alter table description by:
Mark4 number(3)Mark5 number(3)
ALTER TABLE students ADD (Mark4 NUMBER(3),Mark5 NUMBER(3));
Verify by: DESC students;
2.Write a query to alter ‘students’ table to add the ‘total’ & ‘average’ columns and verify it.Alter table description by:
Total number(4)Average number(5,2)
ALTER TABLE students ADD (Total NUMBER(4),Average NUMBER(5,2));
Verify by: DESC students;
2.Write a query to alter ‘students’ table to modify the following column to add constraint on it and verify it.Alter table description by:
Roll_no number(4) primary key constraint
ALTER TABLE students MODIFY (Roll_no NUMBER(4) CONSTRAINT roll_no_pk PRIMARY KEY);
Verify by: DESC students;
3.Write a query to alter ‘students’ table to modify the columns to add constraints on it and verify it.Alter table description by:
Contact_no number(10) unique key constraint
ALTER TABLE students MODIFY (Contact_no NUMBER(10) CONSTRAINT contact_no_uk UNIQUE);
Verify by: DESC students;
TABLE ALTERATION: DROPPING A COLUMN
1.Write a query to alter ‘students’ table to drop the ‘mark5’ column and verify it.
ALTER TABLE students DROP COLUMN mark5;
Verify by: DESC students;
2.Write a query to alter ‘students’ table to drop the ‘mark5’ column and verify it.
ALTER TABLE students DROP COLUMN mark5;
Verify by: DESC students;
TABLE ALTERATION: SET UNUSED COLUMN and DROP UNUSED COLUMNS OPTION
1.Write a query to alter ‘students’ table to set ‘contact_no’ column as unused and verify it.
ALTER TABLE students SET UNUSED COLUMN column_no;
Verify by: DESC students;
2.Write a query to alter ‘students’ table to set ‘contact_no’ column as unused and verify it.
ALTER TABLE students SET UNUSED mark4;Verify by: DESC students;
3.Write a query to alter ‘students’ table to drop the unused columns and verify it.
ALTER TABLE students DROP UNUSED COLUMN;
Verify by: DESC students;
VIEWING CONSTRAINT:
1.Write a query to view all constraint definitions and names from the USER_CONSTRAINTS table.
SELECT * FROM USER_CONSTRAINTS;
2.Write a query to describe the field from the USER_CONSTRAINT table.
SELECT * FROM USER_CONSTRAINTS;
3.Write a query to view the constraints names and its types of the ‘employees’ table from the USER_CONSTRAINTS table.
SELECT constraint_name, constraint_type FROM USER_CONSTRIANTS WHERE table_name = ‘employees’;
4.Write a query to view the constraints names and its types from the ‘locations’ table.
SELECT constraint_name, constraint_type FROM USER_CONSTRIANTS WHERE table_name = ‘locations’;
DISABLING A CONSTRAINT:
1.Write a query to disable the UNIQUE KEY (contact_no_uk) constraint on the ‘students’ table without dropping it or re-creating it and verify it.
ALTER TABLE studentsDISABLE CONSTRAINT contact_no_uk;
Verify by: DESC students;
2.Write a query to disable the PRIMARY KEY constraint on the ‘employees’ table. Also disable associated FOREIGN KEY constraint on the ‘departments’ table without dropping or re-creating it and verify it.
ALTER TABLE employeesDISABLE CONSTRAINT emp_id_pk CASCADE;
Verify by: DESC employees;
3.Write a query to disable the PRIMARY KEY (roll_no_pk) constraint on the ‘students’ table without dropping it or re-creating and verify it.
ALTER TABLE students DISABLE CONSTRAINT roll_no_pk;
Verify by: DESC students;
ENABLING A CONSTRAINT:
1.Write a query to enable or activate the UNIQUE KEY constraint (contact_no_uk) on ‘students’ table and verify it.
ALTER TABLE students ENABLE CONSTRAINT contact_no_pk;
Verify by: DESC students;
2.Write a query to enable or activate the PRIMARY KEY constraint on the ‘employees’ table. Also enable or activate the associated FOREIGN KEY constraint on the ‘departments’ table and verify it.
ALTER TABLE employees ENABLE CONSTRAINT emp_id_pk;
Verify by: DESC employees;
3.Write a query to enable or activate the PRIMARY KEY constraint (roll_no_pk) on the ‘student’ table and verify it.
ALTER TABLE students ENABLE CONSTRAINT roll_no_pk;
Verify by: DESC students;
4.Write a query to enable or activate the PRIMARY KEY constraint on the ‘regions’ table. Also enable or activate associated FOREIGN KEY constraint on the ‘countries’ table and verify it.
ALTER TABLE regions ENABLE CONSTRAINT region_id_pk;Verify by: DESC regions;
DROPPING A CONSTRAINT:
1.Write a query to remove the UNIQUE KEY (contact_no_uk) constraint from the ‘students’ table and verify it.
ALTER TABLE students DROP CONSTRAINT contact_no_uk;
Verify by: DESC students;
2.Write a query to remove the PRIMARY KEY constraint on the ‘department’ table and drop the associated FOREIGN KEY constraint on the employees.dept_id column and verify it.
ALTER TABLE students DROP PRIMARY KEY CASCADE;
Verify by: DESC students;
3.Write a query to remove the PRIMARY KEY (roll_no_pk) constraint from the ‘students’ table and verify it.
ALTER TABLE students DROP CONSTRAINT roll_no_pk;
Verify by: DESC students;
4.Write a query to disable the PRIMARY KEY constraint on the ‘region’ table. Also disable associated FOREIGN KEY constraint on the ‘countries’ table without dropping or re-creating it and verify it.
ALTER TABLE region DROP PRIMARY KEY CASCADE;
Verify by: DESC region;
CHANGING THE NAME OF A TABLE:
1.Write a query to rename the ‘students’ table to ‘stud’ and verify it.
RENAME students TO stud;
Verify by: DESC stud;
2.Write a query to rename the ‘stud’ table to ’students’ and verify it.
RENAME stud TO students;
Verify by: DESC students;
TRUNCATEING AND DELETING TABLE:
1.Write a query to truncate the ‘students’ table and verify it.
TRUNCATE TABLE students;
Verify by: DESC students;
2.Write a query to truncate the ‘students’ table and verify it.
To write a DQL commands to restrict and retrieves information from the same table using nested queries, executes it and verify the same.
SUBQUERY
Sub-Queries are nothing but nested SELECT statement. A sub-query makes it possible for a user to base the search criteria of one SELECT statement on the results of
another SELECT statement.
PURPOSE:
To provide values for condition in where, having and start with clauses of select statement.
To define set of rows to be inserted into target table of insert or create table statement.
To define the set of rows to be include in a view or create the snapshot statement.
SUBQUERY SYNTAX:
SELECT SELECT_LIST
FROM TABLE
WHERE EXPR OPERATOR
The sub query(inner query)executes once before the main query
The result of the sub query is used by main query
TYPES OF SUB QUERIES
(SELECT SELECT_LIST
FROM TABLE);
SINGLE ROW SUB QUERY:
MAIN QUERY
SINGLE ROW SUB QUERY RETURNS A SINGLE VALUE
MULTIPLE ROW SUB QUERY:
MAIN QUERY
SUB QUERY
SUB QUERY
MULTIPLE ROW SUB QUERY RETURNS MULTIPLE VALUES
QUERIES :
SELECTING ROWS USING SUBQUERY :
1. Write a query to display the last name of all employees who earn More than Kumar’s salary and verify it.
SELECT last_name FROM employees WHERE salary > (SELECT
salary FROM employees WHERE last_name=kumar
2. Write a query to display the last_name and hire_date of all
employees who are in the same department as ‘Kumar’ and
verify it.
SELECT last_name, hire_date FROM employees WHERE
departments = (SELECT dept_name FROM employees WHERE
last_name=’Kumar’);
3. Write a query to display the last name and job id of all employees
whose job id is same as that of employee 141.
SELECT last_name, job_id FROM employees WHERE
job_id =(SELECT job_id FROM employees WHERE emp_id=’141’);
4.Write a query to display the last name and job id of all employees whose job id is same
as that of employee 141 and whose salary is greater than that of employee 143.
SELECT last_name , job_id FROM employees WHERE
emp_id = (SELECT emp_id FROM employees WHERE emp_id=141) and > (SELECT
salary FROM employees WHERE emp_id=143);
SELECTING ROWS USING GROUP FUNCTIONS IN :SUBQUERIES
5. Write a query to display the last name,job id and salary of all
employees whose salary is equal to minimum salary.
SELECT last_name, job_id, salary FROM employees WHERE
Salary = (SELECT MIN (salary) FROM employees);
6. Write a query to display the last name,job id and salary of all employees who earn
more than average salary. Sort the result in ascending order of salary.
SELECT last_name, job_id salary FROM employees WHERE
Salary > (SELECT AVG (salary) FROM employees
ORDER BY (salary));
SELECTING ROWS USING HAVING CLAUSE IN SUBQUERY :
7. Write a query to display all the department id which have a minimum salary greater than that of department id 50 .
SELECT dept_id , MIN(salary) FROM employees GROUP BY dept_id HAVING MIN(salary) > (SELECT MIN(salary) FROM employees WHERE dept_id=50);
8. Write a query to display all the job id and which have a lowest average salary and verify it.
SELECT job_id , AVG (salary) FROM employees GROUP BY
Job_id HAVING AVG (salary) = (SELECT MIN (salary) FROM employees GROUP BY( job_id);
SELECTING ROWS USING MULTIPLE ROW SUBQUERY IN
[<ANY(less than the maximum) ,>ANY(more than the minimum)
=ANY(equivalent to IN), <ALL(less than the minimum)
>ALL(more than the maximum),=ALL(equivalent to IN)]
9. Write a query to display the last name,salary,department id of all employees who earn the same salary as the minimum salary for each department and verify it.
SELECT last_name,salary,dept_id FROM employees WHERE salary IN(SELECT
MIN(salary) FROM employees GROUP BY(Dept_id);
10. Write query to display the last name,salary,department id of all employees who
earn the same salary as the average salary for each department and verify it.
SELECT last_name,salary,dept_id FROM employees WHERE
Salary IN(SELECT AVG(salary) FROM employees GROUP BY
Dept_id);
11. Write a query to display the employee id,last name,job id, salary of all employees
who are not IT programmers and whose salary is less than that of any IT programmers’
maximum salary and verify it. Note :use <ANY operator.
SELECT emp_id,last_name,job_id,salary FROM employees
WHERE salary<ANY(SELECT salary FROM employees WHERE
Job_id=’IT_PROG’) AND job_id <> ‘IT_PROG’;
12. Write a query to display the employee id,last name,job id,salary of all employees who are not SALES REPRESENTATIVE and whose salary is more than that of any sales representative’s minimum salary and verify it.
Note:use >ANY operator.
SELECT emp_id,last_name.job_id,salary FROM employees
WHERE salary>ANY(SELECT salary FROM employees WHERE job_id=’SA_REP’) AND job_id < > ‘SA_REP’;
12.Write a query display the employee id,last name,job id,salary of
all employees who are not IT programmers and whose salary is less than that of the IT
programmers minimum salary and verify it Note : use <ALL operator.
SELECT emp_id, last_name, job_id, salary FROM employees WHERE salary <ALL (SELECT salary FROM employees WHERE job_id=’IT_PROG’) AND job_id < > ‘IT_PROG’;
13.Write a query to display the employee id,last name,job id,salary of all employees
who are not SALES REPRESENTATIVE and whose salary is more than that of the sales
representative’s maximum salary and verify it Note : use >ALL operator.
SELECT emp_ id , last_name, job_id, salary FROM employees
WHERE salary >ALL (SELECT salary FROM employees
WHERE Job_id=’SA_REP’ AND job_id < > ‘ SA_REP’;
14.Write a query to display the employees last name who have subordinates and verify it .Note : use IN operator.
SELECT last_name FROM employees WHERE emp_id
IN (SELECT manager_id FROM employees);
15.Write a query to display the employees last name who do not have
subordinates and verify it Note : use NOT IN operator.
SELECT last_name FROM employees WHERE emp_id NOT IN (SELECT manager_id
FROM employees);
RESULT :
JOIN QUERIES
AIM: To write a DDL commands to join, restrict and retrieves information from one or more tables execute it and verify the same.
INTRODUCTIONThe purpose of a join concept is to combine data spread across tables. A join is actually performed by the ‘where’ clause which combines specified rows of tables.Syntax; select columns from table1, table2 where logical expression;
Types of Joins1. Simple Join2. Self Join3. Outer Join
Simple JoinIt is the most common type of join. It retrieves the rows from 2 tables having a common column and is further classified into
(a)Equi-joinA join, which is based on equalities, is called equi-join.
(b)Non Equi-joinIt specifies the relationship between columns belonging to different tables by making use of relational operators other than’=’.
Self joinJoining of a table to itself is known as self-join. It joins one row in a table to another. It can compare each row of the table to itself and also with other rows of the same table.
Outer JoinIt extends the result of a simple join. An outer join returns all the rows returned by simple join as well as those rows from one table that do not match any row from the table. The It specifies the relationship between columns belonging to different tables by making use of relational operators other than’=’.symbol(+) reprsents outer join.
JOINS
SYNTAX: SELECT table1.column,table2.column FROM table1,table2 WHERE table1.column = table2.column;
SQL>desc locn; Name Null? Type ----------------------------------------- -------- --------------------------- LID NOT NULL NUMBER(5) CITY VARCHAR2(10) AREA VARCHAR2(5)SQL>create table dep (dno number(5),dname varchar(10),lid number(5),primary ey(dno),foreign key(lid) references locn(lid));Table created;SQL>desc dep; Name Null? Type ----------------------------------------- -------- -------------------- DNO NOT NULL NUMBER(5) DNAME VARCHAR2(10) LID NUMBER(5)
Name Null? Type ----------------------------------------- -------- ------------------ GNO NOT NULL NUMBER(5) LS NUMBER(8) HS NUMBER(8)
SQL>insert into locn values(&lid,'&city','&area');enter lid:1enter city:chennaienter area:aaaold 1: insert into locn values(&lid,'&city','&area')new 1: insert into locn values(1,'chennai','aaa')1 row created
SQL>insert into dep values(&dno,'&dname',&lid);enter dno:1enter dname:adminenter lid:2old 1: insert into dep values(&dno,'&dname',&lid)new 1: insert into dep values(1,'admin',2)1 row created
SQL>insert into emp values(&eid,'&ename',&dno,&esal, &jobid,&mgr id);enter eid:3enter ename:zzzenter dno:3enter esal :3500enter jobid:2enter mgr id:2old 1: insert into emp values(&eid,'&ename',&dno,&esal,&jobid,&mgrid)new 1: insert into emp values(1,'zzz',3500,2,2)
1 row created
SQL>insert into grade values(&gno,&ls,&hs);enter gno:1enter ls:1000enter hs:2000old 1: insert into grade values(&gno,&ls,&hs)new 1: insert into grade values(1,1000,2000)1 row created
Selecting Rows With Equijoins Using Table Aliases:
1.write a query to display the employee id, last name, department id, department name and location id for all employees and verify It.
SELECT employees.emp_id, employees.last_name, employees.dept_id, d.dept_id, d.loc_id FROM employees,depatments d WHERE employees.dept_id = d.dept_id;
2.Write a query to display the higgin’s department id and department name and verify it.
SELECT e.dept_id,dept_name FROM employees e,departments d WHERE last_name=’Higgins’ AND e.dept_id = d.dept_id;
3.Write a query to display the unique listing of all jobs that are in department 80. Include the location id of the department in the output and verify it.
SELECT j.job_id,d.loc_id FROM job_histroy j,departments d WHERE dept_id=80 AND j.dept_id = d.dept_id;
NON_EQUIJOINS
SQL> select e.ename,e.esal,g.gno from emp e,grade g where e.esal between g.ls and g.hs;ENAME ESAL GNO---------- ---------- ----------bbc 4700 4xxx 4000 3yyy 2000 1zzz 3500 3abc 4500 4
Selecting Rows with Non_Equijoins using Table Aliases:Other conditions such as >=,<= and BETWEEN..AND
4.Write a query to display the last name,salary,grade level of all employees and verify it.
SELECT e.last_name,e.salary,jg.grade_level FROM employees e, job_grades jg WHERE e.salary BETWEEN jg.lowest_sal AND jg.higest_sal;
5.Writea query to display the last_name,phone number,salary and job title of all employees whose salary is greater than Rs.5000/- and verify it. SELECT e.last_name,e.phone_no,e.salary,j.job_id FROM employees e, jobs j WHERE salary>5000;
6.Write a query to display the department name,location id,last name and salaries of all employees who works in location 1800 and verify it.
SELECT e.dept_name,e.last_name,l.loc_id,e.salary FROM employees e, location l WHERE l.loc_id IN (1800);
7.Write a query to display the name ,department name and city of all employees who earn a commision and verify it.
SELECT e.last_name,e.dept_name,l.city FROM employees e,location l WHERE e.comm_pct IS NOT NULL;
OUTER JOINS
LEFT OUTER JOIN:
SYNTAX: SELECT table1.column,table2.column FROM table1,table2 WHERE table1.column(+) = table2.column;SQL> select e.ename,d.dname from emp e,dep d where e.dno(+)=d.dno;
8. Write a query to display the last name,department id and department name of a employees . Make sure that employees without department are included as well and verify it.
SELECT e.last_name,e.dept_id,d.dept_name FROM employees e, department d WHERE e.dept_id (+) = d.dept_id;
9.Write a query to display the last_name,department id ,salary and department name of all employees. Make sure that departments without employees are included as well and verified.
SELECT e.last_name,e.salary,e.dept_id FROM employees e,departments d WHERE d.dept_id = d.dept_id (+);
SELF JOINS
SELFJOIN----TO DISPLAY ENAME & THEIR MANAGER NAMES
SQL> select e.ename,m.ename from emp e,emp m where e.mgrid=m.eid;
SELFJOIN----TO DISPLAY MANAGER'S SALARY FOR EVERY EMPLOYEESQL> select e.ename,m.esal from emp e,emp m where e.mgrid=m.eid;
ENAME ESAL---------- ----------------bbc 2000yyy 4000zzz 2000Selecting Rows using Self Joins:
10.Write a query to find and display the last name of each employee’s manager and verify it.
Employee’s Manager Kumar works for Rajesh
SELECT w.last_name || ‘work for’ || m.last_name AS “Employee’s Manager” FROM employees w,employees m WHERE w.manager_id = m.emp_id;
CROSS JOIN
Selecting Rows using Cross Join: [ like cartesian product of 2 tables]
11.Write a query to displaythe last name and department name of all employees and verify it.
SELECT last_name, dept_name FROM employees CROSS JOIN departments;
NATURAL JOIN (or) INNER JOIN
Selecting Rows using Natural or Inner join: [ like equijoin]
12.Write a query to display the department id , department name , location id and city and verify it.
SELECT dept_id,dept_name,location_id,city FROM departments NATURAL JOIN locations;
13.Write a query to display the department id , department name , location id and city. Limits the rows outputs to those with department id are equal to 20 or 50 and verify it.
SELECT dept_id , dept_name , loc_id , city FROM departments NATURAL JOIN locations WHERE dept_id =’20’ OR dept_id=’50’;
JOIN with USING Clause
Selecting Rows using Join with USING Clause: [like Non_equi_join]
14.Write aquery to display employee id, last name and location id of all employees and verify it.
SELECT e.emp_id,e.last_name,l.loc_id FROM employees e JOIN Departments USING (dept_id);
15.Write a query to display location id and department name . Limits the row outputs to those with location id 4000 and verify it.
SELECT e.last_name,d.dept_name,l.loct_id FROM employees e JOIN departments d USING (dept_id) WHERE loc_id = ‘1400’;
JOIN with ON Clause
Selecting Rows using Join with ON Clauses:[like self_join]
16.Write a query to display the employee id, last name, department id, department name and loction id of all employees and verify it.
SELECT e.emp_id,e.last_name,e.dept_id,d.dept_id,d.loc_id FROM employees e JOIN departments d ON (e.dept_id = d.dept_id);
17.Write a query to display the employee id,last name,department id and department name and loction id of all employees whose manager id is 149 and verify it. SELECT e.emp_id,e.last_name,d.dept_id,d.dept_id,d.dept_name, FROM employees WHERE e.manager_id=149;
OUTER JOIN with ON Clause
LEFT OUTER JOIN with ON Clause:Selecting Rows using Left Outer Join with ON Clause:
18.Write a query to display thw last name , department id and department name of all employees. Make sure that employees without department are
included as well and verify it.
SELECT e.last_name,e.dept_id,d.dept_name FROM employees e LEFT OUTER JOIN department d ON (e.dept_id = d.dept_id);
RIGHT OUTER JOIN with ON Clause
Selecting Rows using Right Outer Join with ON Clause:
19.Write a query to display the last name , department id and department name of all employees.Make sure that departments without employees are includee as well and verify it.
SELECT e.last_name,e.dept_id,d.dept_name FROM employees e RIGHT OUTER JOIN departments d ON (d.dept_id=e.dept_id);
FULL OUTER JOIN with ON Clause
SQL>select e.ename,d,dname from emp e,dep d where e.dno(+)=(+)d.dno;ENAME DNAMEbbc xxx adminyyy financezzz hrabc finance market sales
Selecting Rows using Full Outer Join with ON Clause:
20.Write a query to display the last name,department id and department name of all employees. Make sure the following condition and verify it.
Employees without departments are includee as well. Departments without employees are included as well.
SELECT e.last_name,d.dept_id,d.dept_name FROM employees e FULL OUTER JOIN departments d ON (d.dept_id = e.dept_id);
UNION OPERATOR
Selecting Rows using Union Operator : [Eliminates duplicate records]
21.Write a query to display the current and previous job details of all employees without duplication and verify it .
SELECT emp_id,job_id FROM employees UNION SELECT emp_id,job_id FROM job_histroy;
22.Write a query to display the current and previous job details of all employees in each department without duplication and verify it.
SELECT emp_id,job_id FROM employees UNION SELECT emp_id job_id,dept_id FROM job_history GROUP BY dept_id ORDER BY emp_id;
INTERSECT OPERATOR
Selecting Rows using Intersect Operator:[Return all rows common to
multiple queries]
23.Write a query to disdplay the employee’s id and job id of employees who currently have Job title that they held before beginning their tenure with the company.
SELECT emp_id,job_id FROM employees INTERSECT SELECT emp_id,job_id FROM job_history;
MINUS OPERATOR
Select Rows using Minus Operator:[first SELECT – second SELECT]
24.Write a query to display the employee id and job id of those employees who have not changed their jobs even once and verify it.
SELECT emp_id,job_id FROM employees MINUS SELECT emp_id,job_id FROM jobs;
RESULT:
Creating Views:
01. SQL> CREATE VIEW vw_emp80(id_number, name, salary) AS SELECT emp_id, last_name, salary FROM employees WHERE dept_id=80;
Verified By:
SQL> DESC vw_emp80;
Name Null? Type ----------------- --------------- -------------------- ID_NUMBER NOT NULL NUMBER(6) NAME NOT NULL VARCHAR2(25) SALARY NUMBER(8,2)
02. SQL> SELECT * FROM vw_emp80;
ID_NUMBER NAME SALARY---------- ------ ----------- -------------149 kumar 10500174 abel 11000176 raman 8600
03. SQL> CREATE VIEW vw_sal50(id_number, Name,"Annual_Salary") AS SElect emp_id, last_name, salary*12 FROM employees WHERE dept_id=50;
View created.
Verified By:
SQL> DESC vw_sal50; Name Null? Type ----------------------------------------- -------- ---------------------------- ID_NUMBER NOT NULL NUMBER(6) NAME NOT NULL VARCHAR2(25) Annual_Salary NUMBER
04. SQL> SELECT * FROM vw_sal50;
ID_NUMBER NAME Annual_Salary---------- ------------------------- ------------- 124 petersen 69600
11. SQL> update vw_emp20 set salary=15000 where emp_id=201;
1 row updated.
Verified By:
SQL> select salary from vw_emp20 where emp_id=201;
SALARY----------15000
12. SQL> update vw_emp20 set dept_id=10 where emp_id=201;
view WITH CHECK OPTION where-clause violation.
Reason:
No rows are updated because if the dept_id where to change to 10, a view would no longer will able to see that employee. The view can see only department in dept20 and does not allow dept_id for those employees to be changed.
Creating Views with Read Only Option:
13. SQL> create or replace view vw_emp10(employee_id,employee_name,job_id) as select emp_id,last_name,job_id from employees where dept_id =10;
1 King 17-JUN-97 2 Kumar 21-SEP-99 3 Raj 13-JAN-93
RESULT:
Bind Variables:
01. Verified By (Before):SQL> SELECT emp_id, salary FROM employees WHERE emp_id=178;
EMP_ID SALARY---------- ----------178 7000
PL/SQL Block:
SET SERVEROUTPUT ON VARIABLE g_salary NUMBER BEGIN SELECT salary INTO :g_salary FROM employees WHERE emp_id=178; DBMS_OUTPUT.PUT_LINE('The Salary is assigned to the bind variable..!!!'); END; /
The Salary is assigned to the bind variable..!!!
PL/SQL procedure successfully completed.
Verified By (After):
SQL> PRINT :g_salary;
G_SALARY----------7000
02. Verified By (Before):SQL> SELECT emp_id, last_name FROM employees WHERE emp_id=101;
SQL> VARIABLE g_lname VARCHAR2(25) BEGIN SELECT last_name INTO :g_lname FROM employees WHERE emp_id=101; DBMS_OUTPUT.PUT_LINE(' The last name is assigned to the Bind Variable..!!!'); END;
/The last name is assigned to the Bind Variable..!!!
SQL> DECLARE 2 v_hire_date employees.hire_date %TYPE; 3 v_salary employees.salary %TYPE; 4 v_emp_id NUMBER NOT NULL := 100; 5 BEGIN 6 SELECT hire_date, salary INTO v_hire_date, v_salary FROM employees WHERE emp_id=v_emp_id; 7 DBMS_OUTPUT.PUT_LINE('The hire date is ' || v_hire_date); 8 DBMS_OUTPUT.PUT_LINE('The Salary is '|| v_salary); 9 END; 10 /The hire date is 17-JUN-97The Salary is 24000
PL/SQL procedure successfully completed.
05. Verified By (Before):
SQL> SELECT SUM(salary) AS sum FROM employees WHERE dept_id=60;
SUM----------19200
PL/SQL Block:
DECLAREv_emp_id employees.emp_id %TYPE;v_sum_salary employees.salary %TYPE;v_dept NUMBER NOT NULL := 60;
BEGINSELECT emp_id, SUM(salary) INTO v_emp_id, v_sum_salary FROM
employees WHERE emp_id=v_dept;DBMS_OUTPUT.PUT_LINE('The Sum of Salaries is ' || v_sum_salary);
END;
Procedure successfully completed
06. Verified By (Before):
SQL> SELECT salary FROM employees WHERE job_id='ST_CLERK';
SALARY---------- 3500 3100 2600 2500
PL/SQL Block:
SQL> DECLARE 2 v_salary_inc employees.salary%TYPE := 500; 3 BEGIN 4 UPDATE employees SET salary=salary+v_salary_inc WHERE job_id='ST_CLERK'; 5 DBMS_OUTPUT.PUT_LINE('The Salary is Updated..!!!'); 6 END; 7 /The Salary is Updated..!!!
PL/SQL procedure successfully completed.
Verified (After):
SQL> SELECT salary FROM employees WHERE job_id='ST_CLERK';
SALARY---------- 4000 3600 3100 3000
07. Verified By (Before):SELECT emp_id, last_name, dept_id FROM employees WHERE dept_id=10;
PL/SQL Block: DECLARE v_name employees.last_name%TYPE; v_job employees.job_id%TYPE := 'MK_MAN'; v_deptid employees.dept_id%TYPE :=20; BEGIN SELECT last_name INTO v_name FROM employees WHERE last_name='Petersen'; IF v_name='Petersen' THEN UPDATE employees SET job_id=v_job WHERE last_name=v_name; UPDATE employees SET dept_id=v_deptid WHERE last_name=v_name; DBMS_OUTPUT.PUT_LINE('Updated the Record ..!!!'); END IF; END; /
PL/SQL procedure successfully completed.
Verified (After):SQL> SELECT last_name, job_id, dept_id FROM employees WHERE last_name='Petersen';
10. Verified By (Before): SELECT salary FROM employees WHERE job_id=’ST_CLERK’;
SALARY-----------4500310046003500PL/SQL Block:DECLAREV_salary_inc employees.salary %TYPE := 500;BEGINFOR I in 1..2LOOP
UPDATE employees SET salary=salary+v_salary_inc WHERE job_id =’ST_CLERK’;END LOOP;
END;/
PL/SQL procedure successfully completed
Verified (After):SALARY-----------5000
360051004000
11. PL/SQL Block: DECLARE num number := 100; BEGIN WHILE num<= 250 LOOP num:= num + 25; END LOOP; DBMS_OUTPUT.PUT_LINE( 'The Value of variable num is :' ||num ); END; /The value of variable “num” is :275PL/SQL procedure successfully completed.
12. PL/SQL Block: DECLARE
Var number:=50;BEGIN WHILE var<=250LOOPVar:=var+50;END LOOP;DBMS_OUTPUT.PUT_LINE (‘The value of variable “var ” is :’ || var);END;/The value of variable “var” is :300PL/SQL procedure successfully completed.
13. PL/SQL Block:DECLARE num number := 100; BEGIN LOOP num:= num + 25; EXIT WHEN num=250; END LOOP; DBMS_OUTPUT.PUT_LINE( TO_CHAR(num)); END; /
250
PL/SQL procedure successfully completed.
14.PL/SQL Block: DECLARE Var number :=50 BEGINLOOP var:=var+50;EXIT WHEN var=300;END LOOP DBMS_OUTPUT.PUT_LINE(TO_CHAR(var));END;/
300PL/SQL procedure successfully completed.
15. Verified By (Before):SELECT last_name, job_id , dept_id FROM employees WHERE last_name=’Petersen’;
V_deptid employees.dept_id %TYPE :=20;BEGINSELECT last_name INTO v_name FROM employees WHERE last_name = ‘Petersen’;
IF v_name =’petersen’ THENGOTO updation;END IF;<<Updation>>UPDATE employees SET job_id = v_job_id WHERE last_name =v_name;UPDATE employees SET dept_id = v_dept_id WHERE last_name = v_name;DBMS_OUTPUT.PUT_LINE(‘Updated the record!!!’);END;/Updated the record!!!PL/SQL procedure successfully completed.
Verified By (After):SELECT last_name, job_id, dept_id FROM employees WHERE last_name=’petersen’;
16. Verified By:SELECT emp_id, last_name FROM employees WHERE emp_id=300;
No rows selected.PL/SQL Block: DECLARE v_emp_id employees.emp_id%TYPE; BEGIN SELECT emp_id INTO v_emp_id FROM employees WHERE emp_id=300; Exception WHEN NO_DATA_FOUND THEN DBMS_OUTPUT.PUT_LINE( 'Record for employee ID 300 is not available..!!!'); END; /Record for employee Id 300 is not available!!!PL/SQL procedure successfully completed.
17. Verified By :SELECT emp_id, last_name FROM employees WHERE emp_id=400;
no rows selected.PL/SQL Block: DECLARE
v_emp_id employees.emp_id%TYPE; BEGIN SELECT emp_id INTO v_emp_id FROM employees WHERE emp_id=400; Exception WHEN NO_DATA_FOUND THEN DBMS_OUTPUT.PUT_LINE( 'Record for employee ID 400 is not available..!!!'); END; /Record for employee ID 400 is not available..!!!PL/SQL procedure successfully completed.
18. Verified By:SELECT last_name, job_id, salary FROM employees WHERE job_id='IT_PROG';
PL/SQL Block:DECLARE Ex_lowsal EXCEPTION;V_salary employees.salary % TYPE;BEGINSELECT MIN(salary) INTO v_salary FROM employees WHERE job_id=’IT_PROG’;IF v_salary < 5000 THEN RAIS ex_lowsal;END IF;EXCEPTIONWHEN ex_lowsal THENDBMS_OUTPUT.PUT_LINE(‘Very low salary for IT programmers!!!’);END;/
Very low salary for IT programmers!!!PL/SQL procedure successfully completed.
19. Verified By:SELECT emp_id, manager_id last_name FROM employees WHERE emp_id=100;EMP_ID MANAGER_ID LAST_NAME
--------- -------------- -------------------
100 King
PL/SQL Block:DECLAREEx_manager EXCEPTION;BEGIN SELECT manager_id INTO v_managerid FROM employees WHERE dept_id=100;IF v_managerid = NULL THENEXCEPTION ex_managerEND IF;DBMS_OUTPUT.PUT_LINE (‘Employee Id 100 has NO manager!!!!’);END;/Employee Id 100 has NO manager!!!!PL/SQL procedure successfully completed.
20. Verified By:SELECT last_name from employees WHERE last_name='Rajeshwari';
No rows selectedPL/SQL Block:DECLAREEx_noemp EXCEPTIONV_lname employees.last_name %TYPE;BEGINDELETE FROM employees WHERE last_name=’Rajeshwari’;IF SQL % NOT FOUND THEN RAISE ex_noemp;ELSEDBMS_OUTPUT.PUT_LINE(‘Employee Rajeshwari Record is deleted!!!’);END IF;EXCEPTIONWHEN ex_noemp THENRAISE_APPLICATION_ERROR(-20001,’Rajeshwari is not a valid employee’);END;/ORA.-20001: Rajeshwari is not a valid employeePL/SQL procedure successfully completed.
RESULT:
Creating Procedures:
01. Verified By(Before):
SQL> SELECT salary FROM employees;
SALARY----------
24000 17000 17000
:20 rows selected.
PL/SQL Block:
SQL> CREATE OR REPLACE PROCEDURE proc_raise_salary_all IS BEGIN UPDATE employees SET salary=salary*1.10; END; /
Procedure created.
SQL> EXECUTE proc_raise_salary_all;
PL/SQL procedure successfully completed.
Verified By (After):
SQL> SELECT salary FROM employees;
SALARY----------
29040 20570 20570
:20 rows selected.
02. Verified By(Before):
SQL> SELECT mark1 FROM students;
MARK1----------
78 89 78
:7 rows selected.
PL/SQL Block:
SQL> CREATE OR REPLACE PROCEDURE proc_raise_mark_allISBEGINUPDATE students SET mark1=mark1+5;END;/
Procedure created.
SQL> EXECUTE proc_raise_mark_all;
PL/SQL procedure successfully completed.
SQL> SELECT mark1 FROM students;
MARK1----------83
94 83
:7 rows selected.
Creating procedures with parameters: IN, OUT, INOUT parameters
03. Verified By (Before):
SQL> SELECT salary FROM employees WHERE emp_id=101;
SALARY----------
18700
PL/SQL Block:
SQL> CREATE OR REPLACE PROCEDURE proc_raise_salary( p_emp_id IN employees.emp_id%TYPE)IS
BEGIN UPDATE employees SET salary= salary * 1.30 WHERE emp_id=p_emp_id; END; /
Procedure created.
SQL> EXECUTE proc_raise_salary(101);
PL/SQL procedure successfully completed.
SQL> SELECT salary FROM employees WHERE emp_id=100;
PL/SQL Block: SQL> CREATE OR REPLACE PROCEDURE proc_del_stu( p_roll_no IN students.roll_no%TYPE) IS BEGIN DELETE FROM students WHERE roll_no=p_roll_no; END; /
Procedure created.
SQL> EXECUTE proc_del_stu(7);
PL/SQL procedure successfully completed.
Verified by(After):
SQL> SELECT * FROM students WHERE roll_no=7; no rows selected.
05. PL/SQL Block:
SQL> CREATE OR REPLACE PROCEDURE proc_sal_comm ( p_emp_id IN employees.emp_id%TYPE, p_name OUT employees.last_name%TYPE, p_salary OUT employees.salary%TYPE, p_comm OUT employees.comm_pct%TYPE) IS BEGIN
SELECT last_name, salary, comm_pct INTO p_name, p_salary, p_comm FROM employees WHERE emp_id=p_emp_id;
07. SQL> CREATE OR REPLACE PROCEDURE proc_mail_job ( p_emp_id IN employees.emp_id%TYPE, p_name OUT employees.last_name%TYPE, p_mail OUT employees.email%TYPE, p_job OUT employees.job_id%TYPE) IS BEGIN
SELECT last_name,email,job_id INTO p_name,p_mail,p_job FROM employees WHERE emp_id=p_emp_id;END;/