Database Management Laboratory
Database Management Laboratory
Name :
Register Number :
Aim:
To create a database table, add constraints (primary key, unique, check, Not null),
insert rows, update and delete rows using SQL DDL and DML commands.
Description:
These SQL commands are mainly categorized into five categories as:
Data Definition Language consists of the SQL commands that can be used to define
the database schema. It simply deals with descriptions of the database schema and is used to
create and modify the structure of database objects in the database. DDL is a set of SQL
commands used to create, modify, and delete database structures but not data. These
commands are normally not used by a general user, who should be accessing the database
via an application.
DDL commands:
1. CREATE: This command is used to create the database or its objects (like table, index,
function, views, store procedure, and triggers).
name(column_1 datatype, column_2 datatype,
column_3 datatype, ....);
4. TRUNCATE: This is used to remove all records from a table, including all spaces
allocated for the records are removed.
Syntax: TRUNCATE TABLE table_name;
5. COMMENT: This is used to add comments to the data dictionary.
6. RENAME: This is used to rename an object existing in the database.
The SQL commands that deals with the manipulation of data present in the database belong
to DML or Data Manipulation Language and this includes most of the SQL statements. It is
the component of the SQL statement that controls access to data and to the database.
Basically, DCL statements are grouped with DML statements.
SQL Constraints
SQL constraints are used to specify rules for the data in a table.Constraints are used to
limit the type of data that can go into a table. This ensures the accuracy and reliability of the
data in the table. If there is any violation between the constraint and the data action, the
action is aborted.
Constraints can be column level or table level. Column level constraints apply to a
column, and table level constraints apply to the whole table.
The following constraints are commonly used in SQL:
Constraints can be specified when the table is created with the CREATE TABLE
statement, or after the table is created with the ALTER TABLE statement.
SQL> create table emp_details(emp_no int(10) primary key, emp_name varchar(20) not null,
age int(3) check(age>=20), address varchar(30), doj varchar(10), mobile_no int(12) unique,
dept_no int(5) not null, salary int(10));
SQL> insert into emp_details(emp_no, emp_name, age, address, doj, mobile_no, dept_no,
salary) values (102, 'RRR', 20, 'Salem', '24/06/2017', '9175368421', 563, 7500), (103, 'FFF', 30,
'Salem', '24/07/2000', '7875368421', 541, 20000), (104, 'XXX', 35, 'Erode', '06/07/2001',
'7894563421', 563, 25000);
Result:
Thus the database table with constraints has been created and various DDL and DML
commands have been executed successfully.
Ex.No.:02
Referential Integrity
Date:
Aim:
To create a set of tables, add foreign key constraints and incorporate referential
integrity.
Description:
Referential integrity refers to the relationship between tables. Because each table in a
database must have a primary key, this primary key can appear in other tables because of its
relationship to data within those tables. When a primary key from one table appears in
another table, it is called a foreign key.
The table containing the foreign key is called the child table(Referencing Table), and
the table containing the Primary key/candidate key is called the master or parent
table(Referenced Table).
The essential syntax for a defining a foreign key constraint in a CREATE TABLE or
ALTER TABLE statement includes the following:
reference_option:
Referential Actions
When an UPDATE or DELETE operation affects a key value in the parent table that
has matching rows in the child table, the result depends on the referential action specified by
ON UPDATE and ON DELETE subclauses of the FOREIGN KEY clause.
CASCADE: Delete or update the row from the parent table and automatically delete or
update the matching rows in the child table. Both ON DELETE CASCADE and ON UPDATE
CASCADE are supported. Between two tables, do not define several ON UPDATE
CASCADE clauses that act on the same column in the parent table or in the child table.
RESTRICT: Rejects the delete or update operation for the parent table. Specifying RESTRICT
(or NO ACTION) is the same as omitting the ON DELETE or ON UPDATE clause.
SET DEFAULT: This action is recognized by the MySQL parser, but both InnoDB and NDB
reject table definitions containing ON DELETE SET DEFAULT or ON UPDATE SET
DEFAULT clauses.
For storage engines that support foreign keys, MySQL rejects any INSERT or
UPDATE operation that attempts to create a foreign key value in a child table if there is no
matching candidate key value in the parent table.
For an ON DELETE or ON UPDATE that is not specified, the default action is always
NO ACTION.
A foreign key constraint can be added to an existing table using ALTER TABLE
syntax:
Queries:
SQL> create table product (category int not null, id int not null, price decimal, primary
key(category, id));
SQL> create table customer (id int not null, primary key(id));
SQL> create table product_order (no int not null auto_increment, product_category int not
null, product_id int not null, customer_id int not null, primary key(no), index
(product_category, product_id), index (customer_id), foreign key (product_category,
product_id) references product(category, id) ON UPDATE CASCADE ON DELETE
RESTRICT, foreign key (customer_id) references customer(id));
SQL> insert into product (category, id, price) values (542,1001,25.89), (542,1002,40),
(543,1003,80);
category id price
542 1001 26
542 1002 40
543 1003 80
id
121
123
124
Output: Error Code: 1452. Cannot add or update a child row: a foreign key constraint
fails (`dbmslab`.`product_order`, CONSTRAINT `product_order_ibfk_1` FOREIGN KEY
(`product_category`, `product_id`) REFERENCES `product` (`category`, `id`) ON DELETE
RESTRICT ON UPDATE CASCADE)
Output: Error Code: 1062. Duplicate entry '2' for key 'product_order.PRIMARY'
Output: Error Code: 1451. Cannot delete or update a parent row: a foreign key
constraint fails (`dbmslab`.`product_order`, CONSTRAINT `product_order_ibfk_2`
FOREIGN KEY (`customer_id`) REFERENCES `customer` (`id`))
id
123
124
Result:
Thus a set of tables have been created, added foreign keys and incorporated
referential integrity successfully.
Ex.No.:03
Basic Operations and Aggregate Functions
Date:
Aim:
To query the database tables using ‘where’ clause conditions and to implement basic
SQL operations and various aggregate functions.
Description:
The SQL WHERE Clause: The WHERE clause is used to filter records. It is used to extract
only those records that fulfill a specified condition. The WHERE clause is not only used in
SELECT statements, it is also used in UPDATE, DELETE, etc.
Operators used in The WHERE Clause are Equal(=), Greater than (>), Less than (<),
Greater than or equal (>=), Less than or equal (<=), Not equal (<> or !=), BETWEEN
(Between a certain range), LIKE (Search for a pattern), IN (To specify multiple possible
values for a column).
Basic operations:
Rename or Aliases
SQL aliases or rename are used to give a table, or a column in a table, a temporary
name. Aliases are often used to make column names more readable. An alias only exists for
the duration of that query. An alias is created with the AS keyword.
LIKE operator
The LIKE operator is used in a WHERE clause to search for a specified pattern in a
column.
There are two wildcards often used in conjunction with the LIKE operator:
Syntax
Some examples showing different LIKE operators with '%' and '_' wildcards:
LIKE Operator Description
WHERE CustomerName LIKE 'a%' Finds any values that start with "a"
WHERE CustomerName LIKE '%a' Finds any values that end with "a"
WHERE CustomerName LIKE '%or%' Finds any values that have "or" in any position
WHERE CustomerName LIKE '_r%' Finds any values that have "r" in the second
position
WHERE CustomerName LIKE 'a_%' Finds any values that start with "a" and are at
least 2 characters in length
WHERE CustomerName LIKE 'a_ _%' Finds any values that start with "a" and are at
least 3 characters in length
WHERE ContactName LIKE 'a%o' Finds any values that start with "a" and ends
with "o"
ORDER BY operator
The BETWEEN operator selects values within a given range. The values can be
numbers, text, or dates. The BETWEEN operator is inclusive: begin and end values are
included. NOT BETWEEN operator does not include begin and end values.
Set operators
Set operators combine the results of two component queries into a single result.
Queries containing set operators are called compound queries.
Operator Returns
MINUS/EXCEPT All distinct rows selected by the first query but not the second
The WHERE clause can be combined with AND, OR, and NOT operators.
The AND and OR operators are used to filter records based on more than one
condition:
● The AND operator displays a record if all the conditions separated by AND are TRUE.
● The OR operator displays a record if any of the conditions separated by OR is TRUE.
● The NOT operator displays a record if the condition(s) is NOT TRUE.
Aggregate Function: An aggregate function is a function where the values of multiple rows
are grouped together as input on certain criteria to form a single value of more significant
meaning. Aggregate functions are often used with the GROUP BY and HAVING clauses of
the SELECT statement.
1. COUNT(): The count function returns the number of rows in the result. It does not
count the null values.
Types
COUNT(*): Counts all the number of rows of the table including null.
3. MIN(): MIN function is used to find the minimum value of a certain column. This
function determines the smallest value of all selected values of a column.
4. MAX(): MAX function is used to find the maximum value of a certain column. This
function determines the largest value of all selected values of a column.
5. SUM(): Sum function is used to calculate the sum of all selected columns. It works on
numeric fields only.
The GROUP BY statement groups rows that have the same values.
GROUP BY column_name(s);
HAVING clause
The HAVING clause was added to SQL because the WHERE keyword cannot be used
with aggregate functions.
Queries:
Item1 Com1 2 10 20
Item2 Com2 3 25 75
Item3 Com1 2 30 60
Item4 Com3 5 10 50
Item5 Com2 2 20 40
Item6 Com1 3 25 75
Item7 Com1 5 30 150
Item8 Com1 3 10 30
Item9 Com2 2 25 50
company price
Com1 20
Com1 30
Com2 40
Com3 50
Com2 50
Com1 60
Com2 75
Com1 75
Com3 120
Com1 150
PRODUCT
Item1
Item3
Item6
Item7
Item8
SQL> select company, cost from product_mast where cost between 75 and 150;
company price
Com2 75
Com1 75
Com3 120
Com1 150
SQL> select * from product_mast where rate not between 20 and 25;
Item1 Com1 2 10 20
Item3 Com1 2 30 60
Item4 Com3 5 10 50
Item8 Com1 3 10 30
SQL> select * from product_mast where qty>2 union select * from product_mast where
cost>50;
Item2 Com2 3 25 75
Item4 Com3 5 10 50
Item6 Com1 3 25 75
Item8 Com1 3 10 30
Item10 Com3 4 30 120
Item3 Com1 2 30 60
SQL> select * from product_mast where qty>2 union all select * from product_mast where
cost>50;
Item2 Com2 3 25 75
Item4 Com3 5 10 50
Item6 Com1 3 25 75
Item8 Com1 3 10 30
Item2 Com2 3 25 75
Item3 Com1 2 30 60
Item6 Com1 3 25 75
SQL> select * from product_mast where qty>2 intersect select * from product_mast where
cost>50;
Item2 Com2 3 25 75
Item6 Com1 3 25 75
Item4 Com3 5 10 50
Item8 Com1 3 10 30
Item3 Com1 2 30 60
Item9 Com2 2 25 50
Item1 Com1 2 10 20
Item2 Com2 3 25 75
Item3 Com1 2 30 60
Item5 Com2 2 20 40
Item6 Com1 3 25 75
Item9 Com2 2 25 50
Item4 Com3 5 10 50
Item5 Com2 2 20 40
Item8 Com1 3 10 30
COUNT(*)
10
COUNT(*)
COUNT(DISTINCT
COMPANY)
3
COMPANY COUNT(*)
Com1 5
Com2 3
Com3 2
SQL> select company, count(*) from product_mast group by company having count(*)>2;
Com1 5
Com2 3
SQL> select sum(cost) from product_mast;
SUM(COST)
670
SQL> select company, sum(cost) from product_mast group by company having
sum(cost)>=170;
COMPANY SUM(COST)
Com1 335
Com2 170
SQL> select avg(cost) from product_mast;
AVG(COST)
67.0000
SQL> select max(rate) from product_mast;
MAX(RATE)
30
SQL> select min(rate) from product_mast;
MAX(RATE)
10
Sample table: Customers
Result:
Thus querying the database tables using ‘where’ clause conditions and basic SQL
operations and aggregate functions have been implemented and executed successfully.
Ex.No.:04
Sub queries
Date:
Aim:
Description:
A Subquery or Inner query or a Nested query is a query within another SQL query
and embedded within the WHERE clause, HAVING clause, FROM clause.
A subquery is used to return data that will be used in the main query as a condition to
further restrict the data to be retrieved.
Subqueries can be used with the SELECT, INSERT, UPDATE, and DELETE statements
along with the operators like =, <, >, >=, <=, IN, BETWEEN, etc.
Subqueries also can be used with INSERT statements. The INSERT statement uses the
data returned from the subquery to insert into another table. The selected data in the
subquery can be modified with any of the character, date or number functions.
The subquery can be used in conjunction with the UPDATE statement. Either single or
multiple columns in a table can be updated when using a subquery with the UPDATE
statement.
The subquery can be used in conjunction with the DELETE statement like with any
other statements mentioned above.
IN/NOT IN: The IN operator allows to specify multiple values in a WHERE clause.
or
Queries
6 Konal 22 MP 4500.00
SQL> select * from customers where id in (select id from customers where salary > 4500) ;
SQL> insert into customers_bkp select * from customers where id in (select id from
customers);
SQL> update customers set salary = salary * 0.25 where age in (select age from
customers_bkp where age >= 27 );
6 Konal 22 MP 4500.00
SQL> delete from customers where age in (select age from customers_bkp where age >= 27 );
table 2:artists
id first_name last_name
1 Thomas Black
2 Kate Smith
3 Natali Wein
4 Francesco Benelli
table3 : collectors
id first_name last_name
101 Brandon Cooper
102 Laura Fisher
103 Christina Buffet
104 Steve Stevenson
table4 : sales
SQL> select name, listed_price from paintings where listed_price> (select avg(listed_price)
from paintings);
name listed_price
Pretty woman 2800.00
Handsome man 2300.00
Cool painting 5000.00
SQL> select first_name, last_name from collectors where id in (select collector_id from sales);
first_name last_name
Laura Fisher
Christina Buffet
Steve Stevenson
Result:
Thus the subqueries with simple join operations have been used to query the database
and have been executed successfully.
Ex.No.:05
Join operations
Date:
Aim:
Description:
An SQL JOIN statement is used to combine data or rows from two or more tables
based on a common field between them.
The INNER JOIN selects all rows from both participating tables as long as there is a
match between the columns. An SQL INNER JOIN is the same as a JOIN clause, combining
rows from two or more tables. The INNER JOIN in SQL joins two tables according to the
matching of a certain criteria using a comparison operator.
SQL EQUI JOIN performs a JOIN against equality or matching column(s) values of
the associated tables. An equal sign (=) is used as a comparison operator in the where clause
to refer equality. EQUI JOIN can also be performed by using JOIN keyword followed by ON
keyword and then specifying names of the columns along with their associated tables to
check equality.
The SQL NATURAL JOIN is a type of EQUI JOIN and is structured in such a way that
columns with the same name of associated tables will appear once only.
● The associated tables have one or more pairs of identically named columns.
● The columns must be the same data type.
● Don’t use the ON clause in a natural join.
The SQL CROSS JOIN produces a result set which is the number of rows in the first
table multiplied by the number of rows in the second table if no WHERE clause is used along
with CROSS JOIN.This kind of result is called a Cartesian Product. If WHERE clause is used
with CROSS JOIN, it functions like an INNER JOIN.
The SQL OUTER JOIN returns all rows from both the participating tables which
satisfy the join condition along with rows which do not satisfy the join condition. The SQL
OUTER JOIN operator (+) is used only on one side of the join condition only.
The SQL LEFT JOIN (specified with the keywords LEFT JOIN and ON) joins two
tables and fetches all matching rows of two tables for which the SQL-expression is true, plus
rows from the first table that do not match any row in the second table.
The SQL RIGHT JOIN, joins two tables and fetches rows based on a condition, which
is matching in both the tables ( before and after the JOIN clause mentioned in the syntax
below) , and the unmatched rows will also be available from the table written after the JOIN
clause ( mentioned in the syntax below ).
In SQL the FULL OUTER JOIN combines the results of both left and right outer joins
and returns all (matched or unmatched) rows from the tables on both sides of the join clause.
Queries:
table1-Customers
customer_id first_name
1 John
2 Robert
3 David
4 John
5 Betty
Table2-Orders
1 200 10
2 500 3
3 300 6
4 800 5
5 150 8
5 Betty 800
[Note: Above query also represents INNER JOIN, EQUI JOIN(equality operator is used)]
3 David 2 500
5 Betty 4 800
5 Betty 4 800
3 David 2 500 3
5 Betty 4 800 5
3 David 2 500 3
5 Betty 4 800 5
3 David 500
5 Betty 800
2 Robert NULL
4 John NULL
1 John NULL
Result:
Thus the join operations have been used to query the database and have been
executed successfully.
Ex.No.:06
User Defined Functions and Procedures
Date:
Aim:
To write and execute user defined functions and stored procedures in SQL.
Description:
Stored Procedures:
Stored procedures can also include the IF, CASE, and LOOP control flow statements
that procedurally implement the code.
DELIMITER $$
BEGIN
Declaration_section
Executable_section
END $$
DELIMITER ;
Here, the first DELIMITER argument sets the default delimiter to &&, while the last
DELIMITER argument sets it back to the semicolon ;.
IN – Use to pass a parameter as input. When it is defined, the query passes an argument to
the stored procedure. The value of the parameter is always protected.
OUT – Use to pass a parameter as output. You can change the value within the stored
procedure, and the new value is passed back to the calling program.
INOUT – A combination of IN and OUT parameters. The calling program passes the
argument, and the procedure can modify the INOUT parameter, passing the new value back
to the program.
Syntax:
Delete a stored procedure from the server by using the DROP PROCEDURE statement.
The function which is defined by the user is called a user-defined function. MySQL
user-defined functions may or may not have parameters that are optional, but it always
returns a single value that is mandatory.
Syntax: DELIMITER $$
RETURNS Return_datatype
[NOT] DETERMINISTIC
BEGIN
Function Body
Return Return_value
END$$
DELIMITER;
First, specify the name of the user-defined function that needs to be created after the
CREATE FUNCTION statement.
Second, list all the input parameters of the user-defined function inside the
parentheses followed by the function name. By default, all the parameters are IN parameters.
Third, specify the data type of the return value in the RETURNS statement, which can
be any valid MySQL data type.
Fourth, specify if the function is deterministic or not using the DETERMINISTIC
keyword. It is optional. MySQL uses the NOT DETERMINISTIC option. A deterministic
function in MySQL always returns the same result for the same input parameters whereas a
non-deterministic function returns different results for the same input parameters.
Fifth, write the code in the body of the user-defined function within the BEGIN &
END block. Inside the body section, at least one RETURN statement must be specified. The
RETURN statement returns a value to the calling programs. Whenever the RETURN
statement is reached, the execution of the stored function is terminated immediately.
SELECT <Function_Name>(Value);
Queries:
SQL> DELIMITER $$
BEGIN
update product_price
set price=(price+amt)
where prd_name=prd_name1;
END $$
DELIMITER ;
Functions:
SQL> DELIMITER $$
RETURNS INT
DETERMINISTIC
BEGIN
RETURN TotalCube;
END$$
DELIMITER ;
Func_Cube(3)
27
Result:
Thus the user defined functions and stored procedures have been executed
successfully.
Ex.No.:07
DCL and TCL commands
Date:
Aim:
Description:
Parameters Used:
privileges_name: These are the access rights or privileges granted to the user.
object: It is the name of the database object to which permissions are being granted. In the
case of granting privileges on a table, this would be the table name.
user: It is the name of the user to whom the privileges would be granted.
Parameters Used:
object: It is the name of the database object from which permissions are being revoked. In the
case of revoking privileges from a table, this would be the table name.
user: It is the name of the user from whom the privileges are being revoked.
The privileges that can be granted or revoked to/from the users are SELECT, INSERT,
CREATE, DELETE, ALTER, UPDATE, INDEX, DROP, ALL, GRANT.
1. Commit
2. Rollback
3. Savepoint
Commit: COMMIT command in SQL is used to save all the transaction-related changes
permanently to the disk. Whenever DDL commands such as INSERT, UPDATE and DELETE
are used, the changes made by these commands are permanent only after closing the current
session. So before closing the session, one can easily roll back the changes made by the DDL
commands. Hence, if the changes are to be saved permanently to the disk without closing the
session, then the commit command will be used.
Syntax: COMMIT;
Rollback: This command is used to restore the database to its original state since the last
command that was committed.
Syntax: ROLLBACK;
The ROLLBACK command is also used along with the savepoint command to leap to
a save point in a transaction.
Savepoint: This command is used to save the transaction temporarily. So the users can
rollback to the required point of the transaction.
Queries:
Table:Student
Name Marks
John 79
Jolly 65
Shuzan 70
Name Marks
John 79
Sherlock 65
Shuzan 70
SQL> ROLLBACK;
Name Marks
John 79
Jolly 65
Shuzan 70
If commit was not performed then the changes made by the update command can be
rollback.
SQL> COMMIT;
Name Marks
John 79
Sherlock 65
Shuzan 70
SQL> ROLLBACK;
Name Marks
John 79
Sherlock 65
Shuzan 70
SQL> INSERT INTO Student Values(‘Jack’, 95);
SQL>COMMIT;
SQL> SAVEPOINT A;
SQL> SAVEPOINT B;
SQL> SAVEPOINT C;
Name Marks
John 79
Jolly 65
Rossie 70
Jack 95
Zack 76
Bruno 85
SQL> ROLLBACK to B;
Name Marks
John 79
Jolly 65
Rossie 70
Jack 95
Zack 76
SQL> Rollback to A;
Name Marks
John 79
Jolly 65
Rossie 70
Jack 95
Result:
Aim:
To write SQL Triggers for insert, delete and update operations in the database table.
Description:
Syntax:
ON [Table_Name]
AS
create trigger [trigger_name]: Creates or replaces an existing trigger with the trigger_name.
on [table_name]: This specifies the name of the table associated with the trigger.
[for each row]: This specifies a row-level trigger, i.e., the trigger will be executed for each row
being affected.
BEFORE triggers run the trigger action before the triggering statement is run. AFTER
triggers run the trigger action after the triggering statement is run.
Queries:
SQL> CREATE TABLE Student_Trigger ( Student_RollNo INT NOT NULL PRIMARY KEY,
Student_FirstName Varchar (100),Student_EnglishMarks INT, Student_PhysicsMarks INT,
Student_ChemistryMarks INT, Student_MathsMarks INT, Student_TotalMarks INT,
Student_Percentage INT);
BEFORE INSERT
ON
Student_Trigger
Thus, SQL Triggers for insert, delete and update operations in the database table has
been written and executed successfully.
Ex.No.:09
Views and Index
Date:
Aim:
To create views and index for the database table with a large number of records.
Description:
Views:
In SQL, a view is a virtual table based on the result-set of an SQL statement. A view
contains rows and columns, just like a real table. The fields in a view are fields from one or
more real tables in the database.
Creating a view:
Updating a View
Dropping a View
Index:
The Index in SQL is a special table used to speed up the searching of the data in the
database tables. It also retrieves a vast amount of data from the tables frequently.
To specify sort order, add the keyword ASC or DESC after each column name,
To rename an index:
Syntax: ALTER INDEX old_Index_Name RENAME TO new_Index_Name;
Queries:
NAME ADDRESS
Harsh Kolkata
Ashish Durgapur
Pratik Delhi
Dhanraj Bihar
NAME ADDRESS
Harsh Kolkata
Ashish Durgapur
Pratik Delhi
Dhanraj Bihar
Suresh Gurgaon
Result:
Thus, views and index for the database table with a large number of records have
been created and executed successfully.
Ex.No.:10
XML database and XML schema
Date:
Aim:
Procedure:
System.Xml
System.Xml.Schema
Create an XML document
1. Start Microsoft Visual Studio or Microsoft Visual Studio .NET. Then, create a new
XML file (on the File menu, point to New, and then click File).
2. Select the XML File type, and then click Open.
3. Add the following data to the XML document to represent a product in a catalog:
<Product ProductID="123">
<ProductName>Rugby jersey</ProductName>
</Product>
4. Save the file as Product.xml in a folder that you will be able to readily access later.
1. In Visual Studio 2005 or in Visual Studio .NET, point to New on the File menu, and
then click File.
2. Select the Text File type, and then click Open.
3. Add the following DTD declarations to the file to describe the grammar of the XML
document:
XML
<!ELEMENT Product (ProductName)>
<!ATTLIST Product ProductID CDATA #REQUIRED>
<!ELEMENT ProductName (#PCDATA)>
4. Save the file as Product.dtd in the same folder as your XML document.
5. Reopen Product.xml in Visual Studio 2005
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE Product SYSTEM "Product.dtd">
1. In Visual Studio 2005 or in Visual Studio .NET, point to New on the File menu, and
then click File.
2. Select the Text File type, and then click Open.
3. Add the following XDR schema definitions to the file to describe the grammar of the
XML document:
<?xml version="1.0"?>
<Schema name="ProductSchema"
xmlns="urn:schemas-microsoft-com:xml-data"
xmlns:dt="urn:schemas-microsoft-com:datatypes">
<AttributeType name="ProductID" dt:type="int"/>
<ElementType name="ProductName" dt:type="string"/>
<ElementType name="Product" content="eltOnly">
<attribute type="ProductID" required="yes"/>
<element type="ProductName"/>
</ElementType>
</Schema>
4. Save the file as Product.xdr in the same folder as your XML document.
5. Reopen the original Product.xml, and then link it to the XDR schema, as follows:
<?xml version="1.0" encoding="utf-8" ?>
<Product ProductID="123" xmlns="x-schema:Product.xdr">
<ProductName>Rugby jersey</ProductName>
</Product>
6. Save the modified XML document as ProductWithXDR.xml
1. In Visual Studio .NET, point to New on the File menu, and then click File.
2. Select the Text File type, and then click Open.
3. Add the following XSD schema definition to the file to describe the grammar of the
XML document:
<?xml version="1.0"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="Product">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="ProductName" type="xsd:string"/>
</xsd:sequence>
<xsd:attribute name="ProductID" use="required" type="xsd:int"/>
</xsd:complexType>
</xsd:element>
</xsd:schema>
4. Save the file as Product.xsd in the same folder as your XML document.
5. Reopen the original Product.xml, and then link it to the XSD schema, as follows:
<?xml version="1.0" encoding="utf-8" ?>
<Product ProductID="123"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="Product.xsd">
<ProductName>Rugby jersey</ProductName>
</Product>
6. Save the modified XML document as ProductWithXSD.xml.
Output:
<?xml version="1.0"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="Product">
<xsd:complexType>
<xsd:sequence>
</xsd:sequence>
<xsd:attribute name="ProductID" use="required" type="xsd:int"/>
</xsd:complexType>
</xsd:element>
75
</xsd:schema>
<Product ProductID="123"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="Product.xsd">
<ProductName>Rugby jersey</ProductName>
</Product>
Result:
Thus, the creation of an XML database and validated it using XML schema has been
done successfully.
Ex.No.:11
NOSQL
Date:
Aim:
To create document, column and graph based data using NOSQL database tools.
Description:
NoSQL databases are all quite different from SQL databases. They use a data model
that has a different structure than the traditional row-and-column table model used with
relational database management systems (RDBMS).
1. Document databases
2. Key-value stores
3. Column-oriented databases
4. Graph databases
Document Databases:
A document database stores data in JSON, BSON, or XML documents (not Word
documents or Google Docs, of course). In a document database, documents can be nested.
Particular elements can be indexed for faster querying.
Documents can be stored and retrieved in a form that is much closer to the data
objects used in applications, which means less translation is required to use the data in an
application. SQL data must often be assembled and disassembled when moving back and
forth between applications and storage.
Use cases include ecommerce platforms, trading platforms, and mobile app
development across industries.
Key-value stores
The simplest type of NoSQL database is a key-value store. Every data element in the
database is stored as a key value pair consisting of an attribute name (or "key") and a value.
In a sense, a key-value store is like a relational database with only two columns: the key or
attribute name (such as "state") and the value (such as "Alaska").
Use cases include shopping carts, user preferences, and user profiles.
Column-oriented databases:
While a relational database stores data in rows and reads data row by row, a column
store is organized as a set of columns. This means that when you want to run analytics on a
small number of columns, you can read those columns directly without consuming memory
with the unwanted data. Columns are often of the same type and benefit from more efficient
compression, making reads even faster. Columnar databases can quickly aggregate the value
of a given column (adding up the total sales for the year, for example). Use cases include
analytics.
Unfortunately, there is no free lunch, which means that while columnar databases are
great for analytics, the way in which they write data makes it very difficult for them to be
strongly consistent as writes of all the columns require multiple write events on disk.
Relational databases don't suffer from this problem as row data is written contiguously to
disk.
Graph databases:
A graph database focuses on the relationship between data elements. Each element is
stored as a node (such as a person in a social media graph). The connections between
elements are called links or relationships. In a graph database, connections are first-class
elements of the database, stored directly. In relational databases, links are implied, using
data to express the relationships.
A graph database is optimized to capture and search the connections between data
elements, overcoming the overhead associated with JOINing multiple tables in SQL.
Very few real-world business systems can survive solely on graph queries. As a result
graph databases are usually run alongside other more traditional databases.
Use cases include fraud detection, social networks, and knowledge graphs.
Create Database:
>use javatpointdb
Swithched to db javatpointdb
>db
>show dbs
Insert a document:
>db.movie.insert({"name":"javatpoint"})
db.javatpoint.insert(
{
course: "java",
details: {
},
Drop Database:
> db.dropDatabase()
Create collection :
>db.SSSIT.insert({"name" : "seomount"})
>show collections
SSSIT
db.collection_name.find()
Neo4j CQL
Create nodes:
Open the localhost on the browser: http://localhost:7474/browser/ and use the following
code:
CREATE (single);
Result:
Thus, NOSQL database tools has been used and executed successfully.
Ex.No.:12
GUI based database application-Payroll processing System
Date:
Aim:
Description:
This says about the Payroll Processing System and gives the details of an employee in
an organization. The task of this system is to view the details of the particular employee,
adding of new employee to the database and calculates the net pay of each employee.
Microsoft Visual Basic is used as front end and the Oracle as the back end. The visual basic
and the oracle are connected using the component controls such as Microsoft ADO Data
Control 6.0 and Microsoft DataGrid control.
Database Design:
Coding:
LOGIN FORM:
Form2.Show
Form1.Hide
Else
MsgBox ("Invalid")
End If
End Sub
End
End Sub
Text3.Text = Time
Text4.Text = Date
End Sub
Form2.Hide
Form4.Show
End Sub
Form2.Hide
Form3.Show
End Sub
Form2.Hide
Form5.Show
End Sub
Private Sub Command4_Click()
Form2.Hide
Form1.Show
End Sub
End
End Sub
guideconn1.Open
Set query1 = guideconn1.Execute("insert into emps12 values('" & (Text1.Text) & "','" &
(Text2.Text) & "','" & (Text3.Text) & "','" & (Text4.Text) & "','" & (Text5.Text) & "','" &
(Text6.Text) & "','" & (Text7.Text) & "','" & (Text8.Text) & "')")
guideconn1.Close
End Sub
End Sub
Form3.Hide
Form4.Show
End Sub
Form3.Hide
Form1.Show
End Sub
End
End Sub
Form4.Hide
Form1.Show
End Sub
End
End Sub
Private Sub Command3_Click()
Form4.Hide
Form3.Show
End Sub
Adodc1.CommandType = adCmdText
Adodc1.Refresh
DataGrid1.Refresh
End Sub
Form4.Hide
Form5.Show
End Sub
End Sub
End Sub
Form1.Show
End Sub
Form5.Hide
Form4.Show
End Sub
End
End Sub
Form5.Hide
Form2.Show
End Sub
Adodc1.CommandType = adCmdText
Adodc1.Refresh
DataGrid1.Refresh
End Sub
Screenshots:
Result:
Thus, a GUI based database application has been created and executed successfully
for payroll processing system.
Ex.No.:13
Case Study-EMart Grocery Shop
Date:
Aim:
To create a database for Emart Grocery shop and apply all sql properties.
Sample Code:
Thus, the EMart grocery shop application has been created and executed successfully.
CONTENT BEYOND SYLLABUS
DATABASE DESIGN USING ER MODELING, NORMALIZATION AND
IMPLEMENTATION FOR LIBRARY MANAGEMENT SYSTEM
AIM:
DESCRIPTION:
Case study
Current system:
All the Transaction (books issues & books returned) are manually recorded (registers.)
Students search books by racks it so time consuming
Backgroud of Project
The system was designed to help librain record every book transcation so that the
problem such as file missing will not happened again.
Design view
NORAMALIZATION OF TABLE
Why Normalization:
Database normalization is the process of removing redundant data from your tables in
order to improve storage efficiency, data integrity, and scalability.
Normalization generally involves splitting existing tables into multiple ones, which
must be re-joined or linked each time a query is issued.
In the ISSUE Table there is repeating book_id . A student has issued 3 books.
In the following Student relation all attributes are dependent on the primary key StudID
We can create two other relations from Student Table one is Department fields are
fully dependent on the primary keys DEp_id
DEp_id Dep_name
11 CS & IT Department
22 Education Department
33 Economics Department
44 Laaw Department
House no12
300-
1101 Shaid M Librarian street 6 Sargodha punjab
1234567
Statilete 0346-
1345 Riaz m Data entery town Sargodha Punjab
1234567
Raza 0333-
2264 Arshad m Naib qaisd garden Sargodha Punjab
1234567
Staff table
Staff conatact
Student table
Studentcontact table:
Student_id Address City State Phone
Student table:
Normalization End
Design view
Records
Record
Record view
authorname
RETURN STUDENT
PK PK student_id
return _id
book_id student_name
issue-date
student_dep
issue_id
student contact
PK std_id
streeet
DEPARTMENT
PK dep_no
dep_name
ER Model
Result:
Thus the database design using ER modeling, normalization and implementation for
library management application was successfully designed and output was verified.