Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 33

Relational Database Management System (17332)

Experiment No: 1.2

EXPERIMENT NO. 1.2 1.0 Title: Design and normalize a database up to three normalization form

2.0 Prior Concepts: Database, Relations, Tables, Tuples, Attributes, Domain, Primary key, Foreign Key, Entity, ER diagrams 3.0 New Concepts: Proposition 1: Normalization : Normalization is a body of rules addressing analysis and conversion of data structures into relations. Resultant relation exhibit more desirable properties of internal consistency, minimal redundancy and maximum stability. Proposition 2 : Different forms of Normalization Dr Codd, founder of relational databases has defined them as First, Second and Third normal forms. Later Boyce Codd Normal form (BCNF), fourth and fifth normal forms are derived. Proposition 3 : Normalization Process. Normalization process best can be explained with the example. The following example will be used to explain First, Second and Third normal forms. Consider the data structure of an order as it appears on an order form. Order 1. orderno 2. orderdate 3. customerno 4. itemno 5. itemname 6. qtyordered As many as items ordered in the order 7. rateperunit 8. itemvalue Order has unique order number. Order date is the date on which date the order is placed by a customer having customer number. One or more items may be ordered in an order which would contain details of multiple items. Item value is qtyordered multiplied by rateperunit. Rate per unit is independent of itemno or itemname. Proposition 4: First Normal Form : A relation is in the first normal form if it does not contain any repeating elements groups. The domain of an attribute must have atomic values. Since above example does contain repeating groups of item details, hence it is not in first normal form. To convert a relation into the first normal form remove all repeating (or multivalued) attributes to another (child) relation. Above order relation can be split into two relations order and orderitem as follows. Order Orderitem orderno (Primary key) orderno Primary key orderdate itemno customerno itemname qtyordered rateperunit itemvalue Here key element orderno had to be duplicated in the orderitem relation. It facilitates the linking of the rows in the orderitem relation to the rows in the order table. After eliminated repeating element or groups in both the tables, these relations are now in the First Normal Form

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION

Relational Database Management System (17332)

Experiment No: 1.2

Proposition 5: Second Normal Form A relation is in the second normal form if it is in the First normal form and all non key attributes are fully functionally dependent on the primary key. If we examine the orderitem relation we find that itemname is not fully functionally dependent on the full primary key (orderno + itemno) as it is functionally dependent on partial key itemno. Here it is not necessary to know orderno to determine itemname as we can determine it from itemno alone. Advantage: Second normal form simplifies the anomalies such as insert, update and delete operations. If name and item is changed then it has to be changed in all item rows where it occurs. If not taken care database will not be in consistent state. Thus a relation in 1NF can be converted into 2NF by removing attributes that are not dependent on the full primary key. Proposition 6:Third Normal Form : A relation is in the third normal form if it in the second normal form and every non key attributes is non transitively dependent on primary key or a relation is in third normal form, if it is in 2 NF and every attribute is independent on other non key attribute. If we examine orderitem relation. It is clear that item value can be derived from Qtyorder and rateperunit hence each of these three attributes dependent on other two attributes, thus we can transfer 2NF into 3NFas Orderitem *orderno Primary key *Itemno Qtyordered Rateperunit We could have removed one out of three by keeping other two. Normalization rules does not specify which to discard and which to retain. Thus our original relation order is now transformed into three relations as shown below. Order Order item item *Orderno Orderno *itemno Orderrate itemno itemname CustomerNo Qtyordered Rateperunit 4.0 Learning Objectives : Intellectual Skills : 1. Understand the basics of a database 2. Organize the data by applying normalization rules Motor Skills : 1. 2. 3. 5.0 Ability to handle keyboard and mouse. Ability to work with editor. Ability to draw and represent separate entities

Sample Examples : 5.1 Following table shows student code, student name and percentage, their multiple courses and their marks as shown in marks table format. Whether this table in NF? How to convert this table into a normalized table. Student code S1 S2 S3

C1-86, C2-45, C3,48, C1,59, C3,72, C5,68, C1,56 per 66 (fig-1)

C4,58, C5,62, per 59.8 per 66.33

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION

Relational Database Management System (17332)

Experiment No: 1.2

If S1, S2, S3 are the students having names Rajat Bhatia, Meenal Joshi and Sopan Patil respectively. Also the C1, C2, C3, C4, C5 are the courses having names as English, Mathematics, Physics, Statistics and Accounting respectively. How will you design the tables by applying rules of normalization? Identify the primary key and foreign key of each table. Database must be normalized to minimum of 3NF.(Note: this normalized database is to be used in experiment no.9)

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

6.0

Questions for confirmation of Learning Fill in the blanks (join, atomic, functional, multivariate, transitive) 1. 1NF contains ----------------values. 2. 2NF removes 3. 3NF remove 4. 4NF eliminates 5. 5NF removes ----------------------------------------------------------------dependencies. dependencies. dependencies. dependencies.

7.0

Students Activity 1. Can figure-1 be represented in the form of figure2 as shown? Whether figure2 in 1NF? If yes what are the advantages and disadvantages? Why this design practically not considered.

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION

Relational Database Management System (17332)

Experiment No: 1.2

Student code S1 S2 S3

Course1 C1 C1 C1

