0% found this document useful (0 votes)
29 views57 pages

DDM Print Out

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views57 pages

DDM Print Out

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 57

EX.

NO :1 Database Development Life cycle


Date:

Aim:

Problem Definition

Information plays a vital role in the development and growth of every organization. Currently, the various
departments manage student information independently in their own ways. There are no common, standardized
process and program for capturing, processing and storing student‟s information. This has kept student information
disintegrated in different departments and information provided to the various departments by the students is
characterized with discrepancies. The problems facing the current manual system are data redundancy, difficult to
update and maintain, inconsistent data, insecurity, difficult to impose constraints on various data file and difficult to
backup.

Requirement analysis Scope

The process of collecting and analyzing information about the part of the organization that is to be
supported by the database system, and using this information to identify the requirements for the new
system.

Relations in Student
 a description of the data used or generated;
 the details of how data is to be used or generated;

 any additional requirements for the new database system.

The SQL CREATE TABLE Statement

The CREATE TABLE statement is used to create a new table in a database.

Syntax

CREATE TABLE table_name (

column1 datatype,

column2 datatype, column3

datatype,

....

);

The column parameters specify the names of the columns of the table.

The datatype parameter specifies the type of data the column can hold (e.g. varchar, integer, date, etc.).

Example:

CREATE TABLE Persons (

PersonID int,

LastName varchar(255),

FirstName varchar(255),

Address varchar(255), City

varchar(255)

);

ALTER TABLE - ADD Column

To add a column in a table, use the following syntax: ALTER

TABLE table_name

ADD column_name datatype;

The following SQL adds an "Email" column to the "Customers" table:

Example
ALTER TABLE Customers ADD
Email varchar(255);

ALTER TABLE - ALTER/MODIFY COLUMN

To change the data type of a column in a table, use the following syntax:

ALTER TABLE table_name

ALTER COLUMN column_name datatype;

ALTER TABLE table_name

MODIFY COLUMN column_name datatype;

SQL ALTER TABLE Example

Look at the "Persons" table:

ID LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

ALTER TABLE Persons ADD

DateOfBirth date;

ID LastName FirstName Address City DateOfBirth

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger


Result:
EX.NO: 2 Database design using Conceptual modeling (ER-EER)

Date:

Aim:

Introduction:

The ER model defines the conceptual view of a database. It works around real-world entities and the
associations among them. At view level, the ER model is considered a good option for designing
databases.

Notations in ER Model
Example:

Normalization:

● Normalization is the process of organizing the data in the database.


● Normalization is used to minimize the redundancy from a relation or set of
relations. It is also used to eliminate the undesirable characteristics like
Insertion, Update and Deletion Anomalies.
● Normalization divides the larger table into the smaller table and links them
using relationship.
● The normal form is used to reduce redundancy from the database table.
Types of Normal Forms:
There are the four types of normal forms:

First Normal Form (1NF)

● A relation will be 1NF if it contains an atomic value.


● It states that an attribute of a table cannot hold multiple values. It must hold only single-
valued attribute.
● First normal form disallows the multi-valued attribute, composite attribute, and their
combinations.

Exmaples:

Relation EMPLOYEE is not in 1NF because of multi-valued attribute EMP_PHONE.

EMP_ID EMP_NAME EMP_PHONE EMP_STATE

14 John 7272826385, UP
9064738238

20 Harry 8574783832 Bihar

12 Sam 7390372389, Punjab


8589830302
EMPLOYEE table :
The decomposition of the EMPLOYEE table into 1NF has been shown below:

EMP_ID EMP_NAME EMP_PHONE EMP_STATE

14 John 7272826385 UP

14 John 9064738238 UP

20 Harry 8574783832 Bihar

12 Sam 7390372389 Punjab

12 Sam 8589830302 Punjab

Second Normal Form (2NF)


● In the 2NF, relational must be in 1NF.
● In the second normal form, all non-key attributes are fully functional dependent on the
primary key

1. EMP_ID EMP_NAME
2. EMP_ID EMP_PHONE
3. EMP_ID EMP_STATE

Third Normal Form (3NF)


● A relation will be in 3NF if it is in 2NF and not contain any transitive partial dependency.
● 3NF is used to reduce the data duplication. It is also used to achieve the data integrity.
● If there is no transitive dependency for non-prime attributes, then the relation must be in
third normal form.

A relation is in third normal form if it holds atleast one of the following conditions for every
non-trivial function dependency X → Y.

1. X is a super key.
2. Y is a prime attribute, i.e., each element of Y is part of some candidate key.

Example:
EMPLOYEE_DETAIL table:

EMP_ID EMP_NAME EMP_ZIP EMP_STATE EMP_CITY


222 Harry 201010 UP Noida

333 Stephan 02228 US Boston

444 Lan 60007 US Chicago

555 Katharine 06389 UK Norwich

666 John 462007 MP Bhopal

Super key in the table above:

1. {EMP_ID}, {EMP_ID, EMP_NAME}, {EMP_ID, EMP_NAME, EMP_ZIP}

Candidate key: {EMP_ID}


Non-prime attributes: In the given table, all attributes except EMP_ID are non- prime.
Here, EMP_STATE & EMP_CITY dependent on EMP_ZIP and EMP_ZIP dependent on
EMP_ID. The non-prime attributes (EMP_STATE, EMP_CITY) transitively dependent
on super key(EMP_ID). It violates the rule of third normal form.
That's why we need to move the EMP_CITY and EMP_STATE to the new
<EMPLOYEE_ZIP> table, with EMP_ZIP as a Primary key.

EMPLOYEE table: EMPLOYEE_ZIP table:

EMP_ZIP EMP_STATE EMP_CITY

201010 UP Noida

02228 US Boston

60007 US Chicago

06389 UK Norwich

462007 MP Bhopal

EMP_ID EMP_NAME EMP_ZIP

222 Harry 201010

333 Stephan 02228


444 Lan 60007

555 Katharine 06389

666 John 462007

Boyce Codd normal form (BCNF)


● BCNF is the advance version of 3NF. It is stricter than 3NF.
● A table is in BCNF if every functional dependency X → Y, X is the super key of the
table.
● For BCNF, the table should be in 3NF, and for every FD, LHS is super key.

Example: Let's assume there is a company where employees work in more than one department.
EMPLOYEE table:

EMP_ID EMP_COUNTRY EMP_DEPT DEPT_TYPE EMP_DEPT_NO

264 India Designing D394 283

264 India Testing D394 300

364 UK Stores D283 232

364 UK Developing D283 549

In the above table Functional dependencies are as follows:

1. EMP_ID → EMP_COUNTRY
2. EMP_DEPT → {DEPT_TYPE, EMP_DEPT_NO}

Candidate key: {EMP-ID, EMP-DEPT}


The table is not in BCNF because neither EMP_DEPT nor EMP_ID alone are keys. To
convert the given table into BCNF, we decompose it into three tables:

EMP_COUNTRY table:

EMP_ID EMP_COUNTRY

264 India
EMP_DEPT table:

EMP_DEPT DEPT_TYPE EMP_DEPT_NO

Designing D394 283

Testing D394 300

Stores D283 232

Developing D283 549

EMP_DEPT_MAPPING table:

EMP_ID EMP_DEPT

D394 283

D394 300

D283 232

D283 549

Functional dependencies:

1. EMP_ID → EMP_COUNTRY
2. EMP_DEPT → {DEPT_TYPE, EMP_DEPT_NO}

