Vous êtes sur la page 1sur 60

NO.

1
Aim:-To study DDL commands. Theory:SQL - Structured Query Language SQL is a database language used for accessing data in a relational database. DDL - Data Definition Language DDL commands are the SQL commands used to create, alter, drop (delete) different database objects in an ORACLE database. Table Definition A Database Object is something created and stored in a database. Tables, views, synonym, indexes, sequences are all types of database objects. Table: It is a unit of storage that holds data in the form of rows and columns. DDL COMMAND:To use the Data Definition Language (DDL) for creating, altering and droping the table object in a database. 1. 2. 3. 4. CREATE TABLE ALTER TABLE DROP TABLE TRUNCATE TABLE

Create table command Syntax: create table < table_name> (column_name1 datatype(size), column_name2 datatype(size), : : : : column_name n datatype(size)); e.g. To create a table EMP with the column EMPNO, ENAME, JOB, MGR, JOINDATE, SALARY, COMM, DEPTNO. create table emp ( empno number(5),

ename varchar2(25), job varchar2(15), mgr number(5), joindate date, salary number(7,2), comm number(7,2), deptno number(5)); The above SQL statement will create a table EMP with the given columns. To view the structure of the table created use the DESCRIBE COMMAND.The command displays the column names and datatypes. Syntax: desc[ribe] <table_name>; e.g. desc EMP; Restrictions for creating a table: 1 2 3 4 5 6 1. Table names and column names must begin with a letter. 2. Table names and column names can be 1 to 30 characters long. 3. Table names must contain only the characters A-Z, a-z, 0-9, underscore _ , $ and #. 4. Table name should not be same as the name of another database object. 5. Table name must not be an ORACLE reserved word. 6. Column names should not be duplicate within a table definition.

Alter table command : Syntax: Case 1: alter table <table_name> add ( column_name1 datatype (size), column_name2 datatype (size), : : : : ,column_name n datatype (size)); alter table <table_name>

Case 2:

modify (column_name1 datatype, (size), column_name2 datatype (size), : : : : ,column_name n datatype (size)); After you create a table, you may need to change the table structures because you need to have a column or your column definition needs to be changed. ALTER TABLE statement can be used for this purpose. You can add columns to a table using the ALTER TABLE statement with the ADD clause. e.g. To add a column ADDRESS to the table EMP. alter table emp add (address varchar2 (20)); You can modify existing column in a table by using the ALTER TABLE statement with the MODIFY clause. e.g. To modify the length of the NAME field to 30 in the EMP table. alter table emp modify (ename varchar2 (30)); Result of the above alter table commands can be seen by DESC command. Restrictions: 1. 2. 3. 4. You can add or modify columns, but you cannot drop them from a table. The new column becomes last column by default. You can increase the width or precision of a numeric column. You can change the datatype if the column contains null values (column is empty). 5. Decrease the width of a column if the column contains only null values or if the table has no rows. 6. You can convert a CHAR column to the VARCHAR2 datatype or convert VARCHAR2 column to CHAR datatype if the column contains null values or if you do not change the size. Drop table command

The drop table statement removes the definition (structure) of an Oracle table. When you drop a table, the database loses all the data in the table and all the indexes associated with it. Note: Create a dummy table and then use it in the drop table command. Syntax: drop table <table_name>; e.g drop table emp; Truncate table command The truncate table statement is used to remove all rows from a table and to release the storage space used by the table. Syntax: truncate table <table_name>; e.g truncate table emp; Rename table command Rename statement is used to rename a table, view, sequence, or a synonym. Syntax: rename <oldtable_name> to <newtable_name>; e.g. To change the name of the table EMP to EMPTBL rename emp to emptbl; Exercise:-Quries for Execution:1)Create table student where column names are roll-no,name,address,branch,& date of birth. 2)Add column name email-id in the table. 3)Change the name of the table student to employee. 4)delete the table.

NO.2 Aim:-To study DML command Theory:- Data Manipulation Language (DML) DML commands are the SQL commands used to access or manipulate data in an ORACLE database. To use the Data Manipulation language for inserting, selecting, updating and deleting the data in the table in a database.

Data Manipulation Language (DML) Commands 1. Insert 2. Select 3. Update 4. Delete Insert command Insert command is used to load data into the table. Syntax: insert into <table_name> (column_name1, column_name 2, . . . . . . column_name n) values (expression1, expression 2, . . . . . . expression n); Example: To insert a row into the EMP table created in the previous .

The above SQL statement will insert a single record in the EMP table. In order to add more records to the EMP table, the insert command can be used with a new set of values each time. Case 1: Inserting values for selected columns insert into emp(empno, ename, job, mgr, joindate,salary,comm,deptno, address ) values (1001, nilesh joshi,clerk,1005,17-dec-1995,2800, 600,20,nashik); Inserting values for all columns insert into emp values(1002,avinash pawar, salesman,1003, 20-feb-1996,5000,1200,30,nagpur); Inserting more than one records insert into emp values(&empno,&ename,&job,&mgr,&joindate, &salary,&comm,&deptno,&address); Enter value for empno: 1003 Enter value for ename: amit kumar Enter value for job: manager Enter value for mgr: 1004 Enter value for joindate: 02-apr-1995 Enter value for salary: 20000 Enter value for comm: null Enter value for deptno: 30 Enter value for address: pune SQL> / Note: '/' is used to repeat the previous command. Emp Table EMPN ENAME O 1001 Nilesh joshi 1002 Avinash pawar 1003 Amit kumar 1004 Nitin kulkarni 1005 1006 1007 1008 Niraj sharma Pushkar Deshpande Sumit patil Ravi sawant JOB Clerk Salesma n Manager Presiden t Analyst Salesma n Manager Analyst MG R 1005 1003 1004 1003 1003 1004 1007 JOINDAT E 17-dec-95 20-feb-96 02-apr-86 19-apr-86 03-dec-98 08-sep-96 01-may-91 17-nov-95 SALARY 2800 5000 2000 50000 12000 6500 25000 10000 COM M 600 1200 1500 DEPTN O 20 30 30 10 20 30 20 ADDRES S nashik nagpur pune mumbai satara pune mumbai amravati

