Chapter - 5

Structured Query Language SQL

Overview of SQL
It is a 4 GL Oracle9i in specific DML DDL Triggers and integrity constraints Embedded and Dynamic SQL ClientClient-Server Execution and remote database access Transaction management Security OODBMS features, Data mining, spatial data, and XML data management
BN Shankar Gowda, BIT 2

Basic SQL Commands
Description Data retrieval statement. Data Manipulation Language (DML). Add rows, change data, and delete few rows. Create new tables/views, remove tables/ views, and change the schema. Modified values of database are permanently written into disk, rollback the changes made. Access control can be assigned or changed.

BN Shankar Gowda, BIT


Max = 2000. Raw binary data. Same as NUMBER.0E-130 to 9. 4712 A.Basic data types in Oracle Data type CHAR (size) VARCHAR2(size DATE BLOB CLOB BFILE LONG LONG RAW NUMBER(size) NUMBER(size. Same as NUMBER. Date. Max.D. size/d can't be specified. Binary large object. 4712 B. Max = 4GB. Rest is same as LONG. Numbers. BIT 4 . size/d can't be specified. Same as NUMBER.d) DECIMAL FLOAT INTEGER SMALLINT Description Fixed length character. Numbers. Max = 2GB. BN Shankar Gowda.C. Pointer to binary OS file.9E125. Character large object. Range = 1. Same as NUMBER. Max = 4000. Variable length character string. size = 40 digits. Character data of variable size. to Dec 31. Max = 4GB. Vaild range is from Jan 1.

BIT 5 .Example tables Employee SSN 1111 2222 3333 4444 5555 Name eepak Nandagopal ooja rasad eena ate 5-Jan-62 22-Jan-65 11-Jan-57 15-Jan-85 Salary 22000 30000 18000 32000 8000 grSSN 4444 4444 2222 Null 4444 No 1 3 2 3 3 Department DNo 1 2 3 DName Admin Resea ch Accounts Loc Chennai Banga o e Banga o e BN Shankar Gowda.

foreign key (DNo) references Department(DNo)). DNo number(2) not null. foreign key (MgrSSN) references Employee(SSN). Loc varchar2(15). Name varchar2(20) not null.DDL CREATE TABLE Department( DNo number(3) not null. MgrSSN number(4). DName varchar2(10) not null.2). BDate date. BN Shankar Gowda. primary key (DNo)). Salary number(10. primary key (SSN). BIT 6 . CREATE TABLE Employee( SSN number(4) not null.

A FROM clause. BN Shankar Gowda.Data Retrieval Statement (SELECT) Syntax SELECT *|{[DISTINCT] column | expression} FROM table(s).A SELECT clause. . BIT 7 . The basic SELECT statement must include the following: .

-------------------.--------.ExampleExample-1 SELECT * FROM Employee. The output of this query is shown below: OutputOutput-1 SSN NAME BDATE SALARY MGRSSN DNO ---.--------4444 Prasad 11-JAN-57 32000 3 5555 Reena 15-JAN-85 8000 4444 3 1111 Deepak 05-JAN-62 22000 4444 1 2222 Nandagopal 10-DEC-60 30000 4444 3 3333 Pooja 22-JAN-65 18000 2222 2 BN Shankar Gowda.--------. The * indicates that it should retrieve all the columns from Employee table. BIT 8 .--------.

-------------------.--------.--------. BIT 9 .--------. OutputOutput-2 SSN NAME BDATE SALARY MGRSSN DNO ----.--------------------------------1111 Deepak 05-JAN05-JAN-62 22000 4444 1 2222 Nandagopal 10-DEC-60 30000 10-DEC4444 3 3333 Pooja 22-JAN-65 18000 22-JAN2222 2 4444 Prasad 11-JAN11-JAN-57 32000 3 5555 Reena 15-JAN15-JAN-85 8000 4444 3 BN Shankar Gowda.ExampleExample-2 SELECT * FROM Employee ORDER BY SSN.

Salary * 12 AS YRLY_SALARY Employee. Name. BIT 10 . Salary * 12 FROM Employee.Using arithmetic operators SELECT Name. BN Shankar Gowda. Salary. Using aliases An alias when used for a column: Renames a column heading It is useful in arithmetic calculations. ExampleExample-3 SELECT FROM OR SELECT FROM Name. AS keyword can optionally be used between column name and alias name. Salary. Salary. Salary * 12 "YRLY_SALARY" Employee.

2) NUMBER(4) NOT NULL NUMBER(2) BN Shankar Gowda. OR DESC Employee. BIT 11 .ExampleExample-4 DESCRIBE Employee. OutputOutput-4 Name ------------------------------SSN NAME BDATE SALARY MGRSSN DNO Null? -------NOT NULL NOT NULL Type ---NUMBER(4) VARCHAR2(20) DATE NUMBER(10.

Select Statement with Where ExampleExample-5 SELECT Name. ExampleExample-6 SELECT DName. BDate FROM Employee WHERE BDate = '11-Jan-57'. Loc FROM Department WHERE Loc = 'Bangalore'. '11-JanBN Shankar Gowda. Salary FROM Employee WHERE Salary > 25000. ExampleExample-7 SELECT Name. BIT 12 .

BDate FROM Employee WHERE Salary BETWEEN 25000 AND 30000. ExampleExample-9 SELECT SSN. '__-JANBN Shankar Gowda. ExampleExample-10 SELECT Name FROM Employee WHERE Name LIKE 'P%'.ExampleExample-8 SELECT Name. ExampleExample-11 SELECT Name. 2). DNo FROM Employee WHERE BDate LIKE '__-JAN-__'. Name FROM Employee WHERE DNo IN (1. BIT 13 .

BN Shankar Gowda. DNo FROM Employee ORDER BY DNo DESC. DNo FROM Employee WHERE Salary > 30000 AND DNo = 3.ExampleExample-12 SELECT Name FROM Employee WHERE MgrSSN IS NULL. Salary FROM Employee WHERE Name LIKE 'P%' OR Salary <= 20000. Salary. ExampleExample-13 SELECT Name. Salary. ExampleExample-15 SELECT Name. ExampleExample-14 SELECT Name. BIT 14 . Name.

Arc sine of n (in radians). If n is negative. Tangent of n. n) ABS(n) CEIL(n) FLOOR(n) EXP(n) POWER(n. Truncates to n decimal places. Null Value ± Substitute m for n if n = null. n) TRUNC(column | expr. BN Shankar Gowda. Arc cosine of n (in radians). Absolute value of n. n) MOD(m. Hyperbolic cosine value of n. en nm Square root of n.SQL Functions ROUND(column | expr. Hyperbolic sine value of n. Hyperbolic tan value of n. 1 if n is positive. Cosine of n. m) SQRT(n) SIGN(n) LN(n) LOG(n) SIN(n) COS(n) TAN(n) ASIN(n) ACOS(n) ATAN(n) SINH(n) COSH(n) TANH(n) NVL(n. Returns the remainder of m/n. m) VSIZE(n) Rounds to n decimal places. Largest integer smaller than n. -1 if negative. Natural log of n (lg n) log10 n Sine of n. BIT 15 . Smallest integer larger than n. Storage size of n. Arc tangent of n (in radians). numbers to the left are rounded. 0 if zero.

BN Shankar Gowda. BIT 16 .Working with Dates Century Year Month Day Hour Minute Second 19 99 07 23 4 10 53 SELECT SYSDATE FROM DUAL.

--------10-JAN. OutputOutput-16 Experience --------------247. SELECT GREATEST('10-JAN-93'. '10-JAN-98').73471 ExampleExample-17 (GREATEST & LEAST) The function GREATEST finds the earliest date and LEAST finds the oldest date in the list. OutputOutput-17 GREATEST( LEAST('10 --------.ExampleExample-16 (MONTHS_BETWEEN) SELECT MONTHS_BETWEEN(SYSDATE.10-JAN10-JAN-98 10-JAN-93 BN Shankar Gowda. '09-JAN-1983') '09-JAN"Experience" FROM DUAL. '10-JAN-98') '10-JANFROM DUAL. BIT 17 . GREATEST('10-JAN'10-JANLEAST('10-JANLEAST('10-JAN-93'.

Conversion Functions VARCHAR2 or CHAR is converted to NUMBER VARCHAR2 or CHAR is converted to DATE NUMBER is converted to VARCHAR2 DATE is converted to VARCHAR2 BN Shankar Gowda. BIT 18 .

--------------------Pooja 22-JAN22-JAN-65 January . 22nd. Bdate. TO_CHAR(BDate. YYYY') AS "Formatted" Employee Name = 'Pooja'. TO_CHAR(BDate. 'Month. Bdate. ddth. ExampleExample-19 SELECT FROM WHERE Name.Use of TO_CHAR TO_CHAR function converts a date format to a character string ExampleExample-18 SELECT Name. BIT 19 . OutputOutput-19 NAME BDATE Formatted -------------------. 'DD/MM/YY') AS "Formatted" FROM Employee WHERE SSN = 2222.--------. 1965 BN Shankar Gowda.

ExampleExample-20 SELECT Name. YYYY "at" HH:MI P.')AS "Formatted" FROM Employee WHERE SSN = 2222. Bdate. 10th. Output Prasad 11-JAN-57 January. Output Nandagopal 10-DEC-60 December. fmddth. BIT 20 . TO_CHAR(BDate. 10-DECNote: ³fm´ suppresses unnecessary blanks Use HH12 for 12 hrs clock and HH24 for 24 hrs clock BN Shankar Gowda. fmddth. YYYY') AS "Formatted" FROM Employee. 'fmMonth.M. TO_CHAR(BDate. Bdate. 1957 11-JANExampleExample-21 SELECT Name. 1960 at 12:00 A.M. 11th. 'fmMonth.

ExampleExample-22 SELECT TO_DATE('1-Sep-2003'. OutputOutput-22 TO_DATE(' --------01-SEP01-SEP-03 ExampleExample-23 SELECT TO_DATE('08/30/2003'. 'DD/MM/YYYY') TO_DATE('1-SepFROM DUAL.Use of TO_DATE TO_DATE function is to convert any character literal string into a valid date format. OutputOutput-23 ERROR at line 1: ORAORA-01843: not a valid month BN Shankar Gowda. BIT 21 . 'DD/MM/YYYY') FROM DUAL.

SELECT FROM WHERE SELECT RPAD(Salary. '*') FROM Employee WHERE SSN = 1111. 'b') DUAL. Output bangalore BANGALORE Bangalore Institute Of Technology Database Management base 8 5 0 SELECT LPAD(Salary. SELECT INITCAP('bangalore institute of technology') FROM DUAL. SELECT LENGTH('Database') FROM DUAL. 4) FROM DUAL. 'Management') FROM DUAL. SELECT UPPER('Bangalore') FROM DUAL. 8. SELECT SUBSTR('Database'. SELECT FROM SELECT FROM INSTR('Database'. SELECT CONCAT('Database '. ' ') ***22000 22000*** Database BN Shankar Gowda. LTRIM(' Database'. 8. 'x') DUAL.Character Functions Program SELECT LOWER('Bangalore') FROM DUAL. BIT 22 . 5. '*') Employee SSN = 1111. INSTR('Database'.

Aggregate Functions COUNT AVG MAX MIN STDDEV SUM VARIANCE BN Shankar Gowda. BIT 23 .

of Employees" FROM Employee. ExampleExample-25 SELECT SUM(Salary) AS Total FROM Employee. MIN(Salary) Name. BIT 24 . FROM Employee. MAX(Salary). BN Shankar Gowda.ExampleExample-24 SELECT COUNT(*) AS "No. ExampleExample-26 SELECT Name.

COUNT(*). Group functions ignore nulls. AVG(Salary) FROM Employee GROUP BY DNo. BN Shankar Gowda. By default the result of GROUP BY clause sort the data in ascending order. SUM(Salary).GROUP BY Clause The rules to be followed while using GROUP BY clause are given below: You can't have non-group function or column in SELECT clause. BIT 25 . Example: SELECT DNo.

BN Shankar Gowda. BIT 26 . COUNT(*). SUM(Salary).ExampleExample-27 SELECT DNo. MgrSSN. HAVING clause SELECT FROM GROUP BY HAVING DNo. AVG(Salary) Employee DNo DNo = 3. AVG(Salary) FROM Employee GROUP BY DNo.

2. BN Shankar Gowda. First all rows matching the WHERE conditions are retrieved. groups matching the HAVING clause condition are retained. 3. Finally. BIT 27 . These rows are grouped using the column(s) in GROUP BY clause. SELECT DNo.The order of evaluation when all the clauses are specified is given below: 1. AVG(Salary) FROM Employee WHERE BDate LIKE '__-JAN-__' '__-JANGROUP BY DNo HAVING MAX(Salary) > 10000.

This means that the foreign key of table1 will be made equal to the primary key of table2. ± When the attributes or columns have the same names. ± Without proper joining condition or attributes the SQL will display the Cartesian product of the tables in the FROM clause. BN Shankar Gowda. tag them with table names using dot notation.MULTITABLE QUERIES Simple Equi-Joins : guidelines Equi± Table names in the FROM clause is separated with commas. ± Use appropriate joining condition. BIT 28 .

ExampleExample-28: Display the employee names and the department names for which they work. BN Shankar Gowda. ExampleExample-29 : Display only employees working for Accounts department.DNo. Department WHERE (Employee. Department WHERE Employee. SELECT Name. BIT 29 . DName FROM Employee. DName FROM Employee.DNo = Department. SELECT Name. Salary.DNo = Department. work.DNo) AND (DName = 'Accounts').

BN Shankar Gowda. Employee e2 WHERE (e1. BIT 30 .Salary) AND (e2.Name = 'Nandagopal'). e1.Salary FROM Employee e1. SELECT e1.Name.SelfSelf-Join and Table Aliases ExampleExample-30 : Find the employee who earns more than µNandagopal¶.Salary > e2.

DName FROM Employee E. OutputOutput-31 NAME DNAME -------------------. Department D WHERE E.---------Deepak Nandagopal Pooja Prasad Reena BN Shankar Gowda.Name = D.Right-Outer Join RightExampleExample-31 : SELECT Name.DName(+). BIT 31 .

---------Accounts Admin Research BN Shankar Gowda. OutputOutput-32 NAME DNAME -------------------. Department D WHERE E. BIT 32 .LeftLeft-Outer Join ExampleExample-32 SELECT Name.DName.Name(+) = D. DName FROM Employee E.

BN Shankar Gowda.NESTED QUERIES or SUB QUERIES SELECT <column(s)> FROM table WHERE <condn operator> (SELECT <column> FROM table). >=. <>) or multiple row operators like IN. Outer query uses the result of the inner query. <=. <. queries. If the inner query returns only one row it is called as single row sub queries. queries. The comparison condition may be a single row operator like >. =. ALL. Alternatively if the inner query returns a set of rows (more than one row) it is classified as multiple-row sub multiplequeries. BIT 33 . ANY.

BN Shankar Gowda. Display names of employees whose salary is greater than the employee SSN=1111. SELECT Name FROM Employee WHERE Salary > (SELECT Salary FROM Employee WHERE Name = 1111). SELECT Name FROM Employee WHERE DNo = (SELECT DNO FROM Department WHERE DName = 'Accounts').Single-Row Nested Queries SingleDisplay the names of the employees working for Accounts department. BIT 34 .

Salary FROM Employee WHERE Salary >= (SELECT AVG(Salary) FROM Employee GROUP BY DNO HAVING DNo = 3). SELECT Name. BIT 35 . BN Shankar Gowda.ExampleExample-33 Display all the employees drawing more than or equal to the average salary of department number 3.

ALL: ALL: Compare value to all the values returned by the subquery. ANY: Compare value to each value ANY: returned by the subquery.Multiple-Row Nested Queries MultipleIN: IN: Equal to any member in the list. BIT 36 . BN Shankar Gowda.

BN Shankar Gowda. Salary FROM Employee WHERE Salary IN (SELECT MAX(Salary) FROM Employee). BIT 37 . Salary FROM Employee WHERE Salary = (SELECT MAX(Salary) FROM Employee).Display the name of the highest paid employee. because the inner query produces a single tuple. Both '=' and 'IN' works. SELECT Name. SELECT Name.

BN Shankar Gowda. 20. Error: ORA-01427: single-row subquery returns more than one row ORAsingle- Correct Query: Select Name.000 to Rs. BIT 38 . Salary from Employee where Salary = (Select Salary from Employee where Salary between 20000 and 40000). 40.Find the Name and Salary of people who draw in the range Rs. Salary from Employee where Salary IN (Select Salary from Employee where Salary between 20000 and 40000).000. Select Name.

e = ANY(5.3. and 8 qualifies.3.3. than 8 qualifies. Even 4 qualifies. ll values in the =ANY list qualify.3.8).ANY and ALL Operator Meani g Example Less than the e < ANY (5.8): nything below 3 <ALL axi u .8): nything other than !=ALL anything.8): e is less than any <ANY axi u . single ite in the list (5. ore than >ALL e > ALL (5.3. Less than the e < ALL (5.8). Sa e as IN.8). BIT 39 . BN Shankar Gowda. 5. ore than >ANY e > ANY (5. qualifies. single ite in the list (5.3.8): e is less than any the ini u . Even 7 qualifies.3. Not equal to e != (5.3. because 4 > 3.3. because 7 < 8.8): nything greater the ini u .

Salary Employee DNo = 3). Salary FROM Employee WHERE Salary > ANY (SELECT FROM WHERE Salary Employee DNo = 3). Salary FROM Employee WHERE Salary < ANY (SELECT FROM WHERE ExampleExample-35: SELECT Name. 40 BN Shankar Gowda. BIT .ExampleExample-34: SELECT Name.

BIT 41 . >ALL means greater than the greatest and <ALL means less than the lowest value.ExampleExample-35: SELECT Name. ExampleExample-36: SELECT Name. Salary FROM Employee WHERE Salary > ALL (SELECT Salary FROM Employee WHERE DNo = 3). Salary FROM Employee WHERE Salary < ALL (SELECT Salary FROM Employee WHERE DNo = 3). BN Shankar Gowda.

Sequence: Sequence: Automatically generates a sequence of numbers. Index: Index: Provides an efficient access structure. BIT 42 . BN Shankar Gowda. View: View: A tabular structure similar to a table but it is a collection of one or more tables.CREATING and ALTERING DATABASE OBJECTS Table: Table: A tabular structure that stores data.

2). Name Varchar2(20) not null. BIT 43 . BDate Date.CREATE TABLE Employee( SSN Number(4) not null. DNo Number(2) not null. BN Shankar Gowda. Primary Key (SSN). MgrSSN Number(4). Foreign Key (MgrSSN) references Employee(SSN). Foreign Key (DNo) references Department(DNo)). Salary Number(10.

BIT 44 .---SSN NOT NULL NUMBER(4) NAME NOT NULL VARCHAR2(20) BDATE DATE SALARY NUMBER(10.-------.Names of the tables/views SELECT * FROM TAB. Name Null? Type ------------------------------.2) MGRSSN NUMBER(4) DNO NOT NULL NUMBER(2) BN Shankar Gowda. Schema details of a table DESC Employee.

Salary FROM Employee. Name. BIT 45 . Manager Number(4) references Employee(SSN) ON DELETE CASCADE). DName Varchar2(10) not null. BN Shankar Gowda.ON DELETE constraint CREATE TABLE Department( DNo Number(3) not null. Creating tables with a Subquery CREATE TABLE Emp AS SELECT SSN. Loc Varchar2(15). Primary Key (DNo).

BIT 46 . the column must be empty) ALTER TABLE Employee DROP COLUMN Phone. (Note: to modify data type. BN Shankar Gowda. the column must be empty) ALTER TABLE Employee MODIFY Phone Varchar2(10).ALTER TABLE Statement ALTER TABLE Employee ADD Phone Number(7) not null. (Note: to add not null constraint.

Disabling and Enabling Constraints CREATE TABLE Employee( ««««««««« ««««««««« Salary Number(10. ALTER TABLE Employee ENABLE CONSTRAINT Ch_Sal. BN Shankar Gowda. BIT 47 .2) CONSTRAINT Ch_Sal CHECK (Salary > 0)). ALTER TABLE Employee DISABLE CONSTRAINT Ch_Sal.

BIT 48 Emp_Dept SSN. DName. Name. BN Shankar Gowda. Salary Employee E. Reduces joining of more tables often. Department D E.DNo.CREATE VIEW Statement The advantages of using views are: It restricts data access. Example CREATE VIEW AS SELECT FROM WHERE View created.DNo = D. Many users can access a particular view with proper privileges. .

Restrictions on Views
There are few restrictions on views: You can not insert new rows nor update the view table.
(Error Message: ORA-01776: cannot modify more than one base ORAtable through a join view)

You can not alter the constraints or data types of the columns. If any changes are made to the base table(s), view table will get updated automatically.
BN Shankar Gowda, BIT 49

How to use a Sequence?
± Step-1: StepCREATE SEQUENCE Dept_Seq START WITH 10; ± Step-2: StepINSERT INTO Department values(Dept_Seq.NEXTVAL, 'Sales', 'Belgaum');

Dropping a sequence DROP SEQUENCE Dept_Seq; Creating an index for Employee table on Name CREATE INDEX IDXSSN ON Employee (Name); Dropping an index DROP INDEX IDXSSN;
BN Shankar Gowda, BIT 50

SQL Server 2000 GRANT { ALL | statement [ ,...n ] } TO security_account [ ,...n ] Object permissions: GRANT { ALL [ PRIVILEGES ] | permission [ ,...n ] } { [ ( column [ ,...n ] ) ] ON { table | view } | ON { table | view } [ ( column [ ,...n ] ) ] | ON { stored_procedure | extended_procedure } | ON { user_defined_function } } TO security_account [ ,...n ] [ WITH GRANT OPTION ] [ AS { group | role } ]
BN Shankar Gowda, BIT 51

BIT 52 . {objectprivileges(columnname)] ON objectname TO {username | rolename | PUBLIC} [WITH GRANT OPTION] where. BN Shankar Gowda. objectprivileges: INSERT or UPDATE objectname : table/view/sequence Example: GRANT UPDATE (ssn) ON employee TO bit.Rights (Contd«) Oracle 9i: GRANT {objectprivileges | ALL} [(columnname).

Rollback.Creating Users 1) 2) 3) 4) CONNECT SYSTEM/MANAGER. Commit. etc. BIT 53 . RESOURCE TO Guest. BN Shankar Gowda. GRANT CONNECT. REVOKE Select ON Employee FROM Guest. CREATE USER Guest IDENTIFIED BY bit.