M1 86 59 56

course2 C2 -

M2 45 -

Course3 C3 C3 -

M3 48 72 -

course4 C4 -

M4 58 -

course5 C5 C5 -

M5 62 67 -

(figure2) -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

8.0

Questions 1. What is normalization? What is its advantage? ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------2. Define functional dependency? ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------3. What is the minimum level of normalization data base designers aimed at? Why? ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------4. Define BCNF. Explain with appropriate example.

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION

Relational Database Management System (17332)

Experiment No: 1.2

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

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------C (4) P (4) A(2) T (10) Signature of Teacher

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION

Relational Database Management System (17332)

Experiment No: 4.1

EXPERIMENT NO. 4.1 1.0 Title: Write and execute queries using arithmetic, comparison and logical operators 2.0 Prior Concepts: Data Manipulation Language (DML) 3.0 New Concepts: Proposition 1 : Operator: An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations Proposition 2 : Types of Operators : There are three types of operators: 1. 2. 3. Arithmetic Operators. Comparison / relational Operators. Logical Operators.

Proposition 3 : Arithmetic Operators : Operator + * / + Description Negation Identity Multiplication Division Addition Subtraction Example -sal +sal sal * 1.1 sal / 12 sal + comm. sal comm. Precedence 1 1 2 2 3 3

Proposition 4 : Comparison Operators : It is used to compare one expression with another using comparison operators.SQL uses either symbolic operators or predicates (word comparison) operators

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION

Relational Database Management System (17332)

Experiment No: 4.1

SQL's Comparison Operators symbol Use Description a=b Equal to, Tests for equality of two operands. = != ^= <> < a != b a ^= b a <> b a<b Not equal to, Tests for inequality of two operands. Can use any one.

Example select * from emp where sal =500 select * from emp where sal !=500 select * from emp where sal <500 select * from emp where sal !<500 select * from emp where sal >500 select * from emp where sal !>500 select * from emp where sal <=500 select * from emp where sal >=500 Example select * from emp where sal in (500,600,700) select * from emp where sal not in (500,600,700) select * from emp where sal = any (500,600,700)

Less than, Tests that operand a is less than operand b. a !< b Not less than, Tests that operand a is not less than !< operand b. This is the same as >=. a>b Greater than, Tests that operand a is greater than > operand b. a !> b Not greater than, Tests that operand a is not greater !> than operand b. This is the same as <=. a <= b Less than equal to,Tests that operand a is less than <= or equal to operand b. This is the same as !>. a >= b Greater than equal to, Tests that operand a is greater >= than or equal to operand b. This is the same as !<. Word Comparison operators Keyword Use Description a IN (b,c...) Tests that operand a matches at least one IN element of the list provided (operand b, operand c, etc.). a NOT IN Tests that operand a does not match any NOT IN (b,c...) element of the list provided (operand b, operand c, etc.). a = ANY Tests that the relationship specified (e.g., =, ANY (b,c...) <>, <, >, etc.) is true for at least one element a < ANY of the list provided (operand b, operand c, (b,c...) etc.). When testing for equality, this is a > ANY equivalent to IN. (b,c...), etc. a = SOME Tests that the relationship specified (e.g., =, SOME (b,c...) <>, <, >, etc.) is true for at least one element a < SOME of the list provided (operand b, operand c, (b,c...) etc.). When testing for equality, this is a > SOME equivalent to IN. (b,c...), etc. a = ALL Tests that the relationship specified (e.g., =, ALL (b,c...) <>, <, >, etc.) is true for every element of the a < ALL list provided (operand b, operand c, etc.). (b,c...) a > ALL (b,c...), etc. a Tests that operand a is greater than or equal BETWEEN to operand b and less than or equal to BETWEEN b and c operand c. The range which is specified will contain min value and max value. It is used for numeric and date data type a NOT Tests that operand a is less than operand b NOT or greater than operand c. It test the range BETWEEN BETWEEN b and c other than b to c EXISTS EXISTS Tests that the query returns at least one row. (query)

select * from emp where sal = some (500,600,700)

select * from emp where sal > all (500,600,700)

select * from emp where sal between 400 and 600

NOT

NOT

Tests that the query does not return a row.

select * from emp where sal not between 400 and 600 select * from emp e where exists (select deptno from dept d where deptno= e.deptno) select * from emp e

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION

Relational Database Management System (17332)

Experiment No: 4.1

EXISTS

EXISTS (query) a LIKE b Tests that operand a matches pattern operand b. The pattern may contain _ which matches a single character in that position, or % which matches all characters. Tests that operand a does not match pattern operand b. The pattern may contain _, which matches a single character in that position, or %, which matches all characters. Tests that operand a is NULL. Null value means no value or an unavailable, unassigned, unequal to any value or zero length of string in a data cell Tests that operand a is not NULL.

LIKE

where not exists (select deptno from dept d where deptno=e.deptno) Select * from emp where ename like `smi%' select * from emp where ename not like `smi%' select * from emp where comm is null select * from emp where comm is not null

NOT LIKE

a NOT LIKE b

IS NULL

a IS NULL

IS NULL

NOT

a IS NULL

NOT