Case 2:

Case 3:

Note- The above rows of data should be inserted in the emp table, since succeeding queries are based on this data. Select command It is used to access the inserted data in the table. Syntax: select column_name1, ,column_name n from <table_name> OR select * from <table_name>; Note : Meta character asterisk (*) is expanded by Oracle to mean all columns in the table.Once data has been inserted into a table we can view what has been entered, with the select command. e.g. To see the contents of table EMP select empno, ename , job, mgr, joindate, salary, comm, deptno, address from emp ; OR select * from emp; Selecting distinct rows To prevent the selection of duplicate rows, we include distinct clause in the select command. e.g. select distinct deptno from emp; Filtering table data While viewing data from a table, it is rare that all the data from the table will be required each time. The retrieval of specific columns from a table Syntax: select column_name1, column_name2, ......, column_name n from <table_name>;

e.g. To select only the ENAME & EMPNO columns from the EMP table,folllowing command is used. select empno, ename from emp; To retrieve selected rows & all columns from a table: ORACLE provides the option of using a WHERE clause in an SQL sentence to apply a filter on the rows in the table. When a WHERE clause is added to the SQL statement, ORACLE compares each record from the table with the condition specified in the WHERE clause. Only those rows that satisfy the specified condition will be displayed. Syntax: select column_name1, column_name2,....., column_name n from <table_name> where <search_condition>; e.g. To select only those rows from the EMP table where the JOB is analyst, following command is used. select * from emp where job = analyst; Note: The values specified in all the columns of a table are always case sensitive

Update command The update command is used to change or modify data values in a table. Updating of all rows: Syntax: update <table_name> set column_name1 = expression1, column_name2 = expression2,

. . . column_name n = expression n; e.g. To change the commission of employee whose job is clerk, following command is used. update emp set comm = 800 where job = clerk; To see the result, use select command select job, comm from emp; Delete command It is used to delete data (rows) from the table. Removal of all rows: Syntax: delete from <table_name>; Removal of specified rows:It is used to remove specific rows from the table. delete from <table_name> where <search_condition>; e.g To delete an employee whose emp no is 1002, following command is used. delete from emp where empno = 1002; To see whether rows have been deleted from EMP table, use select command. select * from emp; Exercise:-Query for execution:-

1) Create table employee having attributes emp_id,e_name,dept_no,sal job-title. Query:1)Show the emp_id,ename sal for those employee having salary between 2000 to 15000 2)Show the salary of employee whose name contains substring al at the end. 3)Select emp_id,ename,sal from emp_table ordered by salary in ascending order. 4)Update salary for those employee whose salary greater than 5000. 5)To list records of employee working as manager. 6)To list employee records whose name contain alphabet e at fourth position. 7)To list records of employees other than salesman. 8)Delete all records of employee whose name status with letter p

NO. 3
AIM:-To study select form and where clause. Theory:The basic structure of SQL Select:-The select clause corresponds to the projection operation of the relational algebra. It is used to list the attributes desired in the result of the query. From :-From corresponds to the relation of expression. Where:-It consist of the predicate involving attribute of the relation that appears in the from clause. Select a1,a2an From r1,r2,..rn Where p; A1-attribute name R1-relation name p-predicate/condition To use arithmetic, comparison and logical operators in a database. Types of operators: 1. Arithmetic operators. 2. Comparison or Relational operators. 3. Logical operators.

Arithmetic operators
To perform calculations based on number values, we include arithmetic expressions in SQL. An arithmetic expression consists of column names with number datatype and an arithmetic operator connecting them.

Examples: 1. select salary + 2000 from emp; 2. select ename , salary + comm Total Salary from emp where deptno = 20; Note: 1. 2. * and / have equal higher precedence. + and have equal lower precedence.

The following example illustrates the precedence of operators. e.g. select 1.5 * (salary + comm) from emp; In the above example, the result obtained from adding commission to salary is multiplied by 1.5 Note: If parenthesis is omitted, then multiplication will be performed first followed by addition.

Comparison or Relational Operators


Comparison operators are used in conditions to compare one expression with another. Comparison operators are listed as below: Operator = > >= < <= <> != Meaning Equal to Greater than Greater than or equal to Less than Less than or equal to Not equal to Not equal to

Examples: 1) Display the list of employees whose job is analyst. select * from emp where job = analyst; 2) Display the list of employees whose salary is more or equal to 20000. select * from emp where salary >= 20000 ; 3) Display the list of employees whose salary is less than 5000.

select ename,job,salary from emp where salary <5000; 4) Display the list of employees excluding job title as salesman. select * from emp where job != salesman;

Logical operators
A logical operator is used to combine the results of two conditions to produce a single result. AND operator It is used to combine the result of two conditions and both the conditions must be true for the entire condition to be true. Examples:Display the list of employees whose salary is between 5000 and 20000. select * from emp where salary>= 5000 and salary <= 20000; 1) Display the list of employees whose joining date is between 01-apr-1995 and 10-sep- 1996. select * from emp where joindate >= 01-apr-1995 and joindate <= 10-sep-1996; OR operator It is used to combine the result of two conditions and if one of the condition is true, then entire condition is true. Examples: 1) Display the list of employees whose manager is 1003 or department is 30. select * from emp where mgr = 1003 or deptno = 30; 2) Display the list of employees who belongs to department 10 or 30. select * from emp where deptno = 10 or deptno=30;