Candidate keys:
For the first table: EMP_ID
For the second table: EMP_DEPT
For the third table: {EMP_ID, EMP_DEPT}
Now, this is in BCNF because left side part of both the functional dependencies is a key.

Result:
EX.NO:03 Implement the database using SQL Data definition with
constraints, Views
Date:

Aim:

Procedure:

1.SQL Data definition Language(DDL) :


statements
1. CREATE – is used to create the database or its objects.
2. DROP – is used to delete objects from the database.
3. ALTER – is used to alter the structure of the database.
4. TRUNCATE – is used to remove all records from a table, including all spaces allocated for
the records are removed.
5. COMMENT – is used to add comments to the data dictionary.
6. RENAME – is used to rename an object existing in the database.

DDL COMMANDS
SQL> create table stud (sname varchar2(30), sid varchar2(10), sage number(2), sarea
varchar2(20));
Table created. SQL>
desc stud; Name
Null? Type

SNAME VARCHAR2(30) SID


VARCHAR2(10) SAGE
NUMBER(2) SAREA
VARCHAR2(20)
SQL>alter table stud modify ( sage number(10));
Table altered.
SQL> alter table stud add ( sdept varchar2(20));
Table altered.
SQL> desc stud;
Name Null? Type

SNAME VARCHAR2(30) SID


VARCHAR2(10) SAGE
NUMBER(10) SAREA
VARCHAR2(20) SDEPT
VARCHAR2(20)
SQL> alter table stud drop (sdept varchar2(20));
Table altered.
SQL> desc studs;
Name Null? Type
SNAME VARCHAR2(30) SID
VARCHAR2(10) SAGE
NUMBER(10) SAREA
VARCHAR2(20)
SQL> truncate table studs; Table
truncated.
SQL> desc studs;
Name Null? Type

SNAME VARCHAR2(30) SID


VARCHAR2(10) SAGE
NUMBER(10) SAREA
VARCHAR2(20) SDEPT
VARCHAR2(20)
SQL> drop table studs;
Table dropped.
SQL> rename table studs to old; Table
renamed.
SQL> desc studs;
Table studs doesn't exist.

2.Constraints

Integrity constraints: Integrity constraints guard against the accidental damage to the database.
● Null
● NOT Null
● Primary key
● Unique key
● Foreign key
● Check constraints
● Default constraints

DESCRIPTION:

a) NULL: Null value is a member of all domains and as a result is a legal value for every
attributes.

Syntax:create table tablename(att1 type1,att2 type2 null);

Column of any data type may contain null value unless the column was defined as not null when
the table was created.

b) NOT NULL : Not null specification prohibits the insertion of null value for this attributes.

Syntax: create table tablename(att1 type1,att2 type2 not null);


At the time of column creation not null value can be assigned to it.

CREATE TABLE Persons ( ID int NOT NULL, LastName


varchar(255) NOT NULL, FirstName varchar(255) NOT NULL, Age int );

c) PRIMARY KEY:
A primary key is a one or more columns in a table used to uniquely identify each row in
a table. It uniquely identifies the attribute value.

Syntax:create table tablename(attribute1 value1,attribute2 value2,primary key(attribute));

CREATE TABLE Persons ( ID int NOT NULL PRIMARY KEY, LastName


varchar(255) NOT NULL, FirstName varchar(255), Age int);

d) UNIQUE KEY: unique key is used to ensure that the information in the column for each
record is unique.

Syntax: create table tablename(attribute1 value1,attribute2 value2,unique(attribute));


The unique key specifications says that attributes form a candidate key.

CREATE TABLE Persons ( ID int NOT NULL UNIQUE, LastName


varchar(255) NOT NULL, FirstName varchar(255), Age int );

e) FOREIGN KEY Foreign key represents relationship between tables.


Syntax: create table tablename1(att1 value1,att2 value2,primary key(attribute)); create
table tablename2(att1 value1,att2 value2,foreign key(attribute references
tablename1);

CREATE TABLE Orders ( OrderID int NOT NULL PRIMARY KEY, OrderNumber int
NOT NULL, PersonID int FOREIGN KEY REFERENCES Persons(PersonID));

f) CHECK CONSTRAINTS :Check clause is to ensure the attribute value satisfy specified
condition.

Syntax: create table tablename(att1 value1,att2 value2,att3 value3,primary key(att), check(name


in(att,att)));

CREATE TABLE Persons ( ID int NOT NULL, LastName


varchar(255) NOT NULL, FirstName varchar(255), Age int CHECK (Age>=18));

g) DEFAULT CONSTRAINT: At the time of column creation a default value can be


assigned to it.

Syntax:create table tablename(att value default value);


Example
Staff (staffNo, fName, IName, position, sex, DOB, salary, branchNo)
Branch (branchNo, street, city, postcode)
CREATE TABLE Persons ( ID int NOT NULL, LastName varchar(255) NOT NULL,
FirstName varchar(255), Age int, City varchar(255) DEFAULT 'Sandnes');

3. VIEWS

Definition

▪ A view is a SQL query that is permanently stored in the database and assigned a name.
▪ A view is a virtual table in the database whose contents are defined by a query.
▪ A view does not exist in the database as a stored set of data values.
▪ A view can be used to restrict a user‟s access to only selected rows of a table called as
Horizontal Views.
▪ A view can be used to restrict a user‟s access to only certain columns of a table called as
Vertical Views

To create a VIEW
Syntax
CREATE VIEW view_name AS SELECT column1, column2, ...FROM table_name
WHERE condition;

CREATE VIEW [Brazil Customers] AS SELECT CustomerName, ContactName


FROM Customers WHERE Country = 'Brazil';

To modify the existing VIEW Syntax

CREATE OR REPLACE VIEW view_name AS SELECT column1, column2, ... FROM


table_name WHERE condition;

CREATE OR REPLACE VIEW [Brazil Customers] AS SELECT CustomerName,


ContactName, City FROM Customers WHERE Country = 'Brazil';

Dropping a VIEW

Syntax

DROP VIEW view_name;

DROP VIEW [Brazil Customers];

Result:
EX.No:4
Query the Database using SQL Manipulation
Date:

AIM :

PROCEDURE:

Creating a Table:
▪ CREATE command is used to create a new table in the database.
▪ CREATE command has two formats
● Create an empty table.
SYNTAX:CREATE TABLE table-name (field_name datatype);
CREATE TABLE Persons ( PersonID int, LastName varchar(255),
FirstName varchar(255), Address varchar(255), City varchar(255));

Modifying a Table:
▪ ALTER command is used to modify the structure of a table in the database.
▪ ALTER command can be used in Two modes.
● ADD: To add one or more columns.
● MODIFY: To modify one or more fields defined in the table
SYNTAX:ALTER TABLE table-name ADD/MODIFY (field_name datatype);
ALTER TABLE Persons ADD Email varchar(255);

Deleting a Table:
DROP command is used to remove the structure and data of a table from the database.
SYNTAX:DROP TABLE table-name;
DELETE FROM Customers WHERE CustomerName='Alfreds Futterkiste';

INSERT command:
To insert new values into a table in the database.
● INSERT INTO table-name VALUES (value1, value2…);
● INSERT INTO table-name (column1, column2...) VALUES (value1, value2...);
UPDATE command
To modify or update an existing row or rows of a table in the database.
SYNTAX:UPDATE table-name SET column=value WHERE condition;

DELETE command:
To delete an already existing row or rows from a table.
SYNTAX:DELETE FROM table-name WHERE condition;