Proposition 5: Logical Operator: Logical operators that are similar to those available in most other programming languages. The logical operators AND and OR combine the results of two Boolean values to produce a single result based on them, while the logical operator NOT inverts a result. The Boolean values may be any expression that can be evaluated to TRUE or FALSE. Operator Use Description Example Exp1 AND AND means expression is true if and only if Select * from emp where sal AND exp2 both exp1 and exp2 are true >10000 and job=Clerk OR NOT Exp1 ORexp2 NOT exp OR means expression is true if either of exp1 or exp2 or both are true If expression is true not make it false or vice versa Select * from emp where sal >10000 or job=Clerk Select * from emp where NOT (sal >10000)

4.0 Learning Objectives: Intellectual Skills: 3. Understand the use of DML commands. 4. Understand the use of operators. Motor Skills: 4. 5. 5.2 Ability to handle keyboard and mouse. Ability to work with editor.

Sample Examples : Write the queries for the following and write the output in the space provided. If output is more than two rows write only first two rows. Show columns as they appear in output 5.1 SQL> Output Display unique jobs from emp table Select distinct (job) from emp;

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION

Relational Database Management System (17332)

Experiment No: 4.1

5.2 SQL> Output

List the employees whose salary is more than 3000 after giving 20% increment Select EMP.*, SAL+ (SAL*.2) incrsal from emp where SAL+(SAL*.2) >3000;

5.3 SQL> Output

List the employees, department number who does not belong to department 20

5.4 SQL> Output

List the employee name, salary whose annual salary does not fall from 22000 to 45000

5.5 SQL> Output

List all employee number, employees, job, joined before 1981

5.6 SQL> Output

List all the employee numbers, employees, job except President & Mgr

5.7 SQL> Output

Display names all employees whose name is 5 characters long

5.8 SQL> Output

Display all employees working under manager John or salary greater than 20000

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION

Relational Database Management System (17332)

Experiment No: 4.1

5.9 SQL> Output

Write query to get output in following format

Empno

Ename

jobs

Sal

Daily salary

Annual salary

5.10 SQL> Output

Display the name of employee who does not work under any manager

6.0

Questions for confirmation of Learning: 6.1 SQL> Write the above query number 5.4 by using other operator? What are the options to check range of values

6.2

What NULL data type represents? Why it is used? How to check values for NULL? -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

7.0

Students Activity 7.1 Create the following table with appropriate data types and add the data in the table as shown.

8.0

Questions Client Table Client no. Name C001 Vikas Jain C002 V Chandran

City Mumbai Chennai

Pincode 400054 780001

State Maharashtra Tamilnadu

Balance due 15000 0

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION

Relational Database Management System (17332)

Experiment No: 4.1

C003 C004 C005 C006

Pramod Patil Jatin Sapru Virat Kohli Vilas Pendse

Mumbai Mumbai Delhi Mumbai

400057 400056 100001 400050

Maharashtra Maharashtra Maharashtra

5000 0 2000 0

Write the queries for the following and write the output as displayed: 8.1 Find the names of all clients and their city. SQL> Output

8.2 SQL> Output

Find all the clients having i as second letter in their name

8.3 SQL> Output

Find all the clients who does not stay in Mumbai OR Chennai

8.4 SQL> Output

Print all the clients whose balance due is greater than value 10000..

8.5 SQL> Output

. Display all clients having balance below 2000 and above 3000

8.6 SQL> Output

List all names having name consist of five alphabets only

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION

Relational Database Management System (17332)

Experiment No: 4.1

8.7 SQL> Output

List the information of client whose state is unknown.

8.8 SQL> Output

Find distinct cities of clients

8.9 SQL> Output

Find the revised baldue if 20 % discount is given to each client

8.10

Write a procedure to Create output file client. For (1) Spool the output of all above queries in to a text file client. (2) Set the default editor to notepad. -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

SQL> SQL>

C (4)

P (4)

A(2)

T (10)

Signature Teacher

of

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION

Relational Database Management System (17332)

Experiment No: 4.2

EXPERIMENT No. 1.0 Title:

4.2