NOT operator It is a negative of a single condition. Examples: 1) Display the list of employees whose salary is not less than 5000. select * from emp where not salary < 5000 ; 2) Display the list of employees except job title as Manager. select * from emp where not (job = manager); Order by clause The Order by clause is used to arrange the records in ascending or descending order. Syntax : select <expr> from <table_name> [where condition (s)] [order by {column, expr} [asc | desc ]]; where order by - specifies the order in which the rows are displayed. asc - orders the rows in ascending order. This is the default order. desc - orders the rows in descending order. e.g. i. select ename, job, deptno, joindate from emp order by joindate desc; ii. iii. iv. Query:select * from emp order by empno; select * from emp order by empno, ename; select * from emp order by empno, ename desc;

Create table employee having field name emp_id,emp_name,email,phone_no,joining_date,job_id,salary & department_id where emp_id,emp_name,email joining,job_id have not null value. 1)Display structure of table 2)Insert at least 10 records into the table. 3)Delete from employee where emp_name start wiyh letter p. 4)Give increment of rs 500 in salary of those employee whose salary is greater than 3000 & less than 5000. 5)Add new column manager_id having type character & size of 10 into table. 6)change type and size of manager_id by using alter command as number & size of 6. 7)Delete complete table using drop commond.

NO-4 Aim:-To study aggregate functions & numeric functions. Theory:Group functions
A group function returns a result based on a group of rows. The group functions are listed below: 1. Avg - It returns the average value of the specified column of number datatype. Format: - avg (column_name) e.g. select avg (salary) from emp; 2. Sum - It returns the summation of the specified column of number datatype. Format: - sum (column_name) e.g. select sum (salary) from emp; 3. Min - It returns the lowest value from the specified column of number datatype. Format: - min (column_name) e.g. select min(salary) from emp;

4. Max - It returns the highest value of the specified column of number


datatype. Format: - max (column_name) e.g. select max (salary) from emp;

5. Count - Count function is used to count the number of rows.


Count (*) - It counts all rows, inclusive of duplicate and nulls. e.g. select count (*) from emp; Count (column_name)

It is used to count the number of values present in the specified column without including nulls. e.g. select count (comm) from emp; Count (distinct column_name) It is used to eliminate the duplicate and null values in the specified column. e.g. select count (distinct deptno) from emp; Numeric Functions Numeric function accepts the numeric value as the input and it returns the numeric values as the output. The numeric functions are as follows.

1. Abs - It returns the absolute value of the number.


Format:- abs(n) where n is number. e.g. select abs(-15) from dual;

1. Cos - It returns cosine of the number.


Format: - cos(n) e.g. select cos(180) from dual;

2. Cosh - It returns the hyperbolic cosine of the number.


Format: - cosh (n) e.g. select cosh(1) from dual;

3. Sin It returns sine of the number.


Format:- sin(n) e.g. Select sin(90) from dual;

4. Sinh It returns hyperbolic sine of the number.


Format:- sinh(n)

e.g. Select sinh(1) from dual;

5. Tan It returns tangent value of the number.


Format:- tan(n) e.g. Select tan(90) from dual; Exp - It returns the e raised to the power of the number. Format: - exp(n) e.g. select exp(4) from dual;

6. Ceil - It returns the smallest integer that is larger than the number.
Format: - ceil (n) e.g. select ceil(44.778) from dual;

7. Floor - It returns the largest integer that is smaller than the number.
Format: - floor(n) e.g. select floor(100.2) from dual;

8. Round - It will round m to n number of digits after the decimal point.


Format: - round(m,n) where m - is number n- is number of digits after decimal point e.g. select round (100.256,2) from dual;

9. Trunc - It truncates m to n places after the decimal point.


Format: - trunc(m,n) where m is number n is no of digits after decimal point.

e.g. select trunc (100.256,2) from dual;

10. Power - It returns m raised to the n power.


Format: - power(m,n) where m,n are numbers. e.g. select power(5,2) from dual;

11. Mod - It returns the remainder when m is divided by n.


where m,n are numbers. e.g. select mod(10,3) from dual;

12. Sqrt - It returns the positive square root of a positive number.


Format: - sqrt(n) e.g. select sqrt(4) from dual;

Query for execution:1)Find the average of salary from emp relation. 2)Find the minimum & maximum salary from emp relation. 3)Calculate the sum of the salary. 4)Count the number of employee from emp relation. 5)Count the number of employee whose job is manager 6)To count the number of employee whose commission is NULL.

NO. 5
AIM:-To Study Set Operators in a database, And use of TCL command in SQL. Theory:Types of Set Operators: Union Union all Intersect Minus Rules for using Set Operators: 1. The queries, which are related by a set operator should have the same number of columns and the corresponding columns, must be of the same datatype. 2. A query should not contain any column of type long.

Union
The Union operator returns all distinct rows selected by both queries. e.g select deptno from emp union select deptno from dept; The above ex. returns all distinct column values from the emp and dept table respectively i.e. it eliminates duplicate rows. Union all The 'union all' operator returns all rows selected by either query including duplicates. i.e. it does not eliminate duplicate rows. e.g. select deptno from emp union all select deptno from dept; Note:

It is not necessary that the columns in the two select statements be the same but the datatype must necessarily match. Intersect Intersect operator returns only rows that are common to both the queries. e.g. select deptno from emp intersect select deptno from dept; Minus Minus operator returns all distinct rows selected by the first query and not by the second. e.g. 1 select deptno from dept minus select deptno from emp; e.g. 2 select deptno from emp minus select deptno from dept; The result of the above query will be rows selected by the first statement except those common to the statement following the minus operator. TCL command:TCL is a transaction control language command.All changes make to the database can be refer to as transaction.Transaction changes can be make permanent to the database only if they are committed. TCL commands are:1)COMMIT:-This command is used to end the transaction.Only with the help of the commit command transaction changes can be make perment to the database.This command also causes all the save points in the transaction thus,releasing the transaction lock(save point). Syntax:-SQL>COMMIT 2)SAVEPOINT:- Savepoint are like the markers to divide a very lengthy transaction to smaller ones.They are used to identify a point in a transaction to which we can later Roll