Truncating a Table:
TRUNCATE command will delete the data from the table but the table structure will
remain intact.
SYNTAX: TRUNCATE TABLE table-name;
TRUNCATE TABLE Categories;

INSERT command:
To insert new values into a table in the database.
❖ INSERT INTO table-name VALUES (value1, value2…);
❖ INSERT INTO table-name (column1, column2...) VALUES (value1, value2...);

INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode, Country)


VALUES ('Cardinal', 'Tom B. Erichsen', 'Skagen 21', 'Stavanger', '4006', 'Norway');

UPDATE command
To modify or update an existing row or rows of a table in the database.
SYNTAX:UPDATE table-name SET column=value WHERE condition;\
UPDATE Customers SET ContactName = 'Alfred Schmidt', City= 'Frankfurt' WHERE
CustomerID = 1;

DELETE command:
To delete an already existing row or rows from a table.
SYNTAX:DELETE FROM table-name WHERE condition;
DELETE FROM Customers WHERE CustomerName='Alfreds Futterkiste';
SQL INBUILT FUNCTION & SQL CLAUSES
⮚ Date Function
⮚ Numeric Function
⮚ Character Function
⮚ Conversion Function
⮚ Miscellaneous Function

Date Function

They operate on date values and produce outputs, which also belong to date data type except for
months, between, date function returns a number.

1. Add_month:This function returns a date after adding a specified date with specified number of
months.

Syntax: Add_months(d,n); where d-date n-number of months Select

add_months(sysdate,2) from dual;

2. last_day: It displays the last date of that month.

Syntax: last_day (d); where d-date

Example: select last_day ('1-jan-2011')from dual;

3. Months_between: It gives the difference in number of months between d1 & d2.

Syntax: month_between (d1,d2); where d1 & d2 –dates

Example: select months_between('18-aug-2010','18-apr-2010')from dual;

4. next_day:It returns a day followed the specified date.

Syntax: next_day (d,day);

Example: select next_day(sysdate,'monday')from dual;

NUMERIC FUNCTIONS
1. abs
Example: select abs(-25)from dual;
2. ceil
Example: select ceil(59.67) from dual; 3.exp
Example: select exp(6) from dual;
4. floor
Example: select floor(99.3)from dual;
5. power
Example :select power(15,2) from dual;
6. mod
Example: select mod(100,3) from dual;
7. round
Example: select round(100.3236,2) from dual;
8. truncate
Example: select trunc(100.256,2)from dual; 9.sqrt
Example: select sqrt(225)from dual;

CHARACTER FUNCTIONS
1. initcap(char)
Example: select initcap(„nandhini‟)from dual;
2. lower(char)
Example:select lower('NANDHINI')from dual;
3. uppe(char)
Example:select upper('nandhini')from dual;
4. ltrim(char,[set])
Example:select ltrim('cseit','cse')from dual;
5. rtrim(char,[set])
Example:select rtrim('cseit','it')from dual;
6. replace(char,search string,replace string);
Example:select replace('jack and jue','j','bl')from dual;
7. substr(char,m,n)
Example:select substr('information',3,4)from dual;

CONVERSION FUNCTION

1. to_char():This function converts date to a value of varchar type in a form specified by date
format. If format is negelected then it converts date to varchar2 in the default date format.

Syntax: to_char(d,[format]);

Example: select to_char(sysdate,'dd-mm-yy')from dual;

2. to_date():This function converts character to date data format specified in the form character.

Syntax: to_date(d,[format]);

Example: select to_date('aug 15 2010','mm-dd-yy')from dual;

Miscellaneous Functions

1. uid – This function returns the integer value (id) corresponding to the user currently logged in.

Example: select uid from dual;

2. user – This function returns the logins user name.

Example: select user from dual;

3. vsize: It returns the number of bytes in expression.


Example: select vsize(„tech‟) from dual;

GROUP FUNCTIONS

A group function returns a result based on group of rows.

1. avg
Example: select avg(total)from nandhinir;

2. max
Example: select max(percentage)from nandhinir;

3. min
Example: select min(marks)from nandhinir;

4.sum
Example: select sum(price)from nandhinir;

COUNT FUNCTION

In order to count the number of rows, count function is used


.
1. count(*) – It counts all, inclusive of duplicates and nulls.
Example: select count(*)from nandhinir;

2.count(col_name)– It avoids null value.


Example: select count(total)from nandhinir;

3.count(distinct col_name) – It avoids the repeated and null values.


Example: select count(distinct mat)from nandhinir;

SQL CLAUSES:

SQL SELECT STATEMENT:.


A query may retrieve information from specified columns or from all of the The SQL SELECT
statement is used to query or retrieve data from a table in the database columns in the table. To
create a simple SQL SELECT Statement, you must specify the column(s) name and the table
name.

SELECT column_list FROM table-name [WHERE


Clause]
[GROUP BY clause]
[HAVING clause] [ORDER
BY clause];
TABLE CREATION
STUDENT DETAILS
create table student(id number(10),firstname varchar(20),lastname varchar(20),age
number(5),subject varchar(10),games varchar(10));
desc student;
Name Null? Type
ID NUMBER(10)
FIRSTNAME VARCHAR2(20)
LASTNAME VARCHAR2(20)
AGE NUMBER(5)
SUBJECT VARCHAR2(10)
GAMES VARCHAR2(10)

select firstname from student;


select firstname,lastname from student; select
age from student where age>12;
SQL WHERE CLAUSE:
The WHERE Clause is used when you want to retrieve specific information from a table
excluding other irrelevant data. The WHERE clause is used to extract only those records that
fulfill a specified criterion.
SYNTAX:
SELECT "column_name" FROM "table_name" WHERE "condition".

"OR " LOGICAL OPERATOR:


If you want to select rows that satisfy at least one of the given conditions, you can use the
logical operator, OR.
QUERY: select firstname , lastname, subject from student where subject='maths' or subject='economics';

AND" LOGICAL OPERATOR


If you want to select rows that must satisfy all the given conditions, you can use the
logical operator, AND.
For Example: To find the names of the students between the age 10 to 15 years, the query
would be like:
QUERY:select firstname,lastname,age from student WHERE age >= 10 AND age <= 15
"NOT" LOGICAL OPERATOR:

If you want to find rows that do not satisfy a condition, you can use the logical operator, NOT.
NOT results in the reverse of a condition. That is, if a condition is satisfied, then the row is not
returned.
For example: If you want to find out the names of the students who do not play football, the
query would be like:

QUERY:select firstname,lastname,age,games from student WHERE NOT games='cricket';

SQL ORDER BY: The ORDER BY clause is used in a SELECT statement to sort results either
in ascending or descending order. Oracle sorts query results in ascending order by default.If you
want to sort the re cords in a descending order, you can use the DESC keyword

Syntax
SELECT column_name(s) FROM table_name ORDER BY column_name(s) ASC|DESC

1. QUERY:select name, salary from employe order by name, salary;


2. QUERY:SELECT name, salary FROM employe ORDER BY salary;
3. QUERY:SELECT name, salary FROM employe ORDER BY name, salary;
4. QUERY:SELECT name, salary FROM employe ORDER BY name, salary DESC;
5. QUERY:SELECT name, salary FROM employe
ORDER BY name DESC, salary DESC; 6.QUERY:SELECT
name, salary, salary*1.2 AS newsalary
FROM employe
WHERE salary*1.2>30000
ORDER BY newsalary DESC;
SQL GROUP FUNCTIONS:
Group functions are built-in SQL functions that operate on groups of rows and return one value
for the entire group. These functions are: COUNT, MAX, MIN, AVG, SUM, DISTINCT.