Write and execute the queries using string and numeric functions 2.0 Prior Concepts: Data Manipulation Language (DML), operators in SQL 3.0 New Concepts: Proposition 1:Function: Functions are the ready to use code written and tested by expert. User just need to know how to use it by passing the required value and get the required answer. It may have one or more argument and return a value Character functions: It accepts character input and returns either character or number. Function Name Initcap(char) Lower(char) Upper(char) Ltrim(char,set) Length(char) Chr(n), Ascii(char) Rtrim(char,set) Substr(char,m,n) Instr(char1, char2,[,n [m]] Description Returns the input string with initial letter capitalized and all other character in lower case. Returns the input string with all letters in lower case. Returns the input string with all letters in Upper case. It removes or trims from the left of character string. It returns the length of character string. Returns a character binary equivalent of n Returns a decimal representation of a character It removes or trims specified set from the right of character string. It returns a portion of char, beginning at a character m, n character long, m can be +ve or ve, n cannot be less than 1. Searches char 1 beginning with its nth character for the mth occurrence of char2 and return the position of character .i.e. the first character of this occurrence. It returns character string with each occurrence of searchstring replaced with [repstring]. It returns char with all occurrences of each character in from replaced by its corresponding character in to. Character in char that are not in from are not replaced. It returns char 1 left-padded to given length with the sequence of characters in char 2; It returns char 1 right-padded to given length with the sequence of characters in char 2; Char 1 is concatenated to char 2 It merges two or more string value together. It is similar to concatenation operator || Returns a character string containing the phonetic representation of char. This allows to compare words that are spelled differently but sound alike in English

Replace(char, searchstring, [repstring]) Translate(char, from, to)

Lpad(char1,length,char2) Rpad (char1,length,char2) Concat(char1, char2) Soundex(char)

Numeric Functions: Numeric Functions accepts the numeric value as the input and it returns the numeric value as the output Function Name Description Abs(n) (Where number) Power(m ,n) n is a Returns the absolute value of the n It returns m raised to nth power.

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION

Relational Database Management System (17332)

Experiment No: 4.2

Mod(m, n) Sqrt(n) Exp(n) Round(n,[ m]) Trunc(n, m) Ceil(n) Floor(n) Cos(n) Cosh(n) Sin(n) Sinh(n) Tan(n) Greatest(expr, [expr], ) Least(expr, [expr], ) 4.0 Learning Objectives : Intellectual Skills :

Returns the reminder of m divided by n. It returns square root of n. n cannot be negative Returns the e raised to power of the n. Returns n rounded to m places right of the decimal point. Returns n truncated to m decimal places. Returns the smallest integer that is greater or equal to n. Returns the largest integer that is equal or less than n. Returns the cosine of the n. Returns the hyperbolic cosine of the n Returns the sine of the n. Returns the hyperbolic sine of the n Returns the tangent of the n. Return the greatest of list of expression Return the least of list of expression

5. Understand the use of DML commands. 6. Understand the use of operators with arithmetic and string function 7. Use arithmetic and string functions. Motor Skills : 6. 7. 5.3 Ability to handle keyboard and mouse. Ability to work with editor.

Sample Examples : Character Functions S.No. 1 2 3 4 5 6 7 8 9 10 11 12 Example Select initcap(ename)from emp where empno=7369; Select lower(HELLO)from dual; Select lower(ename)from emp where empno=7369; Select upper(Hello)from dual; Select upper(ename)from emp where empno=7369; Select ltrim(Rajesh,Raj)from dual; Select ltrim(ename,Raj),from emp where empno=7369 ; Select rtrim(ename,sh) from emp where empno=7369; Select length(dname) from dept where deptno=20; Select chr(65) from dual; Select ascii(A) from dual; Select substr (ename,1,3)from dept; Output

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION

Relational Database Management System (17332)

Experiment No: 4.2

13 14 15 16 17 18 19 20

Select ename, instr(ename,jesh) from emp where empno=7369; Select replace(Tick and Tack,T,C)from dual; Select replace(ename,Ra,xy) from emp; Select translate(ename,a,i)from emp where empno=7782; Select lpad(ename,10,*), rpad(ename,10,*) from emp; Select ename from emp where =soundex(Rokesh) where empno=7839; soundex(ename)

Select ename || || job from emp where empno=7369; select concat (concat (ename, ' is a '),job) from emp where sal > 50000;

Numeric Functions W S.No. Example 1 2 3 4 5 6 7 8 9 10 11 12 13 Select abs(-7.5) from dual; Select power( 2,10) from dual; Select mod(11,3) from dual; Select sqrt(64) from dual; Select exp(2) from dual Select sal, round(sal,-3) from emp where empno=7369; Select sal, trunc(sal,-3) from emp where empno=7369; Select ceil(14.3) from dual; Select floor(14.7) from dual; Select sin(90) , cos(0) from dual; Select tan(45) acos(90) from dual; Select sal,greatest(sal,500) from dual; Select sal, least(sal, 1000) from dual;

Output

6.0

Questions for confirmation of Learning: 6.1 Write the query to get the output in following statement 7566 employee number belongs to employee name --------, who works as ------------ of department number ----- and joined on ------- having salary --------Sql>

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

6.2 What is dual table? What it contains? How it works? Why it is provided ---------------------------------------------------------------------MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION

Relational Database Management System (17332)

Experiment No: 4.2

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

6.3 State difference between following with help of example: Replace Translate

Floor

Ceil

Round

Truncate

7.0

Students Activity: Write the queries and output for the following 7.1 SQL> Output Find the data of employee vijay in emp table irrespective of how it is stored in a table (Vijay, VIJAY etc) Write a single query to display your best friends name

7.2 SQL> Output

7.3 SQL> Output

Display the data for those employees whose last names end with an n.

7.4

calculates the remainder of the salary after dividing it by 5,000

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION

Relational Database Management System (17332)

Experiment No: 4.2

SQL> Output

7.5 SQL> Output

Display the salary of employees rounded to 1000 only

Produce the following output from EMP 7.6 EMPLOYEE ---------------SMITH(clerk) SQL> Output select ename || '(' || lower(job) ||')' EMPLOYEE from emp

7.7 SQL> Output

List all the 4 character employees. SQL>Select ename from emp having length (ename) = 4

7.8 SQL> Output

List first 50% of chars of ename in lower case select ename, lower(substr(ename,1,length(ename)/2))

C (4)

P (4)

A(2)

T (10)

Signature Teacher

of

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION

Relational Database Management System (17332)

Experiment No: 5.0

EXPERIMENT No. 1.0 Title:

Learn and use different date formats, date functions and data type conversion from one type to another 2.0 Prior Concepts: Data Manipulation Language (DML), operators in SQL 3.0 New Concepts: Proposition 1: Date and time formats: Default data for date type is DD-MMM-YY, Once data stored in date formats it can be displayed in any format by combination of one or more data formats as shown in following table. Format mask Description CC or SCC Century prefixes BC dates with - YYYY or SYYY Year with 4 digit number, prefixes BC dates with - YYY, YY, Y Year with 3, or 2 or 1 digit RR Year with 2 numbers with Y2k compatibility YEAR Year in characters BC BC/AD Indicator * Q Quarter in numbers (1,2,3,4) MM Month of year 01, 02...12 MONTH Month in characters (i.e. January) MON JAN, FEB WW Week number (i.e. 1) W Week number of the month (i.e. 5) DDD Day of year in numbers (i.e. 365) DD Day of the month in numbers (i.e. 28) D Day of week in numbers(i.e. 7) DAY Day of the week in characters (i.e. Monday) DY Day of the week in short character description (i.e. SUN) J Julian Day (number of days since January 1 4713 BC, where January 1 4713 BC is 1 in Oracle) HH Hour number of the day (1-12) HH12 Hour number of the day (1-12) HH24 Hour number of the day with 24Hours notation (0-23) AM or PM AM or PM, Meridian Indicator MI Number of minutes (i.e. 59) SS Number of seconds (i.e. 59) SSSSS Number of seconds this day. RM The Roman numeral representation of the month (I .. XII) SP Spelled format. Can appear of the end of a number element. The result is always in english. For example month 10 in format MMSP returns "ten" SPTH Spelled and ordinal format; 1 results in first. TH Converts a number to it's ordinal format. For example 1 becoms 1st. TS Short time format. Depends on NLS-settings. Use only with timestamp. Number fmt model Format 99999 999,999.99 0999,999.99 B999,999.99 $999,999.00

Description 5-digits integer 6-digit value with 2-digit decimal zero-fill column blank spaces dollar sign prefix

Date Manipulation Functions:


MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION

Relational Database Management System (17332)

Experiment No: 5.0

Sr.No. 1.

Format Month_between(d1,d2) where d1 and d2 are dates.

2.

3.

4.

add_months(d,n) where d-date, n-number of months to be added to the date. next_day(d,char) where d-date, char-day of week. Last_day(d) Where d-date.

Description Months_between finds the number of months between d1 and d2. If date d1 is later than d2 the result is positive. If date d1 is earlier than d2 the result is negative. Return date after addingthe number of months specified with the function. Return the date of the first weekday named char that is later than date d. Return the last day of the month that contain date d. Used to determine how many days left in a month. Return date rounded to the unit specified by the format model fmt. If the format model fmt is omitted, date is rounded to the nearest date.

round(date,[fmt]) where fmt-format model: Month Day Year 6. trunk(date,[fmt]) Return date with the time portion of the day where fmt-format model: truncated to the unit specified by the format Month model fmt. If the format model fmt is omitted, Day date is truncated to the nearest day. Year Data conversion functions: To use different functions such as string, numeric and date type we need to convert data into appropriate data type to pass as argument. Following are the commonly used functions for data conversion Sr.No. Format Description 1. To_date(expr,[fmt]) where fmt- It converts number or character string into date format model, expr- format. expression, either numbers or a NOTE: character string. Fmt- is the 1) If expression is character and without format default date fmt model. model, it must be of the form DD-MMMYY.Number cannot be defined without format model. 2) Date format cannot be defined using COLUMN command. 2. To_char(expr,[fmt]) where expr It converts either date or value into a character string. number / date, If fmt is not specified and- if expr is a number, a 1. if expr is date, fmt is date fmt character string long enough to accommodate the model. significant digits of the number is created.-if expr is a 2. if expr is number, fmt is date, a string of the form DD-MMM-YY is created. number fmt model. GUIDELINES : 1) If a number is larger than defined format.pound sign (#)appear in place of the value. 2) Decimals are rounded off to fit into the format model. 3. To_number(char) It converts a character string containing a number into a number data type. 4.0 Learning Objectives : Intellectual Skills : 8. Understand the use of DML commands. 9. Understand the use of operators. 10. Use of appropriate date formats and date functions Motor Skills : 8. Ability to handle keyboard and mouse.
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION

5.

Relational Database Management System (17332)

Experiment No: 5.0

5.4

9. Ability to work with editor. Sample Examples : Date Functions S.No. 1 2 3 Example Select add_months(hiredate,2) from emp where empno=7369; Select sysdate ( ) from dual Select months_between(to_date(02-02-2010), MM-DD-YYYY), to _date(01-01-2012, MM-DD-YYYY) Month from dual Select months_between (05-MAY-1996, 05-JAN-1996) Months from dual; Select add_months(sysdate,1) from dual; Select next_day(01-FEB-2006, Wednesday) next_day from dual; Select last_day(sysdate) last from dual; Select round(sysdate, day) round_day from dual; Select trunc(sysdate, day) trunc_day from dual; Select round(sysdate, Month) round_month from dual; Output

4 5 6 7 8 9

Select trunc(sysdate, year) trunc_year from dual; Date formats S.No. 1 Example List the emps with hiredate in format June 4,1988 SQL>select ename, to_char (hiredate,'Month DD,YYYY.') from emp Display hiredate in DD/MM/YYYY format of first employee SQL> Display 20 SQL>
th

Output

3 4 5

October 1999 in the date format

Display hire date in HH:MM:SS format SQL> Display date in AM/PM format SQL>

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION

Relational Database Management System (17332)

Experiment No: 5.0

Data Conversion functions S.No. 1 Example Use of to_char function SQL>select ename, to_char (hiredate,'Month DD,YYYY.') from emp Output

2 3

Use of to_date function Use of to_number

6.0

Confirmation of Learning: 8.1 Write a query to get the output as SQL> Mr John manager of department number 30 joined on 1 MAY (Friday), Nineteen Hundred Eighty one Output 8.1 SQL> Output 7.0 Students Activity Write any five combinations of date format and there output Date format Output 1 2 3 4 5 Questions : 8.1 Write a query to form a string by combining empno, ename and mgr code SQL> 8.2 SQL> Output Write the output of the following Select To_char(hiredate, ddth of Month yyyy) from emp; List the emps whose exp is more than 10 years SQL>select * from emp where months_between(sysdate,hiredate)/12 > 10
st

8.0

8.3 SQL> Output

List the empno, ename, sal of all the Mgrs and Analyst having an experience more than 7 years select empno, ename,sal from emp where job in('manager','analyst') and months_between(sysdate,hiredate)/12 > 7

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION

Relational Database Management System (17332)

Experiment No: 5.0

8.4 SQL> Output 8.5 SQL> Output 8.6 SQL> Output 8.7 SQL> Output 8.8 SQL> Output

To convert string January 01 2007 into date: Select To_date(January 01 2007, Month-dd-yyyy) from dual;

To display your own birth date as : 6 june 2013 Select stud_id, To_char(DOB, mm/yyyy) Date of Birth from stud_info;

th

To display the salary of employee in format $99,999.

Display date in military format

Display salary with leading zero 8 digits with two decimal points

C (4)

P (4)

A(2)

T (10)

Signature of Teacher

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION

Relational Database Management System (17332)

Experiment No: 6.2

EXPERIMENT NO. 6.2 1.0 Title : To write and execute queries using aggregate functions. Set operators and sub queries 2.0 Prior Concepts Data manipulation language (DML), Function concept 3.0 New Concepts : Proposition 1: Aggregate/ Group functions: Aggregate functions returns result based on group of rows. Unlike single-row functions, group functions operate on sets of rows to give one result per group.These sets may be the whole table or the table split into groups

Group Functions avg([distinct|all]n) count({*|[distinct|all]expr})

max([distinct|all]expr) min([distinct|all]expr) sum([distinct|all]n) stddev([distinct|all]x) variance([distinct|all]x)

Average value of n, ignoring null values Number of rows, where expr evaluates to something other than null (count all selected rows using *, including duplicates and rows with nulls) Maximum value of expr, ignoring null values Minimum value of expr, ignoring null values Sum values of n, ignoring null values Standard deviation of n, ignoring null values Variance of n, ignoring null values

Min and max functions can be used for any data type but avg, sum, variance, and stddev functions used only with numeric data types Proposition 2: Set operators:

AUB(union all)

A B (intersection)

A-B (minus)

B-A(minus)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION

Relational Database Management System (17332)

Experiment No: 6.2

Operator Union

Output The UNION operator returns results from both queries after eliminating duplications. It is equivalent to OR Union All All rows selected by either query, including all duplicates Intersect Only common rows selected by both queries. Equivalent to AND Minus All rows returned by the first query that are not present in the second Query Requirement: The number of columns and the data types of the columns being selected must be identical in all the SELECT statements used in the query. The names of the columns need not be identical. The output is sorted in ascending order of the first column of the SELECT clause Proposition 3: Subqueries Subqureis: It is a query which is embedded inside a main query or a outer query. It is also called the inner query or the subquery. It returns a value that is used by the main query. Using a subquery is equivalent to performing two sequential queries and using the result of the first query as the search value in the second query. select ename from emp where sal > (select sal from emp where ename = Vijay); Here inner query determines the salary of employee Vijay. The outer query takes the result of the inner query and uses this result to display all the employees who earn more than this amount. Types of subqueries A single-row subquery is one that returns one row from the inner select statement. This type of subquery uses a single-row operator.(<, >, <=, >=, = ,<> ) Example Display the employees whose job is the same as that of employee number 7788. select ename, job from emp where job = (select job from emp where empno = 7788); Multiple-Row Subqueries Subqueries that return more than one row are called multiple-row subqueries. Subquery uses a multiple-row operator, instead of a single-row operator( IN, ANY, ALL) , with a multiple-row subquery. The multiple-row operator expects one or more values. select ename, sal, deptno from emp where sal IN (select min(salary) from emp group by deptno); Sub queries have the following characteristics: Can pass one row of data to a main statement that contains a single-row operator, such as =, <>,>, >=, <, or <= Can pass multiple rows of data to a main statement that contains a multiple-row operator, such as IN Are processed first by the Oracle server, and the WHERE or HAVING clause uses the results Can contain group functions 4.0 Learning Objectives: Intellectual Skills: 1. Understand concept of group functions. 2. Use aggregate functions. 3. Understand and use sub queries 4. Write queries using sub queries Motor Skills: 1. Ability to handle keyboard and mouse 2. Ability to work with editor. 5.5 Sample examples on aggregate functions Sample Queries Find min salary of employee Find total salaries of employees Find the maximum salary of employee
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION

Output

Relational Database Management System (17332)

Experiment No: 6.2

List the details of highest paid employee SQL>Select * from emp where sal = (select max(sal) from emp) Find the max avg salary drawn for each job except for PRESIDENT SQL>select job, max(sal), avg(sal) from empwhere job <> 'PRESIDENT' Find the total number of employees in emp table Find standard deviation of salaries Find the variance of salaries

Sample examples on set operators Sample Queries Use of Union operator: Find distinct jobs from employee and workers table SQL>

Output

Use of Union All operator: Find all names of employees and workers SQL>

Sample examples on sub queries Sample Queries Display details of all employees having salary more than John salary SQL>select * from emp where sal > (select sal from emp where ename = 'John')

Output

6.0

Questions for Confirmation of Learning: 1. Group functions work across many rows to produce one result per group. (True/False) 2. Group functions include nulls in calculations. (True/False) 3. Display the highest, lowest, sum, and average salary of all employees. Label the Columns Maximum, Minimum, Sum, and Average, respectively. SQL> Output

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION

Relational Database Management System (17332)

Experiment No: 6.2

4. Write a query to display the last name and hire date of any employee in the same department as Savita by excluding Savita. Queries display the number of employees in department 80 who can earn a commission SQL> select count(commission_pct) from employees where department_id = 80 display the number of distinct department values in the employees table sql> select count(distinct department_id) from employees; 7.0 Student Activity Write the queries for the following 8.1 Find the highest Sal of the Emp table. SQL> Output Select Max(sal) from emp Output

8.2 SQL> Output

Find the details of highest paid employee. Select * from emp where sal = (select Max(sal) from emp)

8.3 SQL> Output

Find the total salaries given to the managers select sum(sal) from emp where job = 'MANAGER'

8.4 SQL> Output

Display the average salaries of all CLERKS select avg(sal) from emp where job = 'CLERK'

8.5 SQL> Output

List the details of the emps whose job is same as ALLEN select * from emp where job = (select job from emp where ename ='ALLEN')

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION

Relational Database Management System (17332)

Experiment No: 6.2

8.6 SQL> Output

List the emps of deptno 20 whose jobs are same as deptno 10 Select * from emp where deptno=20 and job in (select job from emp where deptno=10)

8.7 SQL> Output

List the emps whose Jobs are same as Abraham or Sal is more than Sachin. Select * from Emp where job = (select job from emp where ename=Abraham) OR Sal > (select sal from emp where ename='Sachin')

C (4)

P (4)

A(2)

T (10)

Signature of Teacher

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION

Relational Database Management System (17332)

Experiment

EXPERIMENT No. 9 1.0 Title: Design and implementation of views 2.0 Prior Concepts: Data Manipulation Language (DML), Data Definition language( DDL) 3.0 New Concepts: Proposition 1 : Views : Logically represents subsets of data from one or more tables. A view is a logical table based on a table or another view. A view contains no data of its own but is like a window through which data from tables can be viewed or changed. The tables on which a view is based are called base tables. The view is stored as a select statement in the data dictionary. A view does not contain data. The definition of the view is stored in the data dictionary. The definition of the view is stored in the USER_VIEWS data dictionary table Syntax to create views create [or replace] view <view-name> [(<column(s)>)] as <select-statement> [with check option [constraint <name>]]; The optional clause or replace re-creates the view if it already exists. A view is evaluated again each time it is accessed Different options of View Can be a simple view, based on one table Can be a complex view based on more than one table or can contain groups of functions Can replace other views with the same name Can contain a check constraint Can be read-only Advantages of Views Views restrict access to the data because the view can display selective columns from the table. Views can be used to make simple queries to retrieve the results of complicated queries. For example, views can be used to query information from multiple tables without the user knowing how to write a join statement. Views provide data independence for ad hoc users and application programs. One view can be used to retrieve data from several tables. Views provide groups of users access to data according to their particular criteria. Thus implements security and authorization. Creating a View: Create a view, EMPVU20, that contains details of employees in department 20. create view empvu20 as select empno, ename, sal from emp where deptno = 20; Retrieving Data from a View Data is retrieved from a view as you would from any table. You can display either the contents of the entire view or just specific rows and columns. Select * from empv20; Modifying a View: With the or replace option, view can be altered without dropping, re-creating, and regranting object privileges Creating a Complex View Create a complex view of employee and department information. Note that alternative names have been specified for the view. Create view dept_vu (empno, ename, job, salary,deptno, dname, daddress) as select empno, ename, job, sal, deptno, dname, loc from emp, dept where emp.deptno= dept.deptno group by dept.dname;
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION 28

Relational Database Management System (17332)

Experiment

Removing a View you use the drop view statement to remove a view. the statement removes the view definition from the database. dropping views has no effect on the tables on which the view was based drop view viewname restrictions on views: you cannot remove a row from a view it contains any of the following: group functions a group by clause the distinct keyword .4.0 Learning Objectives : Intellectual Skills : 11. 12. Understand the benefits of views. Create, modify, and remove simple and complex views.

Motor Skills : 10. Ability to handle keyboard and mouse. 11. 5.6 Ability to work with editor.

Sample Examples :

Write the queries for the following and write the output in the space provided. If output is more than two rows write only first two rows. Show columns as they appear in output 5.1 SQL> Output Create a view called EMP_VU based on the employee numbers, employee names, and department numbers from the EMP. Change the heading for the ename name to Employee

5.2 SQL> Output

Display the contents of the EMP_VU view.

5.3 SQL> Output

Modifying data using view (modify the name of employee)

5.4 SQL> Output

Creating view with check constraints

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION

29

Relational Database Management System (17332)

Experiment

5.5 SQL> Output

Removing a view

6.0 6.1

Questions for confirmation of learning: What is view? How it is different from base tables? -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

6.2

List the operations that can be performed on views? What are its limitations -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

7.0 7.1

Students Activity Create simple view Student_vu using student table from experiment number 1.2 and complex views SCM_CVU based on student, marks and course table. Join the three tables to display student name, course name and marks obtained from SCM_CVU views Exercise Write the answers of the following 8.1 Create STUDENT_VU on student table SQL> Output

8.0

8.2 SQL> Output

Insert your name through STUDENT_VU views

8.3 SQL>

Modify the record of a STUDENT_VU by changing marks or name of student

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION

30

Relational Database Management System (17332)

Experiment

Output

8.4 SQL> Output

Delete the record you just added in a view STUDENT_VU

8.5 SQL> Output

Write a query to create a complex views SCM_CVU as given in 7.2 above

8.5 SQL> Output

Write a query to delete the course name as DBMS using SCM_CVU. Write output

C (4)

P (4)

A(2)

T (10)

Signature of Teacher

Table Details and data


MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION 31

Relational Database Management System (17332)

Appendix

Bonus Table ename Job Sal comm Table Grade Losal hisal Empno 7369 7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7900 7902 7934 varchar2(10) varchar2(9) Number Number Number Number Number Ename Raj Sachin Ajay Vijay Vinod John Savita Apurva Rakesh Shamim Rahul Kalim Julie Abrahham

Dept Table Deptno Salgrade Dname Loc

Emp Table Number(2) Not Null Varchar2(14) Varchar2(13) Empno Ename Job Mgr Hiredate Sal Comm. deptno Number(4) not null Varchar2(10) Varchar2(9) Number(4) Date Number(10,2) Number(8,2) Number(2)

Emp Table Content Job Mgr Hiredate Clerk 7902 17-DEC1980 Salesman 7698 20-FEB1981 Salesman 7698 22-FEB1981 Manager 7839 2-APR1981 Salesman 7698 28-SEP1981 Manager 7839 1-MAY1981 Manager 7839 9-JUN1981 Analyst 7566 9-DEC1982 President Null 17-NOV1981 Salesman 7698 08-SEP1981 Clerk 7788 12-JAN1983 Clerk 7698 3DEC1981 Analyst 7566 3-DEC1981 Clerk 7782 23-JAN1982

Sal 800 16000 12500 29750 12500 28500 24500 30000 50000 15000 11000 9500 30000 13000

Comm Null 300 500 Null 1400 Null Null Null Null 0 Null Null Null Null

Deptno 20 30 30 20 30 30 10 20 10 30 20 30 20 10

Salgrade Table Content Grade 1 2 3 4 5 Losal 700 1201 1401 2001 3001 Hisal 1200 1400 2000 3000 9999

Department Table Deptno 10 20 30 40 Dname Accounting Research Sales Operations Loc Mumbai Pune Nagpur Aurangabad

Justification Curriculum is changed Practical load changed form 2 hr /week to 4 /hr per week

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION

32

Relational Database Management System (17332)

Appendix

More practicals added in the new curriculum list on topics such as Database design concepts, ER diagrams, Normalisation, Indexes, sequence, More exercises on PL/ SQL, Triggers implicit and explicit, Exception handling, User defined procedures and functions, Database triggers, Shared and exclusive modes of locking All practicals are covered as per curriculum list. Practical numbers are kept same as per curriculum (i.e. from 1 to 15) But each practical is subdivided as per the content and coverage per practical=2 Hours. Like this there will be total 22 practicals designed + two slots as practical exercise with guidelines how to use this two slots Two slots of 2 Hours duration is kept as exercise practicals. This provision is made for o to make for holidays o any working problems/ unavoidable circumstances o students if absent due to genuine reasons o cover remaining continuous assessment o Non completion of first set of exercises o Practice session for students difficulties New questions are added for confirmation of learning of students New exercises added under students activity Care will be taken to formulate a query with specific answers which can be answered in given space only. No additional pages students will require to attach to lab manual for answering exercise. As far as possible minimum standard tables will be used will be added under heading tables/ in appendix

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION

33

You might also like