back.Thus,savepoint is used in conjuction with a rollback to rollback portions of the current transaction. Syntax:-SQL> SAVEPOINT; SQL>SAVEPOINT s1; 3)ROLLBACK:-A rollback command is used to undo the work done in the current transaction.We can rollback the entire transaction so that the changes made by the sql statement are undone or rollback a transaction to a savepoint so the SQL statement after the savepoint is rollback. Syntax:-SQL>Rollback; To rollback a particular point in the transaction i.e. a savepoint Syntax:-SQL>Rollback to savepoint save point; Query for Execution:-

NO-6 Aim:-To study different set membership & clauses of SQL. Theory:- following are the set membership operator
1) 2) 3) 4) IN, NOT IN LIKE, NOT LIKE BETWEEN, NOT BETWEEN IS NULL , IS NOT NULL

IN and NOT IN Predicates


In case a value needs to be compare to a list of values, then the IN/NOT IN predicate is used. We can check a single value against multiple values by using the IN/NOT IN predicate Syntax : IN

select column_name1, column_name2,.,column_name n from < table_name > where column_name in ( value1,value2,,valuen); e.g. select empno, ename , job from emp where job in ( analyst, clerk); The above example displays employee number, name and job of all employees whose job is analyst or clerk. Syntax: NOT IN

select column_name1, ..,column_name n from < table_name > where column_name not in ( value1 ,..,value n); e.g.

select empno, ename, job from emp where job not in ( salesman, clerk); The above example will display employee number, name and job where the JOB is not a salesman or clerk.

Guidelines:
1 2 1) The IN & NOT IN operators can be used with any datatype. 2) If characters or dates are used in the list, they must be enclosed in single quotation marks ( ). LIKE & NOT LIKE Predicates
Oracle provides a LIKE predicate, which allows comparison of one string with another string value which is not identical. This is achieved by using wildcard characters.

Wild card characters are:


1 2 1) 2) Percent sign (%) :- It matches any string. Underscore ( _ ) :- It matches any single character.

For char data types

Syntax: - LIKE using % (Percentage) select column_name1,column_name2, ,column_name n from < table_name> where column_name like value% ; e.g. select ename, job, salary from emp where ename like ni%; The above example will display all rows from table EMP where employee name begins with ni .

Syntax: -

Like using _ ( underscore )

select column_name1,..,column_name n from < table_name> where column_name like __value% ; e.g. select empno, ename,address from emp where address like _une ; The above example will display all rows where the address starts with any character but ends with une. Syntax: BETWEEN

select column_name1,.,column_name n from < table_name> where column_name between lowerbound and upperbound ; You can display rows based on a range of values using BETWEEN operator. The range that you specify contains a lower bound and upper bound. e.g. select ename,salary,comm from emp where comm between 1000 and 3000; Syntax :NOT BETWEEN

select column_name1,..,column_name n from < table_name> where column_name not between lowerbound and upperbound; e.g. select ename, salary, comm from emp where comm not between 1000 and 3000; Guidelines: 1) Values specified with the BETWEEN operator are inclusive. 2) You must specify the lower limit first.

Syntax :-

IS NULL select column_name1,,column_name n from < table _name > where column_name is null;

The IS NULL Operator tests for values that are null. A null value means the value is unavailable , unassigned, unknown, unequal to any value or zero length string. e.g. Display the details of employees whose commission is null. select empno, ename,mgr, job from emp where comm is null; Syntax:IS NOT NULL select column_name1,,column_name n from< table_name> where column_name is not null; e.g. select empno, ename, mgr, job from emp where comm is not null; Different types of clauses 1)Order by clause 2)Group by clause 3)Having clause Order by clause The Order by clause is used to arrange the records in ascending or descending order. Syntax : select <expr> from <table_name> [where condition (s)]

[order by {column, expr} [asc | desc ]]; where order by - specifies the order in which the rows are displayed. asc - orders the rows in ascending order. This is the default order. desc - orders the rows in descending order. e.g. i. select ename, job, deptno, joindate from emp order by joindate desc; ii. iii. iv. select * from emp order by empno; select * from emp order by empno, ename; select * from emp order by empno, ename desc;

Group by
The GROUP BY clause can be used to divide the rows in a table into groups. We can then use the group functions to return summary information for each group. Syntax: select column, group_function (column) from <table_name> [where condition] [group by group_by_expression] [order by column]; where Group by expression - specifies columns whose values determine the basis for grouping rows. e.g. select deptno, avg (salary) from emp group by deptno; Note : avg (sal) is a group function which calculates the average salary for each department since the rows are being grouped by department number. Using Group By clause on single column.

e.g. select avg (salary) from emp group by deptno; Example: Using Group by clause on multiple columns. e.g. select deptno, job, sum(salary) from emp group by deptno, job; First the rows are grouped by department number. Second, within the department number groups, the rows are grouped by job title.

Having clause
HAVING clause is used to specify which groups are to be displayed. Syntax: select column, group_function from table [where condition] [group by group_by_expression] [having group_condition] [order by column]; where group condition - restricts the groups of rows returned to those groups for which the specified condition is TRUE. The Oracle server performs the following steps when you use the HAVING clause. 1. Rows are grouped. 2. The group function is applied to the group. 3. The groups that match the criteria in the HAVING clause are displayed. e.g. select deptno, max (salary) from emp group by deptno having max (salary) > 10000;