1. QUERY :SELECT MAX (salary) FROM employe;


2. QUERY :select min(salary)from employe;
3. QUERY :select avg(salary)from employe;
4. QUERY: select sum(salary)from employe;
5. QUERY:SELECT DISTINCT dept FROM employe;
6. QUERY :SELECT COUNT (DISTINCT name) FROM employe;

SQL GROUP BY CLAUSE:


The SQL GROUP BY Clause is used along with the group functions to retrieve data grouped
according to one or more columns.
For Example:If you want to know the total amount of salary spent on each department, the query
would be:
1. QUERY :SELECT dept, SUM (salary) FROM employe GROUP BY dept;

2. QUERY: select location,dept,sum(salary)from employe GROUP BY location;

SQL HAVING CLAUSE:

● Having clause is used to filter data based on the group functions.This is similar to
WHERE condition but is used with group functions.
● Group functions cannot be used in WHERE Clause but can be used in HAVING clause
● The HAVING clause was added to SQL because the WHERE keyword could not be used
with aggregate functions.

SYNTAX:
SELECT column_name, aggregate_function(column_name) FROM table_name GROUP
BY column_nameHAVING aggregate_function(column_name) operator value

QUERY :SELECT dept, SUM (salary) FROM


employe
GROUP BY dept
HAVING SUM (salary)>25000;

SQL ALIAS

● With SQL, an alias name can be given to a table or to a column.


● You can give a table or a column another name by using an alias. This can be a good
thing to do if you have very long or complex table names or column names.
● SQL Aliases are defined for columns and tables. Basically aliases is created to make
the column selected more readable.

SQL Alias Syntax for Tables: SELECT column_name(s)FROM table_name AS


alias_name

SQL Alias Syntax for Column:SELECT column_name AS alias_name


FROM table_name

1. QUERY :select s.firstname from nandhin s;


2. QUERY :select p.id,s.lastname,s.firstname from nandhin s,employe p where
s.lastname='fleming' and s.firstname='rahul';
3. QUERY :SELECT firstname AS Name FROM student;
4. QUERY :SELECT s.firstname AS Name FROM student s;
5. QUERY :SELECT s.lastname AS Name FROM student s;
SQL LIKE OPERATOR:

● The LIKE operator is used to list all rows in a table whose column values match a
specified pattern.
● It is useful when you want to search rows to match a specific pattern, or when you do not
know the entire value. For this purpose we use a wildcard character '%'.

1. QUERY :SELECT firstname,lastname


FROM student WHERE firstname LIKE 's%';

2. QUERY :select
firstname,lastname from student where firstname like'_a%';
SQL BETWEEN ... AND Operator

The operator BETWEEN and AND, are used to compare data for a range of values.

QUERY :select firstname,lastname, age from student where age between 10 and 15;
SQL IN Operator:
The IN operator is used when you want to compare a column with more than
one value. It is similar to an OR condition.

QUERY :select firstname, lastname, subject from student where subject in('maths','science');

SQL IS NULL Operator


A column value is NULL if it does not exist. The IS NULL operator is used to
display all the rows for columns that do not have a value.
For Example: If you want to find the names of students who do not participate in any games, the
query would be as given below

QUERY :SELECT firstname, lastname FROM student WHERE games IS NULL ;

The SQL SELECT DISTINCT Statement


In a table, some of the columns may contain duplicate values. This is not a
problem, however, sometimes you will want to list only the different (distinct) values in a table.
The DISTINCT keyword can be used to return only distinct (different) values.

QUERY :select distinct location from employe;

NESTED SUBQUERIES:

A Subquery is a select from where expression that is nested with another


query.Mostlysubqueries are used to perform tests for set membership to make set
comparisons and determine set cardinality.

IN:
Set of collection of values produced by a select clause.
Syntax: SELECT column_name(s)
FROM table_name WHERE column_name IN (value1, value2, ...);
SELECT * FROM Customers WHERE Country IN ('Germany', 'France', 'UK');

NOT IN:
The not in connective tests for the absence of set membership.

Syntax:select att1,att2 from table1 where att1 not in(select att1 from table2);

SELECT * FROM Customers WHERE Country NOT IN ('Germany', 'France', 'UK');

EXIST:
The expression evaluates to true only if the sub example represented is not empty.

Syntax: SELECT column_name(s) FROM table_name WHERE EXISTS


(SELECT column_name FROM table_name WHERE condition);

SELECT SupplierName FROM Suppliers


WHERE EXISTS (SELECT ProductName FROM Products WHERE Products.SupplierID =
Suppliers.supplierID AND Price < 20);

NOT EXISTS:
The expression evaluates to true only if thesubexample represented evaluates to

Syntax:select att1 from table1 where not exists (select * from table2 where
table2.att2=table1.att2);

SELECT SupplierName FROM Suppliers


WHERE NOT EXISTS (SELECT ProductName FROM Products WHERE Products.SupplierID
= Suppliers.supplierID AND Price < 20);

SOME:
The some allows as to rewrite the queries in a form that resembles closely our
formulation of the example in English.

Syntax: select att1 from table1 where exist att2>some(select att2 from table1 where att1=value);
The > some comparison in the where clause of the outer select is true if the assets
value of the tuple is greater than one member of set of all asset values for branch.

ALL:
The construct >all corresponds to the phrase “greater than all”.
Syntax: select att1 from table1 group by att1 having sum(att2) >= all(select sum(att2) from
table2 group by att1.

DELETE:
A delete request is expressed in same way as a query. The delete operation is used to
delete all or specific rows from database. We cannot delete values of particular attribute.
Syntax: delete from relation where Condition;

Table Creation:

Table1:
create table book(bookid number(10),title varchar(20),pubyear number(10),unitprice
number(20),authornamevarchar(20),publishernamevarchar(20));

Table2:create table author(authornamevarchar(20),country varchar(20));

Table3:
create table order(orderno number(10),bookid number(10),orderdatedate,quantity
number(10),price number(10));

1. Display the
name of all books for which order is placed.
QUERY:select title from book wherebookid in(select bookid from order5);

author,publisher name of all book published in 2004,2003…


2. Display the title,
QUERY:selecttitle,authorname,publishername from book wherepubyear
in(2004,2003);

3. Display the title,author,pubname


of all book published in 2000,2002,2004
QUERY:selecttitle,authorname,publishername from book wherepubyear in(2000,2002,2004);

4. Display authorname,country who


published in yr 2004
QUERY:select *from author where authorname in
(select authorname from book where pubyear=‟2004‟);

5. Display the titles of book


for which the order is not placed
QUERY:select title from book Where bookid not in(select bookid from order);

for book written by author not in India…


6. Get the titles
QUERY:select title from book where authorname not in
(select authorname from author where country='india');
7. Display the
names of all books for which order is placed
QUERY:select title from book where exists (select *from order where
order.bookid=book.bookid);

8. Display the titles


of book for which order is placed
QUERY:select title from book where not exists
(select *from order where order.bookid=book.bookid);

9. Display the title of book that have price greater than atleast one book published in the year
2004.
QUERY:select title from book where price>some(select price from book where pub_yr=‟2004‟);

10. Display the title of book that have price greater than all the books published in the year
2004.
QUERY:select title from book where price>all
(select price from book where pubyear=‟2004‟);

11. Display the


name of the author who have received highest royalty amount
QUERY: select authorname from book groupby authorname having sum price>=all
(select sum(price)from book groupby authorname);

12. Delete all books from book relation


where pubyear is less then 2002
QUERY:delete from book where pubyear<2002;

13. Delete all books from book relation where pubyear


between 2000 and 2003
QUERY:delete from book49 where pubyear between 2000 and 2003;

Result:
EX.No: 5 Querying/Managing the database using SQL Programming
Date:

Aim:

PROCEDURE:
PL/SQL stands for Procedural Language extension of SQL.

PL/SQL is a combination of SQL along with the procedural features of programming languages.
It was developed by Oracle Corporation in the early 90‟s to enhance the capabilities of SQL.

A Simple PL/SQL Block:

Each PL/SQL program consists of SQL and PL/SQL statements which from a PL/SQL block. A

PL/SQL Block consists of three sections:

● The Declaration section (optional).


● The Execution section (mandatory).
● The Exception (or Error) Handling section (optional).

Declaration Section:
The Declaration section of a PL/SQL Block starts with the reserved keyword DECLARE.

Execution Section:
The Execution section of a PL/SQL Block starts with the reserved keyword BEGIN and ends
with END.

Exception Section:
The Exception section of a PL/SQL Block starts with the reserved keyword EXCEPTION. Every

statement in the above three sections must end with a semicolon ; .

PL/SQL blocks can be nested within other PL/SQL blocks.


Comments can be used to document code.

This is how a sample PL/SQL Block looks.

DECLARE
Variabledeclaration
BEGIN
ProgramExecution
EXCEPTION
Exceptionhandling
END;

In addition to SQL commands,PL/SQL can also process data usin flow of statements.the flow
of control statements are classified into the following categories.

a) Basic PL/SQL Programming

