Cp4152-Database Practices Lab
Cp4152-Database Practices Lab
CONSTRAINT
2
VIEWS
9
TRIGGE
10
2
AIM:
THEORY
ALTER – The structure of a table can be modified by using the ALTER TABLE command. This command is used to add
a new column, modify the existing column definition and to include or drop integrity constraint.
DROP - It will delete the table structure provided the table should be empty.
TRUNCATE - If there is no further use of records stored in a table and the structure has to be retained, and then the
records alone can be deleted.
PROCEDURE
CREATION OF TABLE:
SYNTAX:
EXAMPLE:SQL>CREATE TABLE Employee ( EmpNo number(5), EName VarChar(15), Job Char(10) , DeptNo
number(3));
ALTER TABLE
Syntax:
3
Syntax:
EXAMPLE:
Syntax:
EXAMPLE:
Syntax:
4
EXAMPLE:
RENAMING TABLES
Syntax:
EXAMPLE:
TRUNCATE TABLE
.Syntax:
DESTROYING TABLES
Syntax:
Example:
Problems
PRODUCTNO Varchar2 6
DESCRIPTION Varchar2 15
UNITMEASURE Varchar2 10
QTYONHAND Number 8
CLIENTNO Varchar2 6
NAME Varchar2 20
ADDRESS1 Varchar2 30
ADDRESS2 Varchar2 30
CITY Varchar2 15
PINCODE Number 8
STATE Varchar2 15
SALESMANNO Varchar2 6
SALESMANNAME Varchar2 20
ADDRESS1 Varchar2 30
ADDRESS2 Varchar2 30
CITY Varchar2 15
PINCODE Number 8
STATE Varchar2 15
7
SNO Number 5
SNAME Varchar2 20
AGE Number 5
SDOB Date
Add a column called ‘telephone’ of data type ‘number’ and size =’10’ to the Client _Master table.
THEORY
Constraints are the business Rules which are enforced on the data being stored
in a table are called Constraints
TYPES OF CONSTRAINTS:
1) Primary key
2) Foreign key/references
3) Check
4) Unique
5) Not null
6) Null
7) Default
PROCEDURE
Syntax:
EXAMPLE
Syntax:
EXAMPLE
Syntax:
EXAMPLE
Syntax:
EXAMPLE
Syntax
EXAMPLE
Syntax
EXAMPLE
EXAMPLE
Problems
11
ADDRESS1 Varchar2 30
ADDRESS2 Varchar2 30
CITY Varchar2 15
PINCODE Number 8
STATE Varchar2 15
ADDRESS2 Varchar2 30
CITY Varchar2 15
PINCODE Number 8
STATE Varchar2 15
AIM:
OBJECTIVES
THEORY
DML commands are the most frequently used SQL commands and is used to
query and manipulate the existing database objects. Some of the commands are
1. INSERT
This is used to add one or more rows to a table. The values are separated
by commas and the data types char and date are enclosed in apostrophes.
The values must be entered in the same order as they are defined.
2. SELECT
It is used to retrieve information from the table.it is generally referred to
as querying the table. We can either display all columns in a table or only
specify column from the table.
3. UPDATE
It is used to alter the column values in a table. A single column may be
updated or more than one column could be updated.
4. DELETE
After inserting row in a table we can also delete them if required. The
delete command consists of a from clause followed by an optional where
clause
PROCEDURE
INSERT COMMAND
Example:
15
(b) Inserting more than one record using a single insert commands:
Syntax:
Example:
SELECT COMMAND
Syntax:
Select * from
tablename;
Example:
Syntax:
Select <column1>,<column2> from tablename;
Example:
16
Syntax:
Example:
Syntax:
SELECT DISTINCT <column1>, <column2> FROM <tablename>
Example:
UPDATE COMMAND
Syntax:
DELETE COMMAND
Problems
Product Descripti Profitpe unitmeas qtyonha sellpri Cost
No on rcent ure nd ce price
P00001 Tshirt 5 piece 200 350 250
P00065 Shirt 6 piece 150 500 350
P00032 Jeans 5 piece 100 600 450
P00324 Skirts 4 piece 120 750 500
P02345 CottonJe 3 piece 80 850 550
ans
AIM:
OBJECTIVES
THEORY
a) NESTED QUERIES:
A sub query is a query within a query. In Oracle, we can create sub queries
within your SQL statements. These sub queries can reside in the WHERE
clause, the FROM clause, or the SELECT clause.
b) JOINS:
Natural join:
It returns the matching rows from the table that are being joined
.
Syntax:
>select <attribute> from TN where TN1.attribute=TN2.attribute.
Inner join:
It returns the matching rows from the table that are being joined.
Syntax:
>select <attribute> from TN1 innerjoin TN2 on TN1.attribute=TN2.attribute.
Left outer join:
It returns all the rows from the table1 even when they are unmatched.
Syntax:
5. select <attribute> from TN1 left outer join TN2 on
TN1.attribute=TN2.attribute.
2. select <attribute> from TN where TN1.attribute(+)=TN2.attribute.
22
Syntax:
4. select <attribute> from TN1 right outer join TN2 on
TN1.attribute=TN2.attribute.
2. select <attribute> from TN where TN1.attribute=(+)TN2.attribute.
Full join:
PROCEDURE
NESTED QUERIES -
PNO NUMBER(3)
ENO NUMBER(3)
23
PJOB CHAR(12)
1 DBMS 2
2 COMPILER 3
3 C1 1
1 1 Programmer
2 1 Analyst
1 2 Analyst
2 2 Programmer
NESTED QUERIES
(i) SQL> select ename from emp_det where dno not in(select dno from
emp_det where ename ='SaravanaKumar');
ENAME
24
RajKumar
Shirley
(ii)SQL> select ename, dno from emp_det where dno = (select dno from
emp_det where ename ='RajKumar');
ENAME DNO
RajKumar 2
(iii)SQL> select ename from emp_det where eno in(select eno from work_in
where pno = (select pno from pro_det where pname = 'DBMS')) order by
ename;
ENAME
Mahendran
SaravanaKumar
(iv)SQL> select ename, basic_sal from emp_det where dno = 2 and
basic_sal>(select max(basic_sal) from emp_det where dno = 10) order by
ename;
ENAME BASIC_SAL
RajKumar 10000
(v)SQL> select pno,pname from pro_det where exists(select pno from work_in
where work_in.pno =pro_det.pno);
PNO PNAME
1 DBMS
2 COMPILER
MAX(BASIC_SAL)
8000
(ix)SQL> select * from emp_det where basic_sal < (select avg(basic_sal) from
emp_det);
JOINS
SQL> create table emp(name varchar2(20),salary number(10));
Table created.
SQL> select * from emp;
NAME SALARY
ashu 10000
asma 1200
asif 2000
arif 1000
niyas 3000
SQL> create table emp1(name varchar2(20),empid number(10));
Table created.
.
SQL> select * from emp1;
NAME EMPID
fathi 12
sumi 32
priya 11
wahab 10
sweety 9
asma 1200
26
6 rows selected.
NATURAL JOIN
************
SQL>select emp.name,salary from emp,emp1 where emp.name=emp1.name
NAME SALARY
asma 1200
LEFT OUTER JOIN
SQL>select emp.name,salary from emp left outer join emp1 on
emp.name=emp1.name
NAME SALARY
asma 1200
asif 2000
arif 1000
niyas 3000
ashu 10000
RIGHT OUTER JOIN
wahab 10
fathi 12
priya 11
10 rows selected.
RESULT:
Thus the nested queries and join operations are executed and verifiedin DBMS.
28
EXPERIMENT NO: 5
DATABASE CONNECTIVITY
AIM
Create a php program that allows to enter the employee details into a database.
To create an application program that process a query which returns the grade
result of a student after processing the marks table.
OBJECTIVES
Requirements:
PROCEDURE
Create a database in Mysql. Create a 'marks' table with fields regno, name,
batch, mark1, mark2 and mark3. Write a function which finds the total marks
and if the total marks is greater than 225 then the result is categorized as
“Distinction”, if the total marks is less than 225 , the result is “firstclass”, it the
total marks is less than 180, the result is “second class”, if the total marks is less
than 150 the result is “passed”. If the marks in any one of the subject is less than
40 the result is “Failed”.
php code:
29
<?php
$user_name = "root";
$password = "";
$server = "localhost";
$database = "mysql";
$regno = $_POST['regno'];
//$regno = 1;
if (!$db_handle)
{
die('Could not connect: ' . mysql_error());
}
//echo 'Connected successfully';
$db_found = mysql_select_db($database);
if ($db_found)
{
//echo "Database found";
$SQL = "SELECT * FROM marks WHERE regno = '".$regno."'";
$result_set = mysql_query($SQL);
$record = mysql_fetch_array($result_set);
echo "<BR>MARKLIST";
echo "<BR>Reg No..:".$record['regno'];
echo "<BR>Name.....".$record['name'];
echo "<BR>Group....".$record['batch'];
echo "<BR>Mark1....".$record['mark1'];
echo "<BR>Mark2....".$record['mark2'];
30
echo "<BR>Mark3...:".$record['mark3'];
echo "<BR>Result..:".
compute_result($record['mark1'],$record['mark2'],$record['mark3']);
}
else
{
Html code:
<html>
<body>
<FORM Method = "post" Action="connect1.php">
Reg No:
<INPUT Type = "text" name = "regno"> <BR>
<INPUT type = "submit" value = "Show Result">
</FORM>
</body>
</html> OUTPUT
RESULT
32
Procedure
Installing MongoDB
If you haven’t installed MongoDB yet, let’s do it first. Download the MongoDB package suitable
for your OS. Download the msi/zip file compatible with your OS and install the application. (I am
not going to describe the installation process in detail, as it is straightforward.)
I assume now you have installed the MongoDB database successfully. Open your CMD and
type mongod –version to verify your installation. If you get an output similar to the result in the
picture below, everything is perfect.
When you install MongoDB, a CLI tool called Mongo shell will be installed along with it. You can use it to give
commands to the MySQL server. In order to get access to the mongo shell, you have to start the server with the
following command:
Copy
If you get this output, the MongoDB server has successfully started:
33
Next, we should run the MongoDB shell. To do that, type the command mongo in the CMD.
Now you are in the MongoDB shell, where you can execute commands to:
Create databases
Insert data
As I said earlier, there is no ‘create database’ command in MongoDB. It doesn’t mean there is no way to create a
database—of course there is. Let’s see how, by creating a database called Company using the shell.
MongoDB has a keyword called ‘use,’ which is used to switch to a specified database. For example, if you want
to connect with an existing database named Employee, you can use the command ‘use Employee’ to connect
with it. However, if there is no database as Employee, the command ‘use’ will create it and connects you to it.
Let’s use the ‘use’ command to create our database.
Copy
34
use Company
When you use the command, you will see the following output:
Mongo has created the company database and connected you to it. You can use the db command to confirm,
which will display the currently connected database.
You might want to see all the existing databases before creating a new database. You can do it with the show
dbs command, and it will return the following result:
Admin
Config
Local
Surprisingly, the database we just created is not listed. This is because MongoDB doesn’t truly create the
database until we save values to it.
One of the critical features in NoSQL databases like MongoDB is that they are schema-less—there’s no schema.
That means you don’t specify a structure for the databases/tables as you do in SQL. Instead of tables and rows in
SQL, MongoDB has collections and documents. So, let’s see how you work with collections in MongoDB.
In SQL, you have tables that have a well-defined structure with columns and specified data types. You insert
data into tables as records. Every record you insert should have values (including null values) for every column
defined on the table.
In contrast, NoSQL has collections instead of tables. These collections don’t have any structure, and you insert
data, as documents, into the collection. That means that one document can be completely different from another
document. Let’s create a collection called Employee and add a document to it.
35
Before you could create a collection, remember that you add data to documents in JSON format. So, the
command to insert one document to our database will look like this:
Copy
db.Employee.insert(
"Employeename" : "Chris",
"EmployeeDepartment" : "Sales"
First, switch to the database to add values using the ‘use’ command. Then use db.Employee.insert command to
add a document to the database:
A significant issue you’ll notice in this query is we haven’t set a primary key. MongoDB automatically creates a
primary key field called _id and sets a default value to it. To see this, let’s view the collection we just created.
Run the following command to access our collection in JSON format.
Copy
db.Employee.find().forEach(printjson)
In MongoDB, you cannot set an arbitrary field to the primary key. However, you can change the value of the
default primary key. Let’s add another document while giving value for _id as well.
Copy
db.Employee.insert(
"_id" : 1,
"EmployeeName" : "Mark",
"EmployeeDepartment" : "Marketing"
Great. Now we know how to use the primary key as well. Let’s get back to our main topic. Have we created our
database now? Run the following command again to find it out.
Copy
show dbs
Now you can see the database ‘company’ is listed in the result: it worked!
Removing a database
37
It’s not good to leave this meaningless database on your server. So, let’s remove it as it is a good chance for us
to learn how to drop a database. To drop any database you want, first, you have to connect with it using the use
keyword.
Copy
use Company
That should be the end of our tutorial—we created and removed a Mongo database. However, I want to talk
about one more thing. Although the Mongo shell is a great tool for working with MongoDB servers, many
people find it difficult, especially in a production environment.
That’s why I encourage you to get familiar with a MongoDB Compass tool, a great GUI to work with
MongoDB. Here, I will show you how to create a database in Compass GUI. You can download the Compass
IDE for any operating system. Again, the installation process is very straightforward.
Now open the application and create a connection with the MySQL server that we installed earlier.
38
Go to ‘Fill in connection fields individually.’ It will take you to the following screen. If you use the default
values when installing MongoDB, all you have to do is click the CONNECT button.
39
Now you can see a list of databases available on your MongoDB server.
40
Click the create database button to create a new database. Then, give a database name and a collection name:
41
Unlike the Mongo shell, Compass will create a database even without adding any data:
AIM
Program
<p id="demo"></p>
<script>
var text, parser, xmlDoc;
text = "<bookstore><book>" +
"<title>Everyday Italian</title>" +
"<author>Giada De Laurentiis</author>" +
"<year>2005</year>" +
"</book></bookstore>";
document.getElementById("demo").innerHTML =
xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue;
</script>
</body>
</html>
Output
Everyday Italian
DTD
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE note [
<!ENTITY nbsp " ">
<!ENTITY writer "Writer: Donald Duck.">
<!ENTITY copyright "Copyright: W3Schools.">
44
]>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
<footer>&writer; ©right;</footer>
</note>
Output
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
<footer>Writer: Donald Duck. Copyright: W3Schools.</footer>
</note>
AIM
Procedure
Document table
Keyed table
It also makes the data more available, since you don’t need an XML
parser to read the information.
47
Result: To using a relational database to store the xml document as text study sucessfully.
48
AIM:
THEORY
A view is the tailored presentation of data contained in one or more table and can also be said as
restricted view to the data‟s in the tables. A view is a “virtual table” or a “stored query” which takes the output
of a query and treats it as a table. The table upon which a view is created is called as base table . 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 .
Advantages of a view:
Syntax:
Example
Create or replace view empview as select * from emp; Drop view empview;
PROCEDURE
create a table aa
Bb 23 2001 12 23435
Cc 55 342 76 687478
dd 2 1233 123 53616578
ee 21 1111 111 12435798
49
create table qq
bb 21 23 dfd 573568
cc 43 55 fg 65839
ee 44 21 dfd 1235798
oo 87 34 gfh 6358379
create a view on qq
View created.
BOOK NAMEPUBLISHER
21 bb qwa
SQL> create view wq as select name,ISBN,publisher from qq where book>21 View created.
cc 65839 fg
ee 1235798 dfd
oo 6358379 gfh
SQL> create view ss as select name,book from aa union select name,book from qq;
View created.
NAME BOOK
bb 21
bb 23
cc 43
cc 55
dd 2
ee 21
ee 44
oo 87
8 rows selected.
51
Problems
Doc_code Varchar2(4)
Doc_name Varchar2(4)
Specialization Varchar2(4)
Department Varchar2(4)
Date_of_join Date
Exper Number(2)
create another view that contains doctor codes and doctor names of ‘orthology’ department
Result
Create a Trigger for EMP table it will update another table SALARY while inserting values
PROCEDURE
step 1: start
step 3:specify the operations (update, delete, insert) for which the trigger has to be executed.
step 4: execute the trigger procedure for both before and after sequences step 5: carryout the operation on the
table to check for trigger execution. step 6: stop
PROGRAM
sql> create or replace trigger emptrigr after insert on emp for each row
declare
end;
/trigger created.
vec 1 1000
srm 0 0
53
Vec 1 1000
srm 1 3000
vec 2 6000
srm 1 3000
vec 3 8000
srm 1 3000
1 row created.
Vec 3 8000
Srm 2 11000
54
Problems
Write a trigger that stores the details of students changing their program from CT to CHM.
Write an update trigger on CLIENT_MASTER table.The system should keep track of the records that are being
updated.The old values of the updated record should be added in the AUDIT_TRAIL table
Client_no Varchar2 6
name Varchar2 20
Operation Varchar2 8
userid Varchar2 20
olddate date
RESULT:
The trigger procedure has been executed successfully for both before and after sequences.
55