Query for Execution:1)To find customer name who have a loan at the bank but do not have an account at the bank. 2)select names of customer who have a loan at the bank whose names are neither smith nor jones. 3)finding employee names the cities they live in and working in company ACC using IN. 4)Display the names of employee living in the same city where SUNIL is residing. 5)compute the average salary of proffessors,Research follow and office assistants.

No.-7 Aim:-To study View in SQL. Theory:View:- SQL CREATE VIEW Statement
In SQL, a view is a virtual table based on the result-set of an SQL statement. A view contains rows and columns, just like a real table. The fields in a view are fields from one or more real tables in the database. You can add SQL functions, WHERE, and JOIN statements to a view and present the data as if the data were coming from one single table. SQL CREATE VIEW Syntax CREATE VIEW view_name AS SELECT column_name(s) FROM table_name WHERE condition Note: A view always shows up-to-date data! The database engine recreates the data, using the view's SQL statement, every time a user queries a view.

Creating Simple view i.e. from single table SQL>Create or replace view emp_view as Select empno,ename,job,sal deptno From emp; Perform<DML>operation on a view i.e.insert,update,delete Note down the result and different effect on base table i.e. emp SQL>Create or replace view emp_view1 as Select ename,job,sal,deptno from emp;

Though this is also simple view still test the <DML>operation on it. Insert operation cannot perform on this view because not null column<empno> is not added in view definition <empno>is primary key and we cannot insert null to primary key. SQL>Create or replace view emp_view 3 as Select empno,ename,job,sal abs(sal) From emp; This view is also based on a single table i.e. emp

Creating complex view When a view based on more than one table or any function operated on any column then view is called as complex view. e.g. SQL>Create or replace view emp_view 4 as Select a.empno,a.ename,a,sal,a.job,a.deptno,b.city from emp a,dept b where a.deptno=b.deptno. Perform all DML operation on this view and note the result Check whether the information about the view found in by writing Select * from User_views;
SQL Dropping a View You can delete a view with the DROP VIEW command. SQL DROP VIEW Syntax DROP VIEW view_name

Question: Can you update the data in a view? Answer: A view is created by joining one or more tables. When you update record(s) in a view, it updates the records in the underlying tables that make up the view. So, yes, you can update the data in a view providing you have the proper privileges to the underlying tables. Question: Does the view exist if the table is dropped from the database? Answer: Yes, in Oracle, the view continues to exist even after one of the tables (that the view is based on) is dropped from the database. However, if you try to query the view after the table has been dropped, you will receive a message indicating that the view has errors.

QUERY FOR EXECUTION:1)Create simple view 2)check DML command on simple view 3)Create complex view 4)Check DML command on complex view

NO-8
AIM:-To study different types of Joins. THEORY:-

Join is used to combine the data spread across tables. A join is performed by the 'where' clause which combines the specified rows of tables. Types of Joins i ii iii iv Equi - join Non equi-join Self Join Outer Join

Equi -join
A join, which is based on equalities, is called equi-join. In equi-join comparison operator equal to (=) is used to perform a join. It retrieves rows from tables having a common column. It is also called simple join. Syntax : select table1.column , table1.column, table2.column,., from table1, table2 where table1.column1 = table2.column2; e.g Select emp.empno,emp.ename,emp.deptno, dept.deptno,dept.loc from emp,dept where emp.deptno = dept.deptno;

Guidelines:
1. Rows in one table can be joined to rows in another table according to the common values existing in corresponding columns, that are usually primary and foreign key columns. 2. When writing a select statement that joins tables, precede the column name with the table name. (e.g. dept.deptno) 3. If the same column name appears in more than one table, the column name must be prefixed the table name. (e.g. dept.deptno, emp.deptno) 4. If the column names are unique, then we need not prefix it with the table name. Table aliases Table aliases are used to make multiple table queries shorter and more readable. As a result, we give an alias name or short name to the table in the 'from' clause. The alias can be used instead of the table name throughout the query.

Syntax : e.g. select e.empno, e.ename, e.deptno, d.deptno, d.loc from emp e, dept d where e.deptno = d.deptno; Note: - The above example is same as example of equi join but uses table aliases where 'e' refers to emp table and 'd' refers to dept table. Non equi-join A join that specifies the relationship between columns belonging to different tables by making use of the relational operators (<, >, <=, >=, ! =) other than '=' operator is called as non equi-join. To use non equi-join create the following table. Table - Salgrade Column-name Grade Losal Hisal Datatype Number (4) Number (8) Number (8)

Note - Students will insert the following records in a given table. GRADE --------1 2 3 4 5 LOSAL --------700 1201 1401 2001 3001 HISAL --------1200 1400 2000 3000 9999

To relate emp and salgrade tables using non-equi join. e.g select e.ename, e.salary, s.grade from emp e, salgrade s where e.salary between s.losal and s.hisal;

OR select e.ename, e.salary, s.grade from emp e, salgrade s where e.salary >= s.losal and e.salary <= s.hisal; Self join Joining of a table to itself is known as self join. i.e. 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. e.g. To find the name of each employee's manager you need to join EMP table to itself. select worker.ename "employee", manager.ename "manager" from emp worker, emp manager where worker.mgr = manager.empno; Note: The above example joins the emp table to itself. To stimulate two tables in the FROM clause, there are two aliases, namely WORKER and MANAGER, for the same table, EMP. Outer Join An outer join returns all the rows returned by simple join or equi join as well as those rows from one table that do not match any row from the other table. The symbol (+) represents outer join. Syntax: Case 1 select table.column, table.column from table1,table2 where table1.column (+) = table2.column; select table.column, table.column from table1, table2 where table1.column = table2.column (+); select e.ename, d.deptno, d.dname from emp e, dept d where e.deptno (+) = d.deptno