i) Conditional control -Branching


ii)Iterative control - looping
iii)Sequential control

BRANCHING in PL/SQL:

Sequence of statements can be executed on satisfying certain condition


. If statements are being used and different forms of if are:

1. Simple IF
2. ELSIF
3. ELSE IF

SIMPLE IF:
Syntax:
IF condition THEN
statement1;
statement2;
END IF;

IF-THEN-ELSE STATEMENT:
Syntax:
IF condition THEN
statement1;
ELSE
statement2;
END IF;

ELSIF STATEMENTS:
Syntax:
IF condition1 THEN
statement1; ELSIF
condition2 THEN
statement2; ELSIF
condition3 THEN
statement3;
ELSE
statementn;
END IF;

NESTED IF :
Syntax:
IF condition THEN statement1;
ELSE
IF condition THEN statement2;
ELSE
statement3;
END IF; END
IF; ELSE
statement3;
END IF;

SELECTION IN PL/SQL(Sequential Controls)


SEARCHED CASE:
CASE
WHEN searchcondition1 THEN statement1;
WHEN searchcondition2 THEN statement2;
:
: ELSE
statementn;
END CASE;

ITERATIONS IN PL/SQL
Sequence of statements can be executed any number of times using loop construct.
It is broadly classified into:
Simple Loop
For Loop
While Loop

SIMPLE LOOP

Syntax:
LOOP
stateme
nt1;
EXIT [ WHEN
Condition]; END
LOOP;

WHILE LOOP
Syntax
WHILE condition
LOOP statement1;
statement2;
END LOOP;

FOR LOOP
Syntax:
FOR counter IN [REVERSE] LowerBound..UpperBound
LOOP
statement1;
statement2; END
LOOP;

Exercise:1
write a pl/sql program to swap two numbers with out taking third variable
PROGRAM
set serveroutput on declare
a number(10);
b number(10); begin
a:=&a;
b:=&b;
dbms_output.put_line('THE PREV VALUES OF A AND B WERE'); dbms_output.put_line(a);
dbms_output.put_line(b);
a:=a+b;
b:=a-b;
a:=a-b;
dbms_output.put_line('THE VALUES OF A AND B ARE'); dbms_output.put_line(a);
dbms_output.put_line(b);
end
OUTPUT
Enter value for a:
10
Enter value for b:
20
old 5: a:=&a;
new 5: a:=10;
old 6: b:=&b;
new 6: b:=20;
THE PREV VALUES OF A AND B WERE 10
20
THE VALUES OF A AND B ARE 20
10
PL/SQL procedure successfully completed.

2. .Write a pl/sql program to find the largest of two numbers


PROGRAM
set serveroutput on declare
a number;
b number;
begin a:=&a;
b:=&b; if
a=b then
dbms_output.put_line('BOTH ARE EQUAL'); elsif
a>b then
dbms_output.put_line('A IS GREATER'); else
dbms_output.put_line('B IS GREATER'); end
if;
end;

3. Write a pl/sql code block to calculate the area of a circle for a value of radius varying
from 3 to 6Store the radius and the corresponding values of calculated area in an empty
table named areas ,consisting of two columns radius & area
TABLE NAME:AREAS
create table areas50(radius number(10),area number(6,2));

set serveroutput on declare


pi constant number(4,2):=3.14; radius
number(5):=3;
area number(6,2);
begin
while radius<7 loop
area:=pi*power(radius,2);
insert into areas50 values(radius,area); radius:=radius+1;
end loop; end;

4. write a pl/sql code block that will accept an account number from the user,check if
the users balance is less than minimum balance,only then deduct rs.100/- from the
balance.this process isfired on the acct table.

create table acct50(name varchar2(10),cur_bal number(10),acctno number(6,2));

PROGRAM
set serveroutput on declare
mano number(5); mcb
number(6,2);
minibal constant number(7,2):=1000.00; fine
number(6,2):=100.00;
begin mano:=&mano;
select cur_bal into mcb from acct50 where acctno=mano; if
mcb<minibal then
update acct50 set cur_bal=cur_bal-fine where acctno=mano; end
if;
end;

b) PL/SQL FUNCTIONS

Function:
- Returns a value
- FUNCTION name RETURN data-type IS

Syntax for function:


Create [or Replace] function function_name
(parameter1 [model1] datatype1,
(parameter2 [model2] datatype2,
…) return type IS|AS
PL/SQL Block;

A procedure can have three types of parameters.


1) IN Parameter
2) OUT Parameter
3) IN OUT Parameter

In Parameters are used to accept values from the user.

Exercise 1:

Create a procedure to display a message

Create or replace procedure n1 is


begin
dbms_output.put_line('Hello World');
end;

Exec n1

Exercise 2:

Create a procedure which accepts two numbers and display its sum.

create or replace procedure add_num ( a IN number, b


IN number)
is
c number(3); begin
c := a+b;
dbms_output.put_line(' The sum is '||c); end;
/

exec add_num(5,10);
Exercise 3:

Create a Procedure which accepts an empno and increments his salary by 1000.
create or replace procedure inc( a in number) is
begin
update emp50 set salary = salary+1000 where
eno = a;
end;

exec inc(45);

4. To find the grade of the student.

Function creation

create or replace function datas51(a number) return


number is
begin
if a between 91 and 100 then
dbms_output.put_line('grade is s'); elsif
a between 81 and 90 then
dbms_output.put_line('grade is a'); elsif
a between 71 and 80 then
dbms_output.put_line('grade is b'); elsif
a between 61 and 70 then
dbms_output.put_line('grade is c'); elsif
a between 51 and 60 then
dbms_output.put_line('grade is d'); else
dbms_output.put_line('grade is u'); end
if;
end;

Function created