BIT 54 . BN Shankar Gowda.Examples Objective ± 1 Create a user account called sng with password apple. It simply prohibits him from accessing the database. create user sng identified by apple. Format for Grant command grant {system privilege} to user [with admin options] system privilege: select/delete/insert/update and instead of user you can specify public as well. Format for Revoke command: revoke {system privilege} from user [with admin options] Revoking does not delete a user from Oracle or remove any tables created by him.

Therefore execute the following commands: grant connect.Examples (contd«) Objective ± 2 Create another user deepak identified by rock. At this point of time you must provide grant permission for connect and resource. connect sng/apple. grant connect. create user deepak identified by rock. resource to sng. BIT 55 . BN Shankar Gowda. resource to deepak.

BIT 56 . grant select on EMPLOYEE to deepak. Provide select permission to deepak for the table EMPLOYEE. This statement grants access to Employee table to all and the following command removes this privilege from all.assuming that this table is owned by sng. BN Shankar Gowda. grant select on EMPLOYEE to public.Examples (contd«) Objective ± 3 This objective shows how to grant permission to all. For example. revoke select on EMPLOYEE from public. This can be done by using the keyword public.

EMPLOYEE to reena. reena is some other user. Otherwise you will get an error. ERROR: grant select on sng. connect deepak/rock. BIT 57 .Objective ± 5 Display the contents of EMPLOYEE table. The user deepak can create a view to access the EMPLOYEE table. then he can not pass the granting of that table/view to other users. create synonym EMPLOYEE for sng.EMPLOYEE. BN Shankar Gowda.EMPLOYEE. If the table/view is not owned by a particular user. Creating a synonym. create view EMPLOYEE as select * from sng. // deepak gets connected select * from sng.EMPLOYEE. the table name must be preceded by the username of the owner of the table. Here. Unless a synonym is used.