Case 2

e.g

order by e.deptno; he above example displays numbers and names for all the departments. The operations department, which does not have any employees, is also displayed. Guidelines : 1. The outer join operator can appear only on one side of the expression. The side that has information missing. It returns those rows from one table that has no direct match in the other table. 2. A condition involving an outer join cannot use the IN operator or be linked to another condition by the OR operator.

Query for execution:-

NO-9
AIM:-To study PL/SQL Programming in SQL. THEORY:-

Definition of: PL/SQL (Procedural Language/SQL) A programming language from Oracle that is used to write triggers and stored procedures that are executed by the Oracle DBMS. It is also used to add additional processing (sorting and other manipulation) of the data that has been returned by the SQL query. A PL/SQL program is structured as a "block," which is made up of declaration, executable commands and exception handling sections.

Write a program to print sum and average of any 3 number. Solution:- Declare N1 number(5); N2 number(5); N3 number(5); sum number(5); average number(5); begin N1:=&number; N2:=&number; N3:=&number; Sum= N1+N2+N3; Average= Sum/3; Dbms_output.put_line(sum || is the sum of no.); Dbms_output.put_line(average || is the average of no.); End;

2)Write a program to calculate the greast no between two nos. 3)Write a program to swap two no.

New concepts:
3.1 3.2 Topic : Additional Comparison operators Propositions :

Proposition1: - Range searching It is used to select data that is within a range of values Proposition 2: - Pattern matching In order to allows comparison of one string with another string value which is not identical.

4.0

Title Of The :
To use Comparison operators in ORACLE for range searching and pattern matching of table data.

Information Input:
5.1 New Information: Comparison Operators : 5) 6) 7) 8) 9) IN, NOT IN LIKE, NOT LIKE BETWEEN, NOT BETWEEN IS NULL , IS NOT NULL ANY, ALL

IN and NOT IN Predicates


In case a value needs to be compare to a list of values, then the IN/NOT IN predicate is used. We can check a single value against multiple values by using the IN/NOT IN predicate

Syntax : -

IN

select column_name1, column_name2,.,column_name n from < table_name > where column_name in ( value1,value2,,valuen); e.g. select empno, ename , job from emp where job in ( analyst, clerk); The above example displays employee number, name and job of all employees whose job is analyst or clerk. Syntax: NOT IN

select column_name1, ..,column_name n from < table_name > where column_name not in ( value1 ,..,value n); e.g. select empno, ename, job from emp where job not in ( salesman, clerk); The above example will display employee number, name and job where the JOB is not a salesman or clerk.

Guidelines:
3 4 1) The IN & NOT IN operators can be used with any datatype. 2) If characters or dates are used in the list, they must be enclosed in single quotation marks ( ). LIKE & NOT LIKE Predicates
Oracle provides a LIKE predicate, which allows comparison of one string with another string value which is not identical. This is achieved by using wildcard characters.

Wild card characters are:


3 4 1) 2) Percent sign (%) :- It matches any string. Underscore ( _ ) :- It matches any single character.

For char data types

Syntax: - LIKE using % (Percentage) select column_name1,column_name2, ,column_name n from < table_name> where column_name like value% ; e.g. select ename, job, salary from emp where ename like ni%; The above example will display all rows from table EMP where employee name begins with ni . Syntax: Like using _ ( underscore )

select column_name1,..,column_name n from < table_name> where column_name like __value% ; e.g. select empno, ename,address from emp where address like _une ; The above example will display all rows where the address starts with any character but ends with une. Syntax: BETWEEN

select column_name1,.,column_name n from < table_name>

where column_name between lowerbound and upperbound ; You can display rows based on a range of values using BETWEEN operator. The range that you specify contains a lower bound and upper bound. e.g. select ename,salary,comm from emp where comm between 1000 and 3000; Syntax :NOT BETWEEN

select column_name1,..,column_name n from < table_name> where column_name not between lowerbound and upperbound; e.g. select ename, salary, comm from emp where comm not between 1000 and 3000;

Guidelines: 3) Values specified with the BETWEEN operator are inclusive. 4) You must specify the lower limit first. Syntax :IS NULL select column_name1,,column_name n from < table _name > where column_name is null; The IS NULL Operator tests for values that are null. A null value means the value is unavailable , unassigned, unknown, unequal to any value or zero length string. e.g. Display the details of employees whose commission is null.

select empno, ename,mgr, job from emp where comm is null;

Syntax:-

IS NOT NULL

select column_name1,,column_name n from< table_name> where column_name is not null; e.g. select empno, ename, mgr, job from emp where comm is not null; ANY Operator The ANY operator compares a value to each value returned by a subquery. < ANY means less than the maximum. >ANY means more than the minimum. = ANY is equivalent to IN. ALL Operator The all operator compares a value to every value returned by a subquery. >ALL means more than the maximum. < ALL means less than the minimum.
Note:

ANY and ALL operators are covered in the subquery topic. 3.1 3.2 3.3

Topic : Single row functions (Numeric functions).

Title of the :
To use SQL Numeric functions in a database.

5.0

Information Input:
5.1 New Information :

Numeric Functions
Numeric function accepts the numeric value as the input and it returns the numeric values as the output. The numeric functions are as follows. 13. Abs - It returns the absolute value of the number. Format:- abs(n) where n is number. e.g. select abs(-15) from dual;

14. Cos - It returns cosine of the number. Format: - cos(n)

e.g. select cos(180) from dual; 15. Cosh - It returns the hyperbolic cosine of the number. Format: - cosh (n) e.g. select cosh(1) from dual; 16. Sin It returns sine of the number. Format:- sin(n) e.g. Select sin(90) from dual; 17. Sinh It returns hyperbolic sine of the number. Format:- sinh(n) e.g. Select sinh(1) from dual; 18. Tan It returns tangent value of the number. Format:- tan(n) e.g. Select tan(90) from dual;