set serveroutput on declare


a number(3);
begin a:=&a;
select average into a from stud51 where regno=a;
a:=datas51(a);
end;
OUTPUT:

old 4: a:=&a;
new 4: a:=21; grade
is d

c) TRIGGER

PROCEDURE:

A trigger is a PL/SQL block or a PL/SQL procedure that executes implicitly whenever a


particular event takes place. It can either be:
1. Application trigger: Fires whenever an event occurs with a particular application.
2. Database Trigger: Fires whenever a data event (such as DML) occurs on a schema or
database.

GUIDELINES TO DESIGNING TRIGGERS:

⮚ Use the following guidelines when designing triggers.


⮚ Use triggers to guarantee that when a specific operation is performed, related actions
are performed.

⮚ Only use database triggers for centralized, global operations that should be fired for the
triggering statement, regardless of which user or application issues the statement.

⮚ Do not define triggers to duplicate or replace the functionality already built into the
oracle database. For example do not define trigger to implement integrity rules that can be done
by using declarative constraints.
⮚ The excessive use to triggers can result in complex interdependencies, which may be
difficult to maintain in large applications. Only use triggers when necessary, and beware of
recursive and cascading effects.

Elements in a Trigger:

o Trigger timing
o For table: BEFORE, AFTER
o For view: INSTEAD OF
o Trigger event: INSERT, UPDATE, OR DELETE
o Table name: On table, view
o Trigger Type: Row or statement
o When clause: Restricting condition
o Trigger body: PL/SQL block
“Before triggers” execute the trigger body before the triggering DML event on a table. These
are frequently used to determine whether that triggering statement should be allowed to
complete. This situation enables you to eliminate unnecessary processing of the triggering
statement and it eventual rollback in cases where an exception is raised in the triggering action.

“After triggers” are used when the triggering statement is to be completed before the triggering
action and to perform a different action on the same triggering statement if a BEFORE trigger is
already present.

“Instead of Triggers” are used to provide a transparent way of modifying views that cannot be
modified directly through SQL DML statements because the view is not inherently modifiable.
You can write INSERT, UPDATE, and DELETE statements against the view. The INSTEAD
OF trigger works invisibly in the background performing the action coded in the trigger body
directly on the underlying tables.

Triggering user events:

⮚ UPDATE
⮚ INSERT
⮚ DELETE

Trigger Components:

o Statement: The trigger body executes once for the triggering event. This is the default. A
statement trigger fires once, even if no rows are affected at all.

o Row: The trigger body executes once for each row affected by the triggering event. A
row trigger is not executed if the triggering event affects no rows.
Trigger Body: The trigger body is a PL/SQL block or a call to a procedure. Syntax:
CREATE [OR REPLACE] TRIGGER trigger_name
Timing Event1 [OR event2 OR event3] ON table_name Trigger_body

Exercise1:

CREATE TRIGGER FOR INSERTING RECORDS

create table snt52(stuname char(10),rollno number(5)); Table


created

PROGRAM:
set serveroutput on
create or replace trigger tri52 after insert on snt52 for each row
begin
dbms_output.put_line('record inserted'); end;
Trigger created.

insert into snt52 values('sidhanth',25);


OUTPUT:
record inserted 1
row created..
select * from snt52;
EXERCISE2:

CREATE TRIGGER FOR INSERT,UPDATE AND DELETE

Create table dept52(loc varchar2(10),deptno number(10));


Table created

PROGRAM
set serveroutput on
create or replace trigger trg50
after insert or update or delete on dept52 begin
dbms_output.put_line('Thank You');
end;

Trigger created

Query:Update52 dept set loc='DELHI' where deptno =10;

OUTPUT:
Thank you
1 row updated
Query:delete from dept52 where deptno=15;

EXERCISE 3:

CREATE TRIGGER FOR DELETE RECORDS

create table emp52(empno number(5),ename char(10),job char(10),salary number(10),deptno number(10));

set serveroutput on
create or replace trigger del52_tri
before delete on emp52
for each row
begin
insert into emp49 values(:old.empno,:old.ename,:old.job,:old.salary,:old.deptno);
end;

Trigger created
Query:delete from emp52 where empno=1; 3
rows deleted.

EXERCISE: 4

CREATE A EMPLOYEE DATABASE TO INCREMENT EMPLOYEE SALARY BY


1000.

create table emp50(ename varchar2(30),eno number(5),salary number(30));


Table created.

PROGRAM:
set serveroutput on
create or replace trigger etrig12 after update on emp12 for each row begin
if(:new.salary<:old.salary)then
raise_application_error(-20030,'increase the salary');
end if;
insert into updemp050 values(:new.salary,sysdate); end; /

OUTPUT:

update emp12 set salary=salary+1000 where eno=2;

select *from emp12;

Result:
EX.NO 6 Database design using Normalization – bottom-up approach
Date:

Aim:

Procedure:

Normalization

● Normalization is the process of organizing the data in the database.


● Normalization is used to minimize the redundancy from a relation or set of relations. It is
also used to eliminate the undesirable characteristics like Insertion, Update and Deletion
Anomalies.
● Normalization divides the larger table into the smaller table and links them using
relationship.
● The normal form is used to reduce redundancy from the database table.

Types of Normal Forms


There are the four types of normal forms:
First Normal Form (1NF)

● A relation will be 1NF if it contains an atomic value.


● It states that an attribute of a table cannot hold multiple values. It must hold only single-
valued attribute.
● First normal form disallows the multi-valued attribute, composite attribute, and their
combinations.

Exmaples

● Example: Relation EMPLOYEE is not in 1NF because of multi-valued attribute


EMP_PHONE.

EMP_ID EMP_NAME EMP_PHONE EMP_STATE

14 John 7272826385, UP
9064738238

20 Harry 8574783832 Bihar

12 Sam 7390372389, Punjab


8589830302

EMPLOYEE table:

The decomposition of the EMPLOYEE table into 1NF has been shown below:

EMP_ID EMP_NAME EMP_PHONE EMP_STATE

14 John 7272826385 UP

14 John 9064738238 UP

20 Harry 8574783832 Bihar

12 Sam 7390372389 Punjab

12 Sam 8589830302 Punjab

Second Normal Form (2NF)


● In the 2NF, relational must be in 1NF.
● In the second normal form, all non-key attributes are fully functional dependent on the
primary key

1. EMP_ID EMP_NAME
2. EMP_ID EMP_PHONE
3. EMP_ID EMP_STATE

Third Normal Form (3NF)

● A relation will be in 3NF if it is in 2NF and not contain any transitive partial dependency.
● 3NF is used to reduce the data duplication. It is also used to achieve the data integrity.
● If there is no transitive dependency for non-prime attributes, then the relation must be in
third normal form.

A relation is in third normal form if it holds atleast one of the following conditions for every
non-trivial function dependency X → Y.

1. X is a super key.
2. Y is a prime attribute, i.e., each element of Y is part of some candidate key.

Example:
EMPLOYEE_DETAIL table:
EMP_ID EMP_NAME EMP_ZIP EMP_STATE EMP_CITY

222 Harry 201010 UP Noida

333 Stephan 02228 US Boston

444 Lan 60007 US Chicago

555 Katharine 06389 UK Norwich

666 John 462007 MP Bhopal

Super key in the table above:

1. {EMP_ID}, {EMP_ID, EMP_NAME}, {EMP_ID, EMP_NAME, EMP_ZIP} so on


