Top Banner

of 37

DBMS Package For Class Project

Apr 09, 2018

Download

Documents

Sushil Saini
Welcome message from author
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
  • 8/7/2019 DBMS Package For Class Project

    1/37

    DBMS Package For Class Project

    All database System store the user data in the form of a table. A table isreally a two dimensional matrix that consist of rows and columns. Eachcolumn consists a cell, cell is also called a field. A no. of field placed inhorizontal row is called a record. By creating record and then table, theuser can store and maintain data. This chapter is concerned with the way

    by which any user can create and manipulate the data.

    12.1 Data Types in Oracle

    o CHAR: Values of this Datatype are final length character strings of maximum length 255 characters.

    o VARCHAR/VARCHAR2: Values of this Datatype of variable lengthcharacter strings of maximum length 2000.

    o NUMBER: The NUMBER Datatype is used to store numbers (fixed or floating point). Numbers of virtually any magnitude may be stored up to 30 digitsof precision. Number as large as 9.99*10 to the power of 124 i.e. 1 followed by 125zeros can be stored.

    o DATE: The standard format is DD-MM-YY as in 13-DEC-99. To enter dates other than the standard forma t, use the appropriate functions. Date timestores date in the 24-hour format. By default, the time in a date field is 12: 00: 00am, if no time portion is specified. The default date for a date field is the f irst dayof the current mon th.

    o LONG: It is used when variable length character strings commit off 65, 535characters.

    12.2 DDL Commands

    1. CREATE TABLESyntax: CREATE TABLE tablename (Columname datatype(size),

    column name datatype (size) ; Examp le

    1

  • 8/7/2019 DBMS Package For Class Project

    2/37

    For Example:

    1. Create client_master table where

    Column Name Data Type Size

    client_no Varchar 2 6

    name Varchar 2 20

    address Varchar 2 30

    city Varchar 2 15

    state Varchar 2 15

    pincode number 6

    balance_due number 10,2

    SQL>Create table client_master (client_no varchar2(6), name varchar2(20), addressvarchar2(30), city varchar2(15), state varchar2(15), pincode number(6), balance_duenumber(10,2));

    2. Create product_master table where

    Column Name Data Type S ize

    Product_no Varchar 2 6

    Description Varchar 2 20

    Profit_percent Number 2, 2

    2

  • 8/7/2019 DBMS Package For Class Project

    3/37

    Unit_measure` Varchar 2 10

    Qty_on_hand Number 8

    Sell_price Number 8, 2

    Cost_price Number 8, 2

    SQL>Create table product_master (Product_no varchar2(6),Descriptionvarchar2(20),Profit_percent number(2,2),Unit_measure varchar2(10),Qty_on_handnumber(8),Sell_price number(8,2),Cost_price number(8,2));

    Creating a table from another table

    Syntax:

    CREATE TABLE tablename [(columnname, columnname)] AS SELECT columnname,columnname from

    tablename;

    For Example:

    CREATE TABLE s1 AS SELECT * from client_master;

    Displaying Description of TableSyntax:

    desc tablename;For example:

    3

  • 8/7/2019 DBMS Package For Class Project

    4/37

    2. ALTER TABLE Syntax:

    ALTER TABLE existing_table_name MODIFY (columnnamenewdatatype(size));

    For Example:

    SQL>ALTER TABLE Product_master MODIFY (Description varchar2(25));

    And if we have an EMP table with EmpNo as a one filed in the table and we want to add primary key constraint on EmpNo then we use ALTER command as following way:

    SQL>ALTER TABLE EMP ADD CONSTRAINT Pkey1 PRIMARY KEY (EmpNo);Similarly, if we want to drop constraint then

    SQL>ALTER TABLE EMP DROP CONSTRAINT Pkey1;

    3. DROP TABLE

    This command deletes table structure and cannot be recovered.

    Syntax: DROP TABLE tablename;

    For Example:

    SQL> DROP TABLE EMP;

    4. TRUNCATE TABLE

    Syntax: TRUNCATE TABLE tablename;

    12.3 DML Commands

    1. INSERT

    This command is used for inserting data into table.

    Syntax: INSERT INTO tablename VALUES (value1,value2, .);

    4

  • 8/7/2019 DBMS Package For Class Project

    5/37

    Single-row insertion at a time

    SQL>Insert into Client_master Values ('CN2001', 'Deepak Kumar', 'A-5, Patel Nagar','Rohtak', 'Haryana',124001,50000);

    SQL>Insert into Client_master Values ('CN2002', 'Naresh Kumar', '618, Sec- 15', 'Gurgaon','Haryana',122001,25000);

    Inserting one row, many columns at a time

    INSERT INTO tablename (c1,c2, ..) VALUES (value1,value2, ..);

    SQL>Insert into Client_master (Client_no, name, address) Values ('CN2003', 'AlkaSaini',Hansi, Hisar);

    SQL>Insert into Client_master (Client_no, name, address) Values ('CN2004', 'DivyamSaini',Gurgaon);

    Inserting data into table from another table.

    Syntax:

    INSERT INTO tablename (c1,c2, .... ) SELECT columnname, columnname, .... FROMtablename;

    For Example: INSERT INTO NEW_SUPPLIER (name, address)

    SELECT name, address FROM S1;

    Other Examples:

    SQL>Insert into test values (ABC,05-may-80);

    1 row created

    SQL>Insert into test1 values(Hema,25-sept-91,f,c++,25000);

    1 row created

    SQL> Insert into s1 values('&client_no','&name','&address','&city,&state,&pincode,&balance_due);

    2. UPDATE

    5

  • 8/7/2019 DBMS Package For Class Project

    6/37

    Syntax: UPDATE tablename SET columnname =value [WHERE condition];

    For Examples:

    1. SQL>UPDATE S1 SET CITY = KANPUR WHERE client_no=CN2003;

    2. SQL>UPDATE S1 SET balance_due = 2 * balance_due;

    3. DELETE

    Syntax: DELETE FROM tablename WHERE condition;

    For Examples:

    1. DELETE FROM S1 WHERE client_no=CN2003;2. DELETE FROM S1;

    12.4 DCL Commands

    1. COMMIT CommandThe COMMIT command executes a SQL COMMIT command and savechanges for permanent use.

    Syntax:COMMIT;

    SQL>commit;

    Commit complete.

    6

  • 8/7/2019 DBMS Package For Class Project

    7/37

    2. ROLLBACK Command

    This command is used for undo, work done by last command or transaction.

    Syntax:

    1. ROLLBACK TO SAVEPOINT text_identifier;

    2. ROLLBACK;

    SQL>rollback;

    Rollback complete

    3. SAVEPOINT

    This command is used for creating a save point.

    Syntax:

    SAVEPOINT text_identifier;

    Example :a) UPDATE emp

    SET salary = 95000WHERE emp_id=101;

    SAVEPOINT t1;

    UPDATE empSET salary = 100000;

    SAVEPOINT t2;

    SELECT SUM(salary) FROM emp;

    ROLLBACK TO SAVEPOINT t1;

    COMMIT;

    b) SQL>SAVEPOINT t3;

    SQL>delete test;

    2 rows deleted.

    SQL> Rollback to savepoint t3;

    Rollback complete.

    7

  • 8/7/2019 DBMS Package For Class Project

    8/37

    12.5 ORDER BY, GROUP BY, HAVING clause and DISTINCT keyword

    Order by: The order by clause is used to display the results in sorted order i.e. ascending bykeyword asc or descending by keyword desc. By default output displays in ascending order.

    For example:

    SQL> select * from test order by name desc;

    Output:

    ID NAME

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

    2 saini

    1 alka

    SQL> select * from test order by name asc;

    Output:

    ID NAME

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

    1 alka

    2 saini

    Group by : This clause is used along with the SQL aggregate functions like SUM to providemeans of grouping the result. Tuples with the same value on all attributes in the group byclause are placed in one group.

    For example: Suppose a table s2 with following details:

    SQL> select * from s2;

    ID NAME---------- ---------------

    1 alka2 saini

    8

  • 8/7/2019 DBMS Package For Class Project

    9/37

    3 alka4 alka4 alka

    Use of GROUP BY:

    SQL> select name, sum(id) from s2 group by name;Output:

    NAME SUM(ID)--------------- ----------alka 12saini 2

    Having : This clause is used in SQL because the WHERE clause could not be used withaggregate functions. SQL applies conditions in the having clause after groups have been

    formed, so aggregate function be used.For Example:

    SQL> select name, sum(id) from s2 group by name having sum(id) >4;

    NAME SUM(ID)--------------- ----------alka 12

    SQL> select name, sum(id) from s2 group by name having sum(id) < 4;

    NAME SUM(ID)--------------- ----------saini 2

    DISTINCT keyword

    In a table, some of the columns may contain duplicate values. And if you want to displayonly the different or distinct values from the table, then we use the DISTINCT keyword withthe select clause.

    Syntax: Select DISTINCT column_name FROM tablename;

    For example:

    SQL> select DISTINCT name from emp;

    12. 6 Data Constraints

    9

  • 8/7/2019 DBMS Package For Class Project

    10/37

    Primary Key: A primary key constraints is a unique identifier for a rowwith in a database table. Primary key values cannot be null and must beunique across the column.

    For Example:

    Column level constraint: Applied only at one column at a time along with columndefinition.

    SQL>Create table student (RollNo number(6) PRIMARY KEY, SName varchar2(15),Class varchar2(15), Department varchar2(15));

    Table level constraint: Mostly table level constraint is used for multiple column constraint.SQL>Create table student1 (RollNo number(6), SName varchar2(15), Class varchar2(15),

    Department varchar2(15), Mobile varchar2(10), PRIMARY KEY(RollNo,Mobile));

    Add constraint if table already exist:ALTER TABLE tablename ADD PRIMARY KEY (Column_name);

    DROP primary key constraint:ALTER TABLE tablename DROP PRIMARY KEY;

    Foreign Key: A foreign key constraints is a key used to link two tablestogether. A foreign key in one table points to a primary key in anothertable.

    For Example:

    Column level constraint:

    SQL>Create table Marks (RollNo number(6) REFERENCES STUDENT, Subject1varchar2(15), Subject2 varchar2(15), Subject3 varchar2(15));

    Table level constraint:

    SQL>Create table Marks1 (RollNo number(6), Subject1 varchar2(15), Subject2varchar2(15), Subject3 varchar2(15), FOREIGN KEY (RollNo) REFERENCESSTUDENT);

    Add constraint if table already exist:

    ALTER TABLE tablename ADD CONSTRAINT fk FOREIGN KEY (Column_name)REFERENCES primarykeytablename );e.g. SQL> ALTER TABLE Marks1 ADD CONSTRAINT fk FOREIGN KEY (RollNo)REFERENCES STUDENT;

    10

  • 8/7/2019 DBMS Package For Class Project

    11/37

    DROP foreign key constraint:

    ALTER TABLE tablename DROP CONSTRAINT foreignkeyname ;e.g. SQL> ALTER TABLE Marks1 DROP CONSTRAINT fk;

    Unique Key: A Unique key constraints is also a unique identifierfor a row with in a database table. Primary key values cannotbe null but Unique constraint allows only one null value for thespecified field.

    For Example:

    Column level constraint:SQL>Create table Test1 (ID varchar2(6) CONSTRAINT un UNIQUE, name varchar2(15),address varchar2(30), city varchar2(15));

    Table level constraint:SQL>Create table Test2 (ID varchar2(6), name varchar2(15), address varchar2(30), cityvarchar2(15), CONSTRAINT unk UNIQUE(ID) );

    Null Value Constraint: A NOT NULL constraint enforces that the columnwill not accept null values. When a column becomes NOT NULL, then itbecomes mandatory.

    For Example:

    SQL>Create table Test3 (ID varchar2(6) NOT NULL, name varchar2(15), addressvarchar2(30), city varchar2(15));

    CHECK Constraint: A check constraint is used to specify a condition oneach row in a table. A check constraint cannot be defined on a VIEW andcannot include a SUBQUERY .

    For Example:

    Column level constraint:SQL>Create table Test5 (ID varchar2(6), name varchar2(15) CONSTRAINT cn CHECK (name like S%), address varchar2(30), city varchar2(15));

    Table level constraint:

    11

    http://www.techonthenet.com/oracle/subqueries.phphttp://www.techonthenet.com/oracle/subqueries.php
  • 8/7/2019 DBMS Package For Class Project

    12/37

    SQL>Create table Test6 (ID varchar2(6), name varchar2(15), address varchar2(30), cityvarchar2(15), CONSTRAINT cnk CHECK (name like S%));

    DEFAULT Value Constraint: This type of constraint is used when no value issupplied to particular column.

    For Example:SQL>Create table Test7 (ID varchar2(6) PRIMARY KEY, name varchar2(15), addressvarchar2(30) DEFAULT Gurgaon, city varchar2(15));

    12.7 SQL Functions

    Some most usefull function of SQL are:

    1. AVG() FunctionThe AVG() function returns the average value of a numeric filed.

    Syntax: AVG(filedname)Example:

    1. SELECT AVG(OrderPrice) FROM Orders;2. SELECT ename FROM emp WHERE sal>(SELECT AVG(sal)FROM emp);

    2. COUNT() FunctionThis function returns the number of values and NULL values are not counted by thisfunction.

    Syntax: COUNT(filedname)

    Example:

    SELECT COUNT(sal) FROM emp;

    3. MAX() FunctionThis function returns the largest value of the selected column.

    12

  • 8/7/2019 DBMS Package For Class Project

    13/37

    Syntax: MAX(filedname)

    Example:

    SELECT MAX(sal) FROM emp;

    4. MIN() FunctionThis function returns the smallest value of the selected column.

    Syntax: MIN(filedname)

    Example:

    SELECT MIN(sal) FROM emp;

    5. SUM() FunctionThis function returns the total sum of a column but column must be numeric.

    Syntax: SUM(filedname)

    Example:

    SELECT SUM(sal) FROM emp;

    6. UPPER() FunctionThis function converts the value of a field to uppercase.

    Syntax: UPPER (filedname)

    Example:

    SELECT UPPER (name) FROM emp;

    SELECT UPPER (dbms) FROM dual;

    7. LOWER () FunctionThis function converts the value of a field to lowercase.

    13

  • 8/7/2019 DBMS Package For Class Project

    14/37

    Syntax: LOWER (filedname)

    Example:

    SELECT LOWER (name) FROM emp;

    SELECT LOWER (DBMS) FROM dual;

    8. LENGTH() FunctionThis function returns the length of the value in a text field.

    Syntax: LENGTH (filedname)

    Example:

    SELECT LENGTH (name) FROM emp;I. SQL> SELECT LENGTH('DBMS') from dual;

    Output:

    LENGTH('DBMS')--------------

    4

    9. SQRT() FunctionThis function returns the square root of the specified field or numeric expression.

    Syntax: SQRT (filedname)

    Example:

    SELECT SQRT (sal) FROM emp;

    SELECT SQRT (16) FROM emp;

    SELECT SQRT (2 + 14) FROM dual;

    10. ABS() FunctionThis function returns the absolute value of number.

    14

  • 8/7/2019 DBMS Package For Class Project

    15/37

  • 8/7/2019 DBMS Package For Class Project

    16/37

    13. INITCAP FunctionThis function returns the first letter in upper case of string.

    Syntax: INITCAP(string) or INITCAP(fieldname)For example: SQL>select INITCAP(sushil kumar) Output from dual;Output:

    Output

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

    Sushil Kumar

    14. TO_DATE FunctionThis function coverts a character or string field to a date field.

    Syntax: TO_DATE(string/char[,format])For example: 1. SQL> select TO_DATE('031092','MMDDYY') as Date fromdual;Output:

    Date---------

    10-MAR-922. SQL> select TO_DATE('1/1/02','mm/dd/yy') "Date" from dual;Output:

    Date---------01-JAN-02

    12.8 Logical Operators

    Logical operators used in SQL are:

    AND OR NOT

    AND: This operator gives output if both first condition and the second condition are true.

    For example:

    16

  • 8/7/2019 DBMS Package For Class Project

    17/37

    Let a table test with following details:

    SQL> select * from test;

    ID NAME

    ---------- ---------------1 alka2 saini

    SQL> select * from test where id=1 and name='alka';

    ID NAME---------- ---------------

    1 alka

    SQL> select * from test where id=1 and name='al';

    no rows selected

    OR: This operator gives output if any one condition is true.

    For example:

    SQL> select * from test where id=1 or name='al';

    ID NAME---------- ---------------

    1 alka

    SQL> select * from test where id=5 or name='alka';

    ID NAME---------- ---------------

    1 alka

    NOT: This operator is used for negation.

    For example:

    SQL> select * from test where id not in 1;

    ID NAME---------- ---------------

    2 saini

    SQL> select * from test where id not between 2 and 4;

    17

  • 8/7/2019 DBMS Package For Class Project

    18/37

    ID NAME---------- ---------------

    1 alka

    12. 9 Union, Intersection and Minus clause

    Union Clause: This clause is used to display the combined or merged data of two tables. If there is any duplicate row in both table, that will display only once. The user can combine theoutput by putting together multiple queries with the help of union clause.

    The output of union clause isRecords that are only in Table 1+Records those are only in Table 2+ A single set of recordswhich are common in Table1 and Table 2.For e.g. consider the following tables:

    18

  • 8/7/2019 DBMS Package For Class Project

    19/37

    Above two tables shows the records of students of two different subjects. As one student canread more than one subject, so some records in two tables can common. For example if theuser want to select all the students from both tables, then use union clause as follows:SQL> SELECT Roll_no as ID, Name from Table1 Union Select Id_no as ID, Name fromTable2;

    The output will be:

    Union of Table1 and Table2

    The above result shows the duplicate rows (i.e. S102, S104) displayed only once and all other rows of Table1 and Table2.Limitations:

    Aggregate functions cannot applied in union

    No. of attributes (Columns) in both queries should same.

    Datatype of column in each query should same.

    It cannot be used in sub queries.

    Intersect Clause:This clause is also used to combine more than one query like union. But a major difference isthat it will display only that records which are common to both the tables. The intersect clause output the common rows of both the table.

    19

  • 8/7/2019 DBMS Package For Class Project

    20/37

    The output of intersect clause isA single set of records which are common in Table1 and Table 2.Considering further the above tables i.e. table1 and Table2. If the user wants to select all therecords of students which read both the subjects, then the intersect clause will as follows:SQL>SELECT Roll_no ID, Name from Table1 INTERSECT Select Id_no ID, Name from

    Table2;The output will be:

    Intersection of Table1 and Table2The above result shows only the common rows (i.e. S102, S104) are displayed only once.Minus Clause:This clause is used to select the rows from only one table which are unique in that table. Thatmeans which are not common as shown in following pictorial representation.

    Statement 1: SQL> select * from table1 minus select * from table2;&Statement 2: SQL> select * from table2 minus select * from table1;Outputs:

    20

  • 8/7/2019 DBMS Package For Class Project

    21/37

    The above two statements will not produce the same result.Statement 1 displays all record of Table1 which are not in Table2.

    And statement 2 behaves vice-versa, as it displays all the records of Table2 which are not inTable1.

    12.10 JoinsAs the name suggests join is used for joining more than one table. Sometimes the user requires using multiple tables as single entity, which is implemented by join operation. Joinenable the user to manipulate many tables as a single entity using a single SQL statement.Join operation work on columns or attributes. The user can join tables on columns whichhave the same data type and data width.Some major join operations are:

    a) Equi Join / Inner join

    b) Self Join

    c) Outer Join

    a) Equi join: This works on different tables. It combines many tables assingle entity. The user can join two or more tables on columns thathave same specifications in all the tables. Equi join is also calledinner join .

    For example: Consider the following two tables which give theinformation related to a library:

    21

  • 8/7/2019 DBMS Package For Class Project

    22/37

    Now suppose the user want to display book issue information like Book_No, Title of Book,and Name of the member to which the book is issued in the ascending order. The query willas follows:SQL>SELECT Book_No, Title_of_Book, Name from Book_issue, Member_info

    WHERE Book_issue.Member_no = Member_info.Member_noORDER BY Member_no;

    Note: We are using Table name and Column name separated by period(.) in where clause because both the tables have same column name.The output of above query will:

    Self Join:

    Self-join simply is a join which is used to join a table to itself. The SQL self-join can be done by using aliases, which can be used to treat one table like a different table. SQL self-join can be any form of join such as SQL inner join or SQL outer join etc. User can apply any join tothe SQL self-join.

    Here is common syntax of SQL self-join:

    SELECT column_list FROM table_A AS AINNER JOIN table_A AS B

    ON A.column_name1 = B.column_name2, ...WHERE row_conditions

    22

  • 8/7/2019 DBMS Package For Class Project

    23/37

    Example: Suppose the user want to select the name of the employees along with their managers from the following table Table 1.

    Emp_No Name Manager_No

    E101 Deepanshu E103

    E102 Jannat -

    E103 Sakshi E105

    E104 Pakhi -

    E105 Sanjay E102

    The query will as follows:SQL>SELECT X.Name, Y.Name Manager FROM Table1 X, Table1 Y whereX.Manager_no=Y.Emp_no;In the above query X and Y are the aliases of Table1 , by using this we can use the sametable by two name X and Y. The output will be:

    Name Manager

    Deepanshu Sakshi

    Sakshi Sanjay

    Sanjay Jannat

    Natural Join:

    A natural join statement is used to compare the common columns of two tables with eachother. The user should check whether common columns exist in both tables before doing anatural join.

    Natural joins may cause problems if columns are added or renamed. Also, no more than twotables can be joined using this method. So, it is best to avoid natural joins as far as possible.

    Consider the same example of equi join as this is the same as an equi join on(Book_issue.Member_no = Member_info.Mamber_no).

    23

  • 8/7/2019 DBMS Package For Class Project

    24/37

    Outer JoinAn outer join is similar to the equi join, but it will also return non matched rows from thetable. Outer join is of three types:

    a) Left Outer Join

    b) Right Outer Join

    c) Full Outer Join

    a) Left Outer Join :

    The LEFT JOIN keyword returns all rows from the left table (table_name1), even if there are no matches in the right table (table_name2).

    Syntax:

    SELECT column_name(s)FROM table_name1LEFT JOIN table_name2ON table_name1.column_name=table_name2.column_name

    Example : Consider the following two tables :The Customer table is :

    C_Id FirstName LastName City1 Punit Taneja Sonipat2 Tanvi Bagri Sonipat3 Kamya Sharma Yamunanagar

    The "Order1" table:

    O_Id OrderNo C_Id1 77895 32 44678 33 22456 2

    24

  • 8/7/2019 DBMS Package For Class Project

    25/37

    4 24562 25 34764 15

    Now we want to list all the customers and their orders - if any, from the tables above.

    We use the following SELECT statement:

    SQL>SELECT Customer.LastName, Customer.FirstName, Order1.OrderNoFROM Customer LEFT JOIN Order1ON Customer.C_Id=Order1.C_IdORDER BY Customer.LastName;

    The result-set will look like this:

    The LEFT JOIN keyword returns all the rows from the left table (Customer), even if thereare no matches in the right table (Order1).

    b) Right Outer Join

    The RIGHT JOIN keyword Return all rows from the right table (table_name2), even if thereare no matches in the left table (table_name1).

    Syntax:

    SELECT column_name(s)FROM table_name1RIGHT JOIN table_name2ON table_name1.column_name=table_name2.column_name

    25

  • 8/7/2019 DBMS Package For Class Project

    26/37

    In some databases RIGHT OUTER JOIN is called RIGHT JOIN.

    Example : Continuing the above example, consider the same tables Customer and Order .

    Now we want to list all the orders with their customers - if any, from the tables above.

    We use the following SELECT statement:

    SQL>SELECT Customer.LastName, Customer.FirstName, Order1.OrderNoFROM Customer RIGHT JOIN Order1ON Customer.C_Id=Order1.C_IdORDER BY Customer.LastName;

    The result-set will look like this:

    LastName FirstName OrderNoBagri Tanvi 22456Bagri Tanvi 24562Sharma Kamya 77895Sharma Kamya 44678- - 34764

    The RIGHT JOIN keyword returns all the rows from the right table (Order), even if there are

    no matches in the left table (Customer).

    c) Full Outer Join

    The FULL OUTER JOIN keyword return rows when there is a match in one of the tables. Itis also called FULL JOIN.

    Syntax:

    SELECT column_name(s)FROM table_name1

    FULL JOIN table_name2ON table_name1.column_name=table_name2.column_nameExample : Continuing the above example, consider the same tables Customer and Order .

    Now we want to list all the orders with their customers and customer with their order.

    We use the following SELECT statement:

    26

  • 8/7/2019 DBMS Package For Class Project

    27/37

    SQL>SELECT Customer.LastName, Customer.FirstName, Order1.OrderNoFROM Customer FULL JOIN Order1ON Customer.C_Id=Order1.C_IdORDER BY Customer.LastName;

    The result-set will look like this:

    LastName FirstName OrderNoBagri Tanvi 22456Bagri Tanvi 24562Sharma Kamya 77895Sharma Kamya 44678

    Taneja Punit -- - 34764

    The FULL JOIN keyword returns all the rows from the left table (Customer), and all therows from the right table (Order). If there are rows in "Customer" that do not have matches in"Order", or if there are rows in "Order" that do not have matches in "Customer", those rowswill be listed as well.

    12.11 VIEW: A view is a virtual table that does not physicallyexist. It is derived from another existing table in the database,which is known as base tables. View a voids duplication of data and

    provides data security.

    Syntax:

    CREATE VIEW

    AS ;

    For example:

    CREATE VIEW s1 AS

    27

  • 8/7/2019 DBMS Package For Class Project

    28/37

    ( SELECT C_ID,FIRSTNAME,LASTNAME,CITY FROM customer ) ;

    To delete a view use DROP VIEW command as follow:

    DROP VIEW s1;Updating a VIEW

    You can update a VIEW without dropping it by using the

    following syntax:

    CREATE OR REPLACE VIEW view_name AS

    ;

    Selecting data from view

    Syntax: Select FROM view_name [WHERE

    clause];

    For example:

    Select C_ID,FIRSTNAME,LASTNAME,CITY FROM s1;

    12.12 Some Simple Queries

    1. Get the description of EMP table.

    SQL>Desc EMP ;

    RESULT: Name Null? Type

    -------------------------------- ----------------------- -------------------------EMPNO NOT NULL NUMBER(4)ENAME VARCHAR2(10)JOB VARCHAR2(9)MGR NUMBER(4)

    28

  • 8/7/2019 DBMS Package For Class Project

    29/37

    HIREDATE DATESAL NUMBER(7,2)COMM NUMBER(7,2)DEPTNO NUMBER(3)AGE NUMBER(3)

    ESAL NUMBER(10)

    2. Get the description DEPT table.

    SQL>Desc DEPT ;

    RESULT: Name Null? Type--------------------------------- --------------------- ---------------------------DEPTNO NOT NULL NUMBER(2)DNAME VARCHAR2(14)

    LOC VARCHAR2(13)

    3.Display employee name with empno and job type from emp table.

    SQL> select empno,ename,job from EMP;

    Output:

    EMPNO ENAME JOB---------- ---------- ---------

    7369 SMITH CLERK

    7499 ALLEN SALESMAN7521 WARD SALESMAN7566 JONES MANAGER 7654 MARTIN SALESMAN7698 BLAKE MANAGER 7782 CLARK MANAGER 7788 SCOTT ANALYST7839 KING PRESIDENT7844 TURNER SALESMAN7876 ADAMS CLERK

    EMPNO ENAME JOB---------- ---------- ---------

    7900 JAMES CLERK 7902 FORD ANALYST7934 MILLER CLERK

    14 rows selected.

    29

  • 8/7/2019 DBMS Package For Class Project

    30/37

    4. Display all employee names and their salaries, whose salary lies between2000/- and 5000/- both inclusive.

    SQL> select ename,sal from EMP where sal between 2000 and 5000;

    Output:

    ENAME SAL

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

    JONES 2975

    BLAKE 2850

    CLARK 2450

    SCOTT 3000

    KING 5000

    FORD 3000

    6 rows selected.

    5. Display all employees name which starts with either A or R.SQL> select ename from emp where ename like 'A%' or ename like 'R%';Output:

    ENAME----------ALLENADAMS

    6. Display all employee names and jobs, whose job title include M.

    SQL> select ename,job from emp where job like 'M%';

    Output:

    ENAME JOB

    30

  • 8/7/2019 DBMS Package For Class Project

    31/37

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

    JONES MANAGER

    BLAKE MANAGER

    CLARK MANAGER

    7. Display all jobs available in emp table.

    SQL> select distinct job from emp;

    Output:

    JOB

    ---------

    CLERK

    SALESMAN

    PRESIDENT

    MANAGER

    ANALYST

    8. Display all employee names , salary and 10% rise in salary whose jobtype is clerk.

    SQL> select ename , sal , sal+0.10* sal from emp where job='CLERK';

    Output:

    ENAME SAL SAL+0.10*SAL

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

    SMITH 800 880

    ADAMS 1100 1210

    JAMES 950 1045

    31

  • 8/7/2019 DBMS Package For Class Project

    32/37

    MILLER 1300 1430

    9. Display minimum and maximum salaries of employee.

    SQL> select min(sal),max(sal) from emp;

    Output:

    MIN(SAL) MAX(SAL)

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

    800 5000

    10. Find how many job titles are available in employee table.SQL> select count (distinct job) as NumberOfJob from emp;Output:

    NUMBEROFJOB-----------

    5

    11. Find ename whose manager is not NULL.

    SQL>select ename from emp where mgr is not null;

    Output:

    ENAME

    ----------

    SMITH

    ALLEN

    WARD

    JONES

    MARTIN

    BLAKE

    32

  • 8/7/2019 DBMS Package For Class Project

    33/37

    CLARK

    SCOTT

    TURNER

    ADAMS

    JAMES

    ENAME

    ----------

    FORD

    MILLER

    13 rows selected.

    12. Display total salary spent for each job category.SQL> select job,sum (sal) from emp group by job;

    Output:JOB SUM(SAL)--------- ----------CLERK 4150SALESMAN 5600PRESIDENT 5000MANAGER 8275ANALYST 6000

    13. Display number of employees working in each department and theirdepartment name.

    SQL> select dname, count (ename) from emp, dept where emp.deptno=dept.deptno group bydname;Output:

    33

  • 8/7/2019 DBMS Package For Class Project

    34/37

    DNAME COUNT(ENAME)-------------- ------------ACCOUNTING 3RESEARCH 5SALES 6

    Review Exercise

    1. Create a table Product for the following details:

    Column Name Data Type Size Attributes

    SNo number 6 Primary key

    ProductName Varchar 2 20 Not Null

    Price number 10,2 Not Null

    QTY number 6 Default 1

    DOP date

    Warranty number 6

    2. Insert the following data into the Product table using SQL insertstatement:

    SNo ProductName Price QTY DOP Warranty

    1 Computer 5000 6 13/10/03 2

    2 Printer 1500 4 15/01/04 4

    3 Scanner 800 2 19/07/02 1

    4 Webcam 1200 5 13/10/03 5

    5 Plotter 3000 3 12/04/02 3

    6 Ups 5000 1 17/02/99 27 Speaker 200 15 07/01/04 1

    3. Write following SQL statement based on Product table:

    (a) Write a query for display the productname in ascending order of the price where quantity ismore than 4.(b) Write a query for display the number of computers,scanners and webcams.

    34

  • 8/7/2019 DBMS Package For Class Project

    35/37

    (c ) Write a query for change the price to 3000 for the productname webcam.(d) Write a query for inserting a new record in to the table with the following data

    8,Mouse,300,6, 13/10/03,2(e) Write a query for display details of those products which purchased on 13/10/03.

    4. Create a table BookDetails for the following details:

    Column Name Data Type Size Attributes

    SNo number 6 Primary key

    Title Varchar 2 20 Not Null

    AuthorName Varchar 2 20 Not Null

    Publisher Varchar 2 20

    Qty number 6 Default 1

    Price number 10,2

    5. Insert the following data into the BookDetails table using SQLinsert statement:

    SNo Title AuthorName Publisher Qty Price

    1 Database ManagementSystem

    Sushil Kumar Unique 10 145

    2 C++ Balaguruswamy Mc Graw 5 200

    3 Data structures Horowitz Mc Graw 4 250

    4 Visual Basic Gurewich PHI 2 400

    5 Networks Freed BPB 1 600

    6 Oracle 8i Palmer Galgotia 3 700

    35

  • 8/7/2019 DBMS Package For Class Project

    36/37

    7 Java script Schildt Mc Graw 5 300

    8 Oracle Developer Ivan Bayross BPB 2 200

    6. Write following SQL statement based on BookDetails table:

    (a) Write a query for display the details of all the books published by Mc Graw.(b) Write a query for display total cost of purchasing the books whose author is Sushil Kumar.(Total Cost= Qty * Price)(c ) Write a query for display a list of books with price more than 400.(d) Write a query display the number of books published by BPB.(e) Write a query for display the details of the books for which total cost is maximum.

    7. Create a table Employee for the following details:

    Column Name Data Type Size Attributes

    ENo Varchar 2 6 Primary key

    EName Varchar 2 20 Not Null

    Job Varchar 2 20 Not Null

    Mgr Varchar 2 20

    Salary number 6

    DOJ date

    DNo number 6

    8. Insert the following data into the Employee table using SQL insertstatement:

    36

  • 8/7/2019 DBMS Package For Class Project

    37/37

    ENo EName Job Mgr Salary DOJ DNo

    E1000 Allen Director 7000 14/02/95 12

    E1695 Smith Manager E1000 5000 10/02/97 20

    E1566 Martin Manager E1000 5200 23/07/96 10E1350 Jones Clerk E1695 1250 17/02/98 15

    E1352 Ford Analyst E1566 4000 12/07/99 20

    E1353 Adams Clerk E1695 1200 11/11/99 15

    E1356 James Salesman E1566 800 12/02/98 20

    9. Write following SQL statement based on Employee table:

    (a) Write a query for display all employees details whose names begins with the alphabet A.(b) Write a query for minimum and maximum salary for each job type. Write a query for find out the number of employees having job as Manager.(d) Write a query for calculate the average salary for each department.(e) Write a query for display the salary with 12% increment.

    10. Create a table Student for the following fields:RollNo, Name, DOB, Subject1, Subject2, Subject3.

    a. Write a SQL statement for adding a new column Grade. b. Insert 5 rows in Student table with SQL insert statement.c. Write a SQL statement for display results with total marks(Subject1+Subject2+Subject3 ) and

    percentage.d. Write a SQL statement for display student name with ascending order of total marks.e. Write a SQL statement for find out how many students score is > 50%.