19. Exp - It returns the e raised to the power of the number.

Format: - exp(n) e.g. select exp(4) from dual; 20. Ceil - It returns the smallest integer that is larger than the number. Format: - ceil (n) e.g. select ceil(44.778) from dual; 21. Floor - It returns the largest integer that is smaller than the number. Format: - floor(n) e.g. select floor(100.2) from dual; 22. Round - It will round m to n number of digits after the decimal point. Format: - round(m,n) where m - is number n- is number of digits after decimal point e.g. select round (100.256,2) from dual; 23. Trunc - It truncates m to n places after the decimal point. Format: - trunc(m,n) where m is number n is no of digits after decimal point. e.g. select trunc (100.256,2) from dual;

24. Power - It returns m raised to the n power. Format: - power(m,n) where m,n are numbers. e.g. select power(5,2) from dual; 25. Mod - It returns the remainder when m is divided by n. where m,n are numbers. e.g. select mod(10,3) from dual; 26. Sqrt - It returns the positive square root of a positive number. Format: - sqrt(n) e.g. select sqrt(4) from dual;

3.1

Topic : Group functions

1.0

Title of :
To use group functions in a database.

2.0

Information Input:
5.1 New Information: Group functions A group function returns a result based on a group of rows. The group functions are listed below: 1. Avg - It returns the average value of the specified column of number

datatype. Format: - avg (column_name) e.g. select avg (salary) from emp;

2. Sum - It returns the summation of the specified column of number datatype. Format: - sum (column_name) e.g. select sum (salary) from emp; 3. Min - It returns the lowest value from the specified column of number datatype. Format: - min (column_name) e.g. select min(salary) from emp; 6. Max - It returns the highest value of the specified column of number datatype. Format: - max (column_name) e.g. select max (salary) from emp; 7. Count - Count function is used to count the number of rows. Count (*) - It counts all rows, inclusive of duplicate and nulls. e.g. select count (*) from emp; Count (column_name)

It is used to count the number of values present in the specified column without including nulls. e.g. select count (comm) from emp;

Count (distinct column_name) It is used to eliminate the duplicate and null values in the specified column. e.g. select count (distinct deptno) from emp;

1.0

New concepts:
3.1 Topic : Clauses

2.0 Title of the :


To use Order By, Group By and Having clause in a database. 5.0

Information input
5.1 New Information : Types of Clauses:1. Order by clause 2. Group by clause 3. Having clause Order by clause The Order by clause is used to arrange the records in ascending or descending order. Syntax : select <expr> from <table_name> [where condition (s)] [order by {column, expr} [asc | desc ]]; where order by - specifies the order in which the rows are displayed.

asc - orders the rows in ascending order. This is the default order. desc - orders the rows in descending order. e.g. i. select ename, job, deptno, joindate from emp order by joindate desc; ii. iii. iv. select * from emp order by empno; select * from emp order by empno, ename; select * from emp order by empno, ename desc;

Guidelines: 1. The ORDER BY clause should be placed last in the query. 2. The default sort order is ascending. Sorting by column aliases: You can use a column alias in the ORDER BY clause. e.g. select empno, ename, salary*12 annsal from emp order by annsal; The above example sorts the result by the alias "annsal" which represents the annual salary. Note: You can sort query results by more than one column. The sort limit is the number of columns in the given table. Column alias can be given any name. e.g. select ename, salary *12 "Annual Salary" from emp order by ename;

Group by
The GROUP BY clause can be used to divide the rows in a table into groups. We can then use the group functions to return summary information for each group. Syntax: select column, group_function (column) from <table_name> [where condition] [group by group_by_expression] [order by column]; where Group by expression - specifies columns whose values determine the basis for grouping rows. e.g. select deptno, avg (salary) from emp group by deptno; Note : avg (sal) is a group function which calculates the average salary for each department since the rows are being grouped by department number. Using Group By clause on single column. e.g. select avg (salary) from emp group by deptno; Example: Using Group by clause on multiple columns. e.g. select deptno, job, sum(salary) from emp group by deptno, job; First the rows are grouped by department number. Second, within the department number groups, the rows are grouped by job title.

Having clause
HAVING clause is used to specify which groups are to be displayed. Syntax: select column, group_function from table [where condition] [group by group_by_expression] [having group_condition] [order by column]; where group condition - restricts the groups of rows returned to those groups for which the specified condition is TRUE. The Oracle server performs the following steps when you use the HAVING clause. 4. Rows are grouped. 5. The group function is applied to the group. 6. The groups that match the criteria in the HAVING clause are displayed. e.g. select deptno, max (salary) from emp group by deptno having max (salary) > 10000; Guidelines: 1. If you include group function in a SELECT clause, you cannot select individual results as well unless the individual column appears in the GROUP BY clause. Any column or expression in the SELECT list that is not an aggregate function must be in GROUP BY clause. 2. You cannot use the column alias in the GROUP BY clause. 3. By default rows are sorted by ascending order of the columns included in the Group By clause. 4. You cannot use the WHERE clause to restrict groups. 5. You use the Having clause to restrict groups. 6. The HAVING clause can precede the GROUP BY clause, but it is recommended that you place the GROUP BY clause first because it is more logical.

6.0

Lab Exercise:
1. Display the average salaries for each department.

2. Display all the employee information in the ascending order of joining date.

3. Display the minimum, maximum, sum and average salary for each job type.

4. Write a query to display the number of people with the same job.

Data Manipulation Language (DML)

1.0

New Concepts:
3.1 3.2 Topic : Set Operators Propositions: Proposition1: Set Operator Set operators combine the results of two Queries into a single one.