Candidate key: {EMP_ID}
Non-prime attributes: In the given table, all attributes except EMP_ID are non- prime.
Here, EMP_STATE & EMP_CITY dependent on EMP_ZIP and EMP_ZIP dependent on
EMP_ID. The non-prime attributes (EMP_STATE, EMP_CITY) transitively dependent
on super key(EMP_ID). It violates the rule of third normal form.
That's why we need to move the EMP_CITY and EMP_STATE to the new
<EMPLOYEE_ZIP> table, with EMP_ZIP as a Primary key.
EMPLOYEE table:

EMPLOYEE_ZIP table:
EMP_ZIP EMP_STATE EMP_CITY

201010 UP Noida

02228 US Boston

60007 US Chicago

06389 UK Norwich

462007 MP Bhopal

EMP_ID EMP_NAME EMP_ZIP

222 Harry 201010

333 Stephan 02228

444 Lan 60007

555 Katharine 06389

666 John 462007

Boyce Codd normal form (BCNF)

● BCNF is the advance version of 3NF. It is stricter than 3NF.


● A table is in BCNF if every functional dependency X → Y, X is the super key of the
table.
● For BCNF, the table should be in 3NF, and for every FD, LHS is super key.

Example: Let's assume there is a company where employees work in more than one department.
EMPLOYEE table:

EMP_ID EMP_COUNTRY EMP_DEPT DEPT_TYPE EMP_DEPT_NO

264 India Designing D394 283

264 India Testing D394 300

364 UK Stores D283 232

364 UK Developing D283 549

In the above table Functional dependencies are as follows:

1. EMP_ID → EMP_COUNTRY
2. EMP_DEPT → {DEPT_TYPE, EMP_DEPT_NO}

Candidate key: {EMP-ID, EMP-DEPT}


The table is not in BCNF because neither EMP_DEPT nor EMP_ID alone are keys. To
convert the given table into BCNF, we decompose it into three tables:

EMP_COUNTRY table:
EMP_ID EMP_COUNTRY

264 India

264 India

EMP_DEPT table:

EMP_DEPT DEPT_TYPE EMP_DEPT_NO

Designing D394 283

Testing D394 300

Stores D283 232

Developing D283 549

EMP_DEPT_MAPPING table:

EMP_ID EMP_DEPT

D394 283

D394 300

D283 232

D283 549

Functional dependencies:

1. EMP_ID → EMP_COUNTRY
2. EMP_DEPT → {DEPT_TYPE, EMP_DEPT_NO}

Candidate keys:
For the first table: EMP_ID
For the second table: EMP_DEPT
For the third table: {EMP_ID, EMP_DEPT}
Now, this is in BCNF because left side part of both the functional dependencies is a key.

Output:
Thus the normalization is executed in the realation.

Result:
Ex.No 7 Develop database applications using IDE/RAD tools
Date:

Aim:

Procedure:

The Development Environment


Learning the ins and outs of the Development Environment before you learn visual basic is somewhat like
learning for a test you must know where all the functions belong and what their purpose is. First we will
start with labeling the development environment.

The above diagram shows the development environment with all the important points labeled.
Many of Visual basic functions work similar to Microsoft word eg the Tool Bar and the tool box
is similar to other products on the market which work off a single click then drag the
width of the object required. The Tool Box contains the control you placed on the form window.
All of the controls that appear on the Tool Box controls on the above picture never runs out of
controls as soon as you place one on the form another awaits you on the Tool Box ready to be
placed as needed.

The project explorer window

The Project explorer window gives you a tree-structured view of all the files inserted into the
application. You can expand these and collapse branches of the views to get more or less detail
(Project explorer). The project explorer window displays forms, modules or other separators
which are supported by the visual basic like class'es and Advanced Modules. If you want to
select a form on its own simply double click on the project explorer window for a more detailed
look. And it will display it where the Default form is located.

Properties Window

Some programmers prefer the Categorisized view of the properties window. By defaulting, the
properties window displays its properties alphabetically (with the exception of the name value)
when you click on the categorized button the window changes to left picture.

The Default Layout

When we start Visual Basic, we are provided with a VB project. A VB project is a collection of
the following modules and files.
1. The global module( that contains declaration and procedures)
2. The form module(that contains the graphic elements of the VB application along
with the instruction )
3. The general module (that generally contains general-purpose instructions not
pertaining to anything graphic on-screen)
4. The class module(that contains the defining characteristics of a class, including its
properties and methods)
5. The resource files(that allows you to collect all of the texts and bitmaps for an
application in one place)

On start up, Visual Basic will displays the following windows :


1. The Blank Form window
2. The Project window
3. The Properties window

It also includes a Toolbox that consists of all the controls essential for developing a VB
Application. Controls are tools such as boxes, buttons, labels and other objects draw on a form to
get input or display output. They also add visual appeal.

Understanding the tool box.

You may have noticed that when you click on different controls the Properties Window
changes slightly this is due to different controls having different functions. Therefore more
options are needed for example if you had a picture then you want to show an image. But if you
wanted to open a internet connection you would have to fill in the remote host and other such
settings. When you use the command () you will find that a new set of properties come up the
following will provide a description and a property.

Opening an existing Visual Basic project.

Microsoft have included some freebies with visual basic to show its capabilities and functions.
Dismantling or modifying these sample projects is a good way to understand what is happening at
runtime. These files can be located at your default directory /SAMPLES/
To Open these projects choose 'Open Project' from the 'File' menu. Then Double click on the
samples folder to open the directory then Double click on any project to load it.
Opening a new visual basic file & Inserting Source code.
From looking at the examples it time to make your own application. Choose 'New Project' from
the 'File' menu. Use the blank form1 to design a simple interface for an estate agents database,
have some textboxes for names and other details. Insert some controls and make it look
professional. Textboxes can be used to store there name and other details, make sure you put a
picture box in for a picture of the house.
Now insert the following source code for your application.

Private Sub Form_Load()


Picture1.Picture = LoadPicture("C:\Program Files\VB\Graphics\Icons\Misc\MISC42.ICO")
End Sub

Running and viewing the project in detail.


Once an application is loaded it can be run by click on the icon from the toolbar, to pause press
and to terminate use . Once a project is loaded, the name of the form(s) that it contains is
displayed in the project window. To view a form in design mode, select the form required by
clicking with the mouse to highlight its name, then clicking on the view form button.

In this example the project has been loaded and the maillist.frm has been selected for viewing. This Ms
Mail example project useds 6 forms and 1 modules.
In Design mode, when the form is viewed, the code attached to any screen object may be inspected by
double clicking on that object. The screen shots below show the interface of the Ms Mail example
(.../samples/Comtool/VBMail/MaiLLST.FRM) to view the code for this form select from the project
window item.

Private Sub SetupOptionForm(BasePic As Control)


BasePic.Top = 0
BasePic.Left = 0
BasePic.Visible = True
BasePic.enabled = True
OKBt.Top = BasePic.Height + 120 Me.width
= BasePic.Width + 120 Me.Heigh = Ok
Bt.Top + OkBt.Height + 495
End Sub

Brief introduction to the usages of Access data bases


The most compelling thing about Visual Basic is it's easy way of accessing and modifying
databases. There are many ways to work with databases in Visual Basic, and Use in this text
is DAO (Data Access Objects). We will get familiar with opening a database and
retrieving/adding/deleting/updating records from tables. Use an Access Database (*.mdb) in
examples, since this is the most used DBMS (DataBase Management System) for smaller
applications made in Visual Basic. We will at the end of this lesson have made a simple, yet
functional, phone book application.