Inserting dates INSERT INTO Employee VALUES (6666. 4444. &BDate. &Name. 1). Inserting through Keyboard INSERT INTO Employee VALUES (&SSN. BIT 58 . 'Deeapk'. &MgrSSN. TO_DATE('5-Jan'DD-MM'DD-MM-YYYY HH24:SS'). 22000.DML Statements INSERT Statement INSERT INTO Employee VALUES (1111. '5-Jan-62'. 4444. 'John'. 22000. '5 Jan-62'. BN Shankar Gowda. &Salary. TO_DATE('5-Jan-2003 3:40'. &DNo). 1).

05.Inserting rows from an existing table INSERT INTO EMP2 SELECT * FROM Employee. DELETE Statement DELETE Employee WHERE SSN = 1111. UPDATE Employee SET Salary = Salary * 1. BIT 59 . To hike the salary of all employees by 10%. UPDATE Statement UPDATE Employee SET DNo = 1 WHERE Name = 'Nandagopal'. BN Shankar Gowda.

Dlocation Varchar2(15)). Project( Project(PNumber Number(2). Sex Char(1). BN Shankar Gowda. Hours Number(3. Dependent( Dependent(ESSN Char(9). Dnum Number(2)). DName Varchar2(10). Dependent_Name Varchar2(15). Works_On( Works_On(ESSN Char(9). MgrStartDate Date).2).Salary Number(10.1)). Name Varchar2(20). MgrSSN Char(9). BIT 60 . Relationship Varchar2(10)). Dept_Locations( Dept_Locations(DNumber Number(2).ADDITIONAL EXAMPLES Company Database Example Employee( Employee(SSN Char(9). Plocation Varchar2(15). Address Varchar2(30). Sex Char. PName Varchar(10). Bdate Date. Department( Department(Dnumber Number(2). PNo Number(2). SuperSSN Char(9). DNo Number(2)). Bdate Date.

number of employees in each department and their average salary. ExampleExample-3: Retrieve the department number. Department WHERE DNo = DNumber GROUP BY DNo. '__-___ExampleExample-2: Calculate the wages earned by each employee.00. assuming the remuneration for each hour is Rs. Avg(Salary) FROM Employee. BIT 61 . SELECT DNo. 250.ExampleExample-1: Find all employees who were born during 1980. BN Shankar Gowda. Count(*).Sum(Hours) * 250 FROM Works_On GROUP BY Essn. Sum(Hours). SELECT Name FROM EMPLOYEE WHERE BDate LIKE '__-___-80'. SELECT Essn.

SELECT each department. BN Shankar Gowda. Count(*) FROM Department. the project name. 25. the project name. PName. retrieve the project number. project.000/. PName HAVING Count(*) > 3. Works_On WHERE PNumber = PNo GROUP BY PNumber. SELECT PNumber. PName. BIT 62 . Works_On WHERE PNumber = PNo GROUP BY PNumber.000/SELECT DName.ExampleExample-4: For each project. Employee WHERE DNumber = DNo AND Salary > 25000 GROUP BY DName. Count(*) FROM Project. 25. Count(*) FROM Project. PName. ExampleExample-5: For each project on which more than 3 employees work. retrieve the project number. and the number of employees who work on that project. and the number of employees who work on that project. ExampleExample-6: Print the number of employees whose salaries exceed more than Rs. Display the department name also.

Student_id char(10). Grade char(1)) BN Shankar Gowda. Salary number(10. GPA number(3. FName char(4).1)) Faculty( Faculty(Faculty_id char(4). Faculty_id char(4)) Enrol( Enrol(Course_id char(5). SName varchar2(10). Desig varchar2(5). Major varchar2(5). Dept varchar2(5).2)) Course( Course(Course_id char(5). CName varchar2(10).STUDENT Database Example Student( Student(Student_id char(10). BIT 63 .

64 . ExampleExample-2: List the names of students enrolled for the course 'IS6T1' and have received 'A' grade. SELECT SName FROM Student WHERE Student_id In( SELECT Student_id FROM Enrol WHERE Course_id = 'IS6T1'). 10000. SELECT SName FROM Student WHERE Student_id In( SELECT Student_id FROM Enrol WHERE Course_id = 'IS6T1' AND Grade = 'A'). BIT > 10000. ExampleExample-3: List all the departments having an average salary of above Rs.ExampleExample-1: List the names of all students enrolled for the course 'IS6T1'. SELECT Dept FROM Faculty GROUP BY Dept HAVING AVG(Salary) BN Shankar Gowda.

SELECT FROM WHERE FName Faculty SUBSTR(FName.- BN Shankar Gowda.1.1) LIKE 'P' AND SUBSTR(FName. SUBSTR(FName.-2. BIT 65 .1) LIKE 'A'.ExampleExample-5: List the names of all faculty members beginning with 'P' and ending with letter 'A'.

Price : Int) CATEGORY (Categorid : Int.More Examples Book Dealer Database AUTHOR (Authorid : Int. BIT 66 . ear : Int. Name : String. Title : String. Name : String. Country : String) CATALOG (Bookid : Int. Country : String) PUBLISHER (Publisherid : Int. Publisherid : Int. City : String. Quantity : Int) BN Shankar Gowda. City : String. Description : String) ORDER_DETAILS (OrderNo : Int. Bookid : Int. Authorid : Int. Categoryid : Int.

BIT 67 . A. A.AName from Catalog C.Queries Give the details of the authors who have 2 or more books in the catalog and the price of the books is greater than the average price of the books in the catalog and the year of publication is after 2000.Year > 2000 and C. Author A where A.Authorid. BN Shankar Gowda.AName having count(C.Authorid.Price > (Select Avg(Price) from Catalog) group by C.Authorid = C.Authorid and C.Authorid) >= 2. Query select C.

Find the number of the book which has maximum sales.Authorid = A.Bookid as Book#.Authorid = C.Bookid and sales = (select Max(Sales) from salesdetails).Authorid group by OD. catalog C.Authorid and S.Sales from Author A.Price) as Sales from Order_Details OD.AName.Bookid and C. Sum(OD. BN Shankar Gowda.Price as Cost.S. Sum(OD.Price). select Salesdetails S where A. A. Author A where OD. S.Book# = C. Catalog C.Quantity) as Qty. BIT 68 . Create View SalesDetails as ( Select OD.Authorid.Bookid. C.Quantity * C.Bookid = C. C.

Dept : String) ENROLL (RegNo : String. Marks : Int) BOOK_ADOPTION (Course# : Int. Publisher : String. BIT 69 . BookTitle : String.Student Enrollment Database STUDENT (RegNo : String. Sem : Int. ISBN : Int) TEXT (ISBN : Int. Sem : Int. Author : String) BN Shankar Gowda. BDate : date) COURSE (Course# : Int. CName : String. Major : String. Course# : Int. Name : String.

Produce a list of text books (include Course#.Course# and BA.Course# = BA. T. Text T where C. ISBN.ISBN.BookTitle from Course C.Dept = 'CSE' group by C.BookTitle.ISBN = T.ISBN. T.ISBN and C.Course#. T.Course#. BIT 70 . T. BookTitle) in the alphabetical order for courses offered by the 'CS' department that use more than two books Select C.Book_Adoption BA. BN Shankar Gowda.

BIT 71 .End of Chapter 5 BN Shankar Gowda.

Sign up to vote on this title
UsefulNot useful