NO. 5
AIM:-To Study Set Operators in a database.

Theory:-

Types of Set Operators: Union Union all Intersect Minus

Rules for using Set Operators: 3. The queries, which are related by a set operator should have the same number of columns and the corresponding columns, must be of the same datatype. 4. A query should not contain any column of type long.

Union
The Union operator returns all distinct rows selected by both queries. e.g select deptno from emp union select deptno from dept; The above ex. returns all distinct column values from the emp and dept table respectively i.e. it eliminates duplicate rows. Union all The 'union all' operator returns all rows selected by either query including duplicates. i.e. it does not eliminate duplicate rows. e.g. select deptno from emp union all select deptno from dept; Note: It is not necessary that the columns in the two select statements be the same but the datatype must necessarily match.

Intersect Intersect operator returns only rows that are common to both the queries. e.g. select deptno from emp intersect select deptno from dept; Minus Minus operator returns all distinct rows selected by the first query and not by the second. e.g. 1 select deptno from dept minus select deptno from emp; e.g. 2 select deptno from emp minus select deptno from dept; The result of the above query will be rows selected by the first statement except those common to the statement following the minus operator.

Query for Execution:-

1.0

Prior Concepts:
Data Manipulation Language, Operators in SQL, Functions in SQL.

2.0

New Concepts:
3.1 3.2 Topic : Joins Propositions:

Proposition1: - Join Join is used to combine the data spread across tables. A join is performed by the 'where' clause which combines the specified rows of tables.

3.0

Title of the :
To relate data through Join concept in a database.

4.0

New Information:
5.1 New Information: Types of Joins i ii iii iv Equi - join Non equi-join Self Join Outer Join

Equi -join
A join, which is based on equalities, is called equi-join. In equi-join comparison operator equal to (=) is used to perform a join. It retrieves rows from tables having a common column. It is also called simple join. Syntax : select table1.column , table1.column, table2.column,., from table1, table2 where table1.column1 = table2.column2; e.g Select emp.empno,emp.ename,emp.deptno, dept.deptno,dept.loc from emp,dept where emp.deptno = dept.deptno;

Guidelines:
5. Rows in one table can be joined to rows in another table according to the common values existing in corresponding columns, that are usually primary and foreign key columns. 6. When writing a select statement that joins tables, precede the column name with the table name. (e.g. dept.deptno) 7. If the same column name appears in more than one table, the column name must be prefixed the table name. (e.g. dept.deptno, emp.deptno) 8. If the column names are unique, then we need not prefix it with the table name. Table aliases Table aliases are used to make multiple table queries shorter and more readable. As a result, we give an alias name or short name to the table in the 'from' clause. The alias can be used instead of the table name throughout the query. Syntax : e.g. select e.empno, e.ename, e.deptno, d.deptno, d.loc from emp e, dept d where e.deptno = d.deptno; Note: - The above example is same as example of equi join but uses table aliases where 'e' refers to emp table and 'd' refers to dept table. Non equi-join A join that specifies the relationship between columns belonging to different tables by making use of the relational operators (<, >, <=, >=, ! =) other than '=' operator is called as non equi-join. To use non equi-join create the following table. Table - Salgrade Column-name Datatype

Grade Losal Hisal

Number (4) Number (8) Number (8)

Note - Students will insert the following records in a given table. GRADE --------1 2 3 4 5 LOSAL --------700 1201 1401 2001 3001 HISAL --------1200 1400 2000 3000 9999

To relate emp and salgrade tables using non-equi join. e.g select e.ename, e.salary, s.grade from emp e, salgrade s where e.salary between s.losal and s.hisal; OR select e.ename, e.salary, s.grade from emp e, salgrade s where e.salary >= s.losal and e.salary <= s.hisal;

Self join Joining of a table to itself is known as self join. i.e. 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. e.g. To find the name of each employee's manager you need to join EMP table to itself. select worker.ename "employee", manager.ename "manager" from emp worker, emp manager where worker.mgr = manager.empno;

Note: The above example joins the emp table to itself. To stimulate two tables in the FROM clause, there are two aliases, namely WORKER and MANAGER, for the same table, EMP. Outer Join An outer join returns all the rows returned by simple join or equi join as well as those rows from one table that do not match any row from the other table. The symbol (+) represents outer join. Syntax: Case 1 select table.column, table.column from table1,table2 where table1.column (+) = table2.column; select table.column, table.column from table1, table2 where table1.column = table2.column (+); select e.ename, d.deptno, d.dname from emp e, dept d where e.deptno (+) = d.deptno order by e.deptno;

Case 2

e.g

The above example displays numbers and names for all the departments. The operations department, which does not have any employees, is also displayed. Guidelines : 3. The outer join operator can appear only on one side of the expression. The side that has information missing. It returns those rows from one table that has no direct match in the other table. 4. A condition involving an outer join cannot use the IN operator or be linked to another condition by the OR operator.

6.0

Lab Exercise:

1. Display employee Nikhils employee number, name, department number, and department location.

2. Display the list of employees who work in the sales department.

3. Display the list of employees who do not work in the sales department.

4. Display the employee name and salary of all employees who report to Sumit Patil.

DCL:Data control language command It provides users with privilege commands.The owner of the database has the sole authority over them.The owner can allow other database users access to the object as per his/her description.Granting privilages(Insert,select,etc.) to other allows them to perform operation within their privilages per view. 1)GRANT privilege Command:-

Syntax:SQL>GRANT<privilages>an<object>to<user name>; Objects are logical data storage structure like tables,view,sequence,index,synonyms etc. e.g.SQL>GRANT SELECT<UPDATE ON ORDER master to warehouse; we can also specify all to grant all the privilages

Vous aimerez peut-être aussi