Database Object
The first thing you must do in your application is to open a database where your tables are
stored. You need to declare a variable to hold your database in order to do this. This is done
with:

Dim dbMyDB As Database

This gives you a variable/object that can hold a reference to your database. To open a simple Access
database named "MyDatabase.mdb", do this:

Set dbMyDB = OpenDatabase("MyDatabase.mdb")

So, now you have opened a database. This won't give you any data. What you need to do is open
a table in the database. You're not limited to open a single table; sometimes you have two or
more tables that are related to each other and linked together w ith foreign keys, and there are
ways to handle this to. But in this "Visual Basic - Database Primer”

RecordSet Object

Visual Basic uses an object called RecordSet to hold your table. To declare such an object and to
open the table, do this:

Dim rsMyRS As RecordSet


Set rsMyRS = dbMyDB.OpenRecordSet("MyTable", dbOpenDynaset)

Declared a RecordSet object and used the Database object's OpenRecordSet method to open a
table of type Dynaset. Open a RecordSet in several modes. VB's online help file explains the
different modes and what they are for. The Dynaset mode is the mode I use mostly. It gives you
a RecordSet that you can add, delete and modify records in.

Accessing records

Now that we have opened a table (referred to as RecordSet from now on) we want to access the
records in it. The RecordSet object allows us to move in it by using the methods MoveFirst,
MoveNext, MovePrevious, MoveLast (among others). I will use some of these to fill up a list
box with the records of our RecordSet.

To get this example to work, make a database (with Access) called "MyDatabase.mdb" with the
table "MyTable" in it. This table should have the fields "ID" of type "Counter" that you set to be
the primary key, the field "Name" of type Text and a field "P hone" of type Text. Add some
records to it. Put a list box on a form and call it "lstRecords".
Private Sub Form_Load()
Set dbMyDB = OpenDatabase("MyDatabase.mdb")
Set rsMyRS = dbMyDB.OpenRecordSet("MyTable", dbOpenDynaset)

If Not rsMyRS.EOF Then rsMyRS.MoveFirst Do


While Not rsMyRS.EOF lstRecords.AddItem
rsMyRS!Name
lstRecords.ItemData(lstRecords.NewIndex) = rsMyRS!ID
rsMyRS.MoveNext
Loop End
Sub

This will make the list box fill up with your records when the form loads. The line that says If
Not rsMyRS.EOF Then rsMyRS.M oveFirst tells the program to move to the first record in case
there are any records at all. The EOF is a Boolean property that is true if the current record is the
last. It is also true if there are no records in the RecordSet.

Then we make the program add the "Name" field of all records to the list box by adding the
current records field "Name" and moving to the next record. You ask for a field of a RecordSet
by putting a ! between the name of the RecordSet object and the na me of the field. The while
loop checks to see if there are more records to add.

Searching the RecordSet

The primary key for all the records in order to search for a record.
Put a text box somewhere on the form and call it "txtPhone". Then copy the following code to
the project.

Private Sub lstRecords_Click()


rsMyRS.FindFirst "ID=" & Str(lstRecords.ItemData(lstRecords.ListIndex))
txtPhone.Text = rsMyRS!Phone
End Sub

This will display the phone number of the selected person when clicking in the list box. It uses
the FindFirst method of the RecordSet object. This takes a string parameter that is like what is
after WHERE in a SQL expression. You state the field that you want to search in (here "ID"),
then the evaluation criteria (here "=") and last the value to search for (here the ItemData of the
selected item in the list box).
So what we did was to search for the record with the "ID" field value that was the same as the
ItemData property of the selected item in the list box. Then we show the value of the "Phone"
field in the text box.

Updating the Database

You will probably want to be able to update some value of some field when doing database
programming. This is done with Edit and Update. We will try to change the value of the "Phone"
field by editing the text in the text box and clicking a button.
Put a command button on the form and name it "cmdUpdate". Then copy the following code to
the project.

Private Sub cmdUpdate_Click()


rsMyRS.Edit
rsMyRS!Phone = txtPhone.Text
rsMyRS.Update
End Sub

Could it be that simple? Yes. This changes the phone number of our selected person. Or to put it
technically: This changes the value of the "Phone" field of our current record. Imagine the
current record being a set of boxes, with a field in each box. The Edit method takes the lid off all
of the boxes and Update puts them back on. When we write rsMyRS!Phone = txtPhone.Text we
replace the content of the "Phone" box with the content in the text box.
Deleting and Adding records

Deleting
Deleting records couldn't be simpler. To delete the current record you just invoke the Delete
method of the RecordSet object. We will put this feature in our little project. Make one more
command button named "cmdDelete" and the following code will do the work of deleting our
currently selected person.

Private Sub cmdDelete_Click()


rsMyRS.Delete
lstRecords.RemoveItem lstRecords.ListIndex
End Sub

Adding
Adding records is much like updating, except you use AddNew instead of Edit. Let's add one
more command button to our application. Let's call it...errh...let me see...yea! "cmdNew" =).
Here is the code that adds a new record.
Private Sub cmdNew_Click()
rsMyRS.AddNew
rsMyRS!Name = "A New Person"
lstRecords.AddItem rsMyRS!Name
lstRecords.ItemData(lstRecords.NewIndex) = rsMyRS!ID rsMyRS!Phone
= "Person's Phone Number"

rsMyRS.Update End
Sub

The AddNew method takes a set of new boxes and adds them to our RecordSet. We then put
some new values in them and close the lids with Update. As you can see we never stated any
value for "ID", but as you remember, this is a field of type "Counter" which automatically gets a
unique value.

RESULT :
Ex.No 8 Database design using EER-to-ODB mapping / UML class diagrams

Date:

Aim:

Procedure:

EER to ODB Mapping:

Result :
EX.NO 9 Object features of SQL-UDTs and sub-types, Tables using UDTs, Inheritance,
Date: Method definition

Aim:

Procedure:

DROP TYPE person_typ FORCE;

-- if created

CREATE OR REPLACE TYPE person_typ AS OBJECT (

idno NUMBER,

name VARCHAR2(30),

phone VARCHAR2(20),

MAP MEMBER FUNCTION get_idno RETURN NUMBER,

MEMBER FUNCTION show RETURN VARCHAR2)

NOT FINAL;

CREATE OR REPLACE TYPE BODY person_typ AS

MAP MEMBER FUNCTION get_idno RETURN NUMBER IS

BEGIN

RETURN idno;

END;

-- function that can be overriden by subtypes

MEMBER FUNCTION show RETURN VARCHAR2 IS

BEGIN

RETURN 'Id: ' || TO_CHAR(idno) || ', Name: ' || name; END;

END;

Result:
EX.NO 10 Querying the Object-relational database using Objet Query language

Date:

Aim:

Procedure:

CREATE TABLE Orders (


OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)
);

CREATE TABLE Persons ( OrderID


int NOT NULL, OrderNumber int
NOT NULL, PersonID int,
PRIMARY KEY (OrderID),
);

Result:
EX.NO 10 Querying the Object-relational database using Objet Query language

Date:

Aim:

To implement the Querying the Object-relational database using Objet Query language.

Procedure:

CREATE TABLE Orders (


OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)
);

CREATE TABLE Persons ( OrderID


int NOT NULL, OrderNumber int
NOT NULL, PersonID int,
PRIMARY KEY (OrderID),
);

Result:

Thus the relation is created as object and the SQL query is manipulated.

You might also like