cp4152 Database Practices Lab
cp4152 Database Practices Lab
Create table using data definition language ,create alter, drop, enforce a
foreign key ,primary key ,check, not null constraints and creating views
Procedure:
Mysql>Create table passenger2(passportId Integer Primary
Key,Name varchar(10) NotNull,Age Integer Not Null,Sex
char,Address varchar(20) Not Null);
Mysql> desc
passenger2;
Adding Extra
column to
Existing
Table
Mysql>Alter table passenger3 add column TicketNo varchar(10);
CHECK Constraint
It is used to restrict the value of a column between a range. It performs check on the
values, before storing them into the database. Its like condition checking before saving
data into a column.
The UNIQUE constraint in SQL is used to ensure that no duplicate values will be
inserted into a specific column or combination of columns that are participating in the
UNIQUE constraint and not part of the PRIMARY KEY
USE SQLShackDemo
GO
CREATE TABLE ConstraintDemo1
(
ID INT NOT NULL,
Name VARCHAR(50) NULL
RESULT
Create alter, drop, enforce a foreign key ,primary key ,check, not null constraints
and creating views was successfully created.
Ex.no:2
Create table using Data manipulation language, insert, delete, update.
AIM: Create a DML Commands are used to manage data within the scheme objects.
Procedure:
values(1234,'Hyderabad','Tirupathi');
values(2345,'Hyderabad','Banglore');
values(23,'Hyderabad','Kolkata');
values(45,'Tirupathi','Banglore');Query
values(34,'Hyderabad','Chennai');
sec)
mysql> select * from Bus2;
values(145,'Ramesh',45,'M','abc123');Query
values(278,'Geetha',36,'F','abc124');
values(4590,'Ram',30,'M','abc12');Query
values(6789,'Ravi',50,'M','abc14');Query
values(5622,'Seetha',32,'F','abc55');Query
Aim: Create cartesian product, equi join, left outer join, right outer join, full outer join
Procedure:
CARTESIAN JOIN
The CARTESIAN JOIN or CROSS JOIN returns the Cartesian product of the sets of
records from two or more joined tables. Thus, it equates to an inner join where the join-
condition always evaluates to either True or where the join-condition is absent from the
statement.
+ + + +
|OID | DATE | CUSTOMER_ID | AMOUNT |
+ + + +- +
| 102 | 2009-10-08 00:00:00 | 3 | 3000 |
| 100 | 2009-10-08 00:00:00 | 3 | 1500 |
| 101 | 2009-11-20 00:00:00 | 2 | 1560 |
| 103 | 2008-05-20 00:00:00 | 4 | 2060 |
+ + + +- +
let us join these two tables using CARTESIAN JOIN
SQL> SELECT ID, NAME, AMOUNT, DATE
FROM CUSTOMERS, ORDERS;
Equi join
The left outer join returns a resultset table with the matched data from the two tables and
then the remaining rows of the left table and null from the right table's columns.
ON table-name1.column-name = table-name2.column-name;
ID NAME ID
1 abhi 1
2 adam 2
3 alex 3
4 anu null
5 ashish null
ID Address
1 DELHI
2 MUMBAI
3 CHENNAI
7 NOIDA
8 PANIPAT
Output
ID NAME ID Address
1 abhi 1 DELHI
2 adam 2 MUMBAI
3 alex 3 CHENNAI
The right outer join returns a result set table with the matched data from the two
tables being joined, then the remaining rows of the right table and null for the
remaining left table's columns.
ON table-name1.column-name = table-name2.column-name;
ID NAME ID Address
1 abhi 1 DELHI
2 adam 2 MUMBAI
3 alex 3 CHENNAI
The full outer join returns a resultset table with the matched data of two table then
remaining rows of both left table and then the right table.
ON table-name1.column-name = table-name2.column-name;
SELECT * FROM class FULL OUTER JOIN class_info ON (class.id = class_info.id);
ID NAME ID Address
1 abhi 1 DELHI
2 adam 2 MUMBAI
3 alex 3 CHENNAI
4 anu null null
5 ashish null null
null null 7 NOIDA
null null 8 PANIPAT
RESULT
Cartesian product, equi join, left outer join, right outer join, full outer join was
successfully created.
Ex.no:4
Set aggregate functions, set operation and nested queries
Aim : Create using aggregate functions, set operation and nested queries
Procedure:
COUNT FUNCTION
o COUNT function is used to Count the number of rows in a database table. It can
work on both numeric and non-numeric data types.
o COUNT function uses the COUNT(*) that returns the count of all the rows in a
specified table. COUNT(*) considers duplicate and Null.
o COUNT(*)
o or
o COUNT( [ALL|DISTINCT] expression )
Table name: Product mast
PRODUCT COMPANY QTY RATE COST
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
1. SELECT COUNT(*)
2. FROM PRODUCT_MAST;
Output: 5
2. SUM Function
Sum function is used to calculate the sum of all selected columns. It works on numeric
fields only.
1. SUM()
2. or
3. SUM( [ALL|DISTINCT] expression )
1. SELECT SUM(COST)
2. FROM
PRODUCT_MAST; 3. 670
4. 670
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
Output:540
3. AVG function
The AVG function is used to calculate the average value of the numeric type. AVG
function returns the average of all non-Null values
1. AVG()
2. or
3. AVG( [ALL|DISTINCT] expression )
SELECT AVG(COST)
FROM PRODUCT_MAST;
Output:67.00
4. MAX Function
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.
1. MAX()
2. or
3. MAX( [ALL|DISTINCT] expression )
1. SELECT MAX(RATE)
2. FROM PRODUCT_MAST;
Output:30
5. MIN Function
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.
Syntax
1. MIN()
2. or
3. MIN( [ALL|DISTINCT] expression )
Example:
1. SELECT MIN(RATE)
2. FROM PRODUCT_MAST;
Output:10
Set operation
The SQL Set operation is used to combine the two or more SQL SELECT statements.
1. Union
2. UnionAll
3. Intersect
4. Minus
1. Union
o The SQL Union operation is used to combine the result of two or more SQL
SELECT queries.
o In the union operation, all the number of datatype and columns must be same in
both the tables on which UNION operation is being applied.
o The union operation eliminates the duplicate rows from its result set.
Syntax
ID NAME
1 Jack
2 Harry
3 Jackson
Second table:
ID NAME
3 Jackson
4 Stephan
5 David
1. SELECT * FROM First
2. UNION
3. SELECT * FROM Second;
ID NAME
1 Jack
2 Harry
3 Jackson
4 Stephan
5 David
2. Union All
Union All operation is equal to the Union operation. It returns the set without removing
duplication and sorting the data.
Syntax:
1 Jack
2 Harry
3 Jackson
3 Jackson
4 Stephan
5 David
3. Intersect
o It is used to combine two SELECT statements. The Intersect operation returns the
common rows from both the SELECT statements.
o In the Intersect operation, the number of datatype and columns must be the same.
o It has no duplicates and it arranges the data in ascending order by default.
Syntax
Example:
3 Jackson
4. Minus
o It combines the result of two SELECT statements. Minus operator is used to
display the rows which are present in the first query but absent in the second
query.
o It has no duplicates and data arranged in ascending order by default.
Syntax:
1. SELECT column_name FROM table1
2. MINUS
3. SELECT column_name FROM table2;
Example
1 Jack
2 Harry
Nested queries
A nested query in SQL contains a query inside another query. The result of the inner query will
be used by the outer query. For instance, a nested query can have two SELECT statements, one
on the inner query and the other on the outer query.
The SELECT query inside the brackets (()) is the inner query, and the SELECT query outside
the brackets is the outer query. The result of the inner query is used by the outer query.
RESULT:
Aggregate functions, set operation and nested queries was successfully created.
Ex No:5
Aim: Create transaction control language commit, roll back, save points
Procedure:
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 we want the changes to be saved permanently to the disk without closing the session,
we will use the commit command.
1. COMMIT;
mysql> USE school;
Public School
3 Delhi 1200 30 10 [email protected]
m
Public School
4 Ashoka 1110 40 40 [email protected]
Universal
School
5 Calibers 9000 31 50 [email protected]
English Medium
School
1. mysql> COMMIT;
2. SAVEPOINT
We can divide the database operations into parts. For example, we can consider all the insert
related queries that we will execute consecutively as one part of the transaction and the delete
command as the other part of the transaction. Using the SAVEPOINT command in SQL, we can
save these different parts of the same transaction using different names. For example, we can
save all the insert related queries with the savepoint named INS. To save all the insert related
queries in one savepoint, we have to execute the SAVEPOINT query followed by the savepoint
name after finishing the insert command execution.
1. SAVEPOINT savepoint_name;
3. ROLLBACK
While carrying a transaction, we must create savepoints to save different parts of the transaction.
According to the user's changing requirements, he/she can roll back the transaction to different
savepoints. Consider a scenario: We have initiated a transaction followed by the table creation
and record insertion into the table. After inserting records, we have created a savepoint INS.
Then we executed a delete query, but later we thought that mistakenly we had removed the
useful record. Therefore in such situations, we have an option of rolling back our transaction. In
this case, we have to roll back our transaction using the ROLLBACK command to the savepoint
INS, which we have created before executing the DELETE query.
1. ROLLBACK TO savepoint_name;
2. mysql> ROLLBACK TO Insertion;
3. mysql> SELECT *FROM t_school;
RESULT:
Transaction control language commit, roll back, save points was successfully
done.
Ex no :6
Row level and statement level triggers
Statement level triggers and other is row level trigger. The Statement level trigger will be fired
for every transaction not for every row. It will fire whenever the trigger event occurs on the
specified table. It will not check how many rows are impacting with statement level trigger.
Procedure:
Syntax :
Begin
SQL statements;
END;
output
2 rows updated
1. The row level trigger will always used for each row statement. If the for each
row statement is there then that trigger is called as row level trigger.
2. It will fire once for each row affected by triggering event. It will not fire
for transaction.
3. It will not fire if triggering event is not impacting the rows.
on Employee
for each row
begin
DBMS_OUTPUT.PUT_LINE(‘Row Level trigger executed’);
end;
The above statement will create a row level trigger.
output
0 rows updated
RESULT:
Row level and statement level triggers successfully created
Ex no :7
Procedure:
XML
An XML document is a basic unit of XML information composed of elements and other markup
in an orderly package. An XML document can contains wide variety of data. For example,
database of numbers, numbers representing molecular structure or a mathematical equation.
<?xml version = "1.0"?>
<contact-info>
<name>Tanmay Patil</name>
<company>aws</company>
<phone>(011) 123-4567</phone>
</contact-info>
RESULT:
XML documents,document type definition and XML Schema successfully created
Ex no :8
Relational database to store the XML documents as a text and data elements
Aim : Implementing Relational database to store the XML documents as a text and data
elements
Procedure:
Add necessary triggers and other meta information Insert XML document Side tables get
automatically
StorageType conversion
XMLVarCharFromFile(),.. Retrieval: Cast Functions
Varchar(XMLVarChar) Update
Cast functions or storage UDFs
Update(xmlobj, path,value) Selection using XPATH
WHERE Extractvarchar(order, ‘/order/Customer’) LIKE “%IBM%’
Or, use side tables
to store data from an XML file into SQL database with 2 tables. The XML file looks like this
(the full file has more Document nodes):
<Documents>
<Document>
<Number>110</Number>
<Date>2020-10-23</Date>
<TotalPrice>3800</TotalPrice>
<Items>
<Item>
<SKU>001234</SKU>
<Name>FirstItem</Name>
<Quantity>10</Quantity>
<Price>1550</Price>
</Item>
<Item>
<SKU>001235</SKU>
<Name>SecondItem</Name>
<Quantity>8</Quantity>
<Price>1200</Price>
</Item>
<Item>
<SKU>001236</SKU>
<Name>ThirdItem</Name>
<Quantity>21</Quantity>
<Price>1050</Price>
</Item>
</Items>
</Document>
</Documents>
The SQL database has 2 tables. One for Documents, and the other one for Items.
create table Document(
DocumentId int identity(1,1) not null primary key,
Number int not null,
[Date] date not null,
TotalPrice money not null
);
[XmlElement("Date")]
public DateTime Date { get; set; }
[XmlElement("TotalPrice")]
public int TotalPrice { get; set; }
}
[MetadataType(typeof(DocumentMetadata))]
public partial class Document
{
}
XDocument xDoc = XDocument.Load(XmlFile);
List<Document> documentList = xDoc.Descendants("Document").Select(document => new
Document
{
Number = Convert.ToInt32(document.Element("Number").Value),
Date = Convert.ToDateTime(document.Element("Date").Value),
TotalPrice = Convert.ToInt32(document.Element("TotalPrice").Value),
}).ToList();
if (dbDoc != null)
{
dbDoc.Number = doc.Number;
dbDoc.Date = doc.Date;
dbDoc.TotalPrice = doc.TotalPrice;
}
else
{
entity.Documents.Add(doc);
}
}
entity.SaveChanges();
Selecting/Extracting XMLType
Instance Extract()
Obtains the node/nodes from the document identified by the XPath (subset of) expression
Use getStringVal() or getNumberVal() to get scalar content Select
p.poDoc.extract(‘/PO/PONO/text()’).getnumberval() From po_xml_tab p; ExistsNode()
Checks if the given XPath evaluates in at least a single XML element or text node
Useful for filtering as well as for functional indexes Select
e.poDoc.extract(‘//PONO/text()’).getNumberVal() as pono From po_xml_tab e
Where e.podoc.existsnode(‘/Po/PONO’) = 1 and poid > 1
Functions to convert from XMLType to other type
RESULT:
Relational database to store the XML documents as a text and data elements was created
Ex no :9
XML querying
Procedure
In the XMLQUERY function, a default namespace is first specified. This namespace matches the
namespace of the documents previously inserted. The for clause specifies iteration through the
<customerinfo> elements in each document from the Info column. The INFO column is
specified by using the passing clause, which binds the INFO column to the variable
named doc that is referenced in the for clause. The return clause then constructs an <out>
element, which contains the <name> element from each iteration of the for clause.
The WHERE clause uses the XMLEXISTS predicate to consider only a subset of the documents
in the Info column. This filtering yields only those documents that have a <city> element (along
the path specified) with a value of Toronto.
To pass a value to the SQL fullselect in the db2-fn:sqlquery function, run the following
query:
VALUES XMLQUERY (
'declare default element namespace "http://posample.org";
for $d in db2-fn:sqlquery(
''SELECT INFO FROM CUSTOMER WHERE Cid = parameter(1)'',
$testval)/customerinfo
return <out>{$d/name}</out>'
passing 1000 as "testval" )~
The XMLQUERY function passes the value 1000 to the XQuery expression by using the
identifier testval. The XQuery expression then passes the value to the db2-fn:sqlquery function
by using the PARAMETER scalar function.
<out xmlns="http://posample.org">
<name>Kathy Smith</name>
</out>
Querying in an XQuery context
DB2® XQuery offers two built-in functions specifically for use with DB2 databases: db2-
fn:sqlquery and db2-fn:xmlcolumn. db2-fn:sqlquery retrieves a sequence that is the result table
of an SQL fullselect. db2-fn:xmlcolumn retrieves a sequence from an XML column.
If your query invokes an XQuery expression directly, you must prefix it with the case-insensitive
keyword XQUERY.
This query is equivalent to the SQL query SELECT Info FROM Customer.
Using db2-fn:sqlquery
To retrieve all XML documents in the INFO column, run the following query:
XQUERY db2-fn:sqlquery ('SELECT Info FROM Customer')~
You do not have to specify the INFO and CUSTOMER names in uppercase because the
SELECT statement is processed in an SQL context and is therefore not case sensitive.
The db2-fn:xmlcolumn function retrieves a sequence from the INFO column of the
CUSTOMER table. The for clause binds the variable $d to each <customerinfo>
element in the CUSTOMER.INFO column. The where clause restricts the items to only
those that have a <city> element (along the path specified) with a value of Toronto.
The return clause constructs the returned XML value. This value is an element <out>
that contains the <name> element for all documents that satisfy the condition specified
in the where clause, as follows:
<out xmlns="http://posample.org">
<name>
Kathy Smith
</name>
</out>
Using db2-fn:sqlquery
To issue a fullselect within an XQuery expression, run the following query:
RESULT:
Implementing database using XML querying was successfully done
Ex no :10
MongoDB use DATABASE_NAME is used to create database. The command will create a new
database if it doesn't exist, otherwise it will return the existing database.
Syntax
Basic syntax of use DATABASE statement is as follows −
use DATABASE_NAME
Example
If you want to use a database with name <mydb>, then use DATABASE statement would be as
follows −
>use mydb
switched to db mydb
To check your currently selected database, use the command db
>db
mydb
f you want to check your databases list, use the command show dbs.
>show dbs
local 0.78125GB
test 0.23012GB
Your created database (mydb) is not present in list. To display database, you need to insert at
least one document into it.
>db.movie.insert({"name":"tutorials point"})
>show dbs
local 0.78125GB
mydb
0.23012GB
The dropDatabase() Method
MongoDB db.dropDatabase() command is used to drop a existing database.
Syntax
Basic syntax of dropDatabase() command is as follows −
db.dropDatabase()
This will delete the selected database. If you have not selected any database, then it will delete
default 'test' database.
Example
First, check the list of available databases by using the command, show dbs.
>show dbs
local 0.78125GB
mydb
0.23012GB
test 0.23012GB
if you want to delete new database <mydb>, then dropDatabase() command would be as
follows −
>use mydb
switched to db mydb
>db.dropDatabase()
>{ "dropped" : "mydb", "ok" : 1 }
>
Now check list of databases.
>show dbs
local
0.78125GB
test 0.23012GB
Traditional DB
In a traditional relational database management system (RDBMS), you have a table for users and
a table for updates. A foreign key represents the one-to-many relationship between users and
updates. Getting a user's updates is as simple as making a SQL query like "SELECT * FROM
updates WHERE updates.user_id = users.user_id". The problem with a traditional RDBMS is
that scaling becomes more difficult as you exceed the capabilities of the single machine.
Simple secondary index that stores a list of element ids
index: user_id => [update_id]
updates: update_id => update_data
Secondary index paged by month
index: user_id, month => [update_id]
updates: update_id => update_data VStack underlying Voldemort stores
stack: user_id, page_id => update_id, next_page, previous_page
updates: update_id => update_data
// iterating over a VStack
VStack<Integer, String> myUpdates =
new VStack<Integer, String>(1337 /* example userid */,
storeClient /* Voldemort StoreClient */);
for (String update : myUpdates) {
System.out.println(update);
}
This operation uses a filter predicate of {}, which corresponds to the following SQL statement:
The following example selects from the inventor collection all documents where
the statu equals "D":
This operation uses a filter predicate of { status: "D" }, which corresponds to the following SQL
statement:
The following example retrieves all documents from the inventory collection
where statu equals either "A" or "D":
db.inventory.insertMany([
{ item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm" }, status: "A" },
{ item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "A" },
{ item: "paper", qty: 100, size: { h: 8.5, w: 11, uom: "in" }, status: "D" },
{ item: "planner", qty: 75, size: { h: 22.85, w: 30, uom: "cm" }, status: "D" },
{ item: "postcard", qty: 45, size: { h: 10, w: 15.25, uom: "cm" }, status: "A" }
]);
Specify Conditions Using Query Operators
A query filter document can use the query operators to specify conditions in the following form:
The following example retrieves all documents from the inventory collection
where statu equals either "A" or "D":
The operation uses a filter predicate of { status: { $in: [ "A", "D" ] } }, which corresponds to the
following SQL statement:
Refer to the Query and Projection Operators document for the complete list of MongoDB query
operators.
A compound query can specify conditions for more than one field in the collection's documents.
Implicitly, a logical AN conjunction connects the clauses of a compound query so that the
query selects the documents in the collection that match all the conditions.
The following example retrieves all documents in the inventory collection where
The operation uses a filter predicate of { status: "A", qty: { $lt: 30 } }, which corresponds to the
following SQL statement:
Using
operator, you can specify a compound query that joins each clause with a
the
OR conjunction so that the query selects the documents in the collection that match at
logical
least one condition.
The operation uses a filter predicate of { $or: [ { status: 'A' }, { qty: { $lt: 30 } } ] }, which
corresponds to the following SQL statement:
RESULT:
Creation of database using Mongo DB, Dynamo DB, Voldemort Key-Value Distributed Data
store Hbase and Neo4j was successfully done
Ex no :11
Implementing access control in relational database
Aim:
Implementing access control in relational database
Procedure
A relational database stores data in relations which are expected to satisfy some simple
mathematical properties.
The columns of the table are called attributes and the rows are called tuples. There is no
signicance to the order of the columns or rows. Duplicate rows with identical values for all
columns are not allowed.
There is an important distinction between relation schemes and relation instances. The relation
scheme gives us the names of the attributes as well as the permissible values for each attribute.
The set of permissible values for an attribute is said to be the attribute's domain. The relation
instance gives us the tuples of the relation at a given instant.
Let the domain of the NAME, DEPT, RANK, OFFICE, and SUPERVISOR attributes be
character strings, and the domain of the SALARY attribute be integers.
A particular instance of the EMPLOYEE relation,
NAME DEPT RANK OFFICE SALARY SUPERVISOR Rao Electrical Engg Professor KH252
50,000 Jones Kaplan Computer Sci Researcher ST125 35,000 Brown Brown Computer Sci
Professor ST257 55,000 Black Jones Electrical Engg Chairman KH143 45,000 Black Black
Administration Dean ST101 60,000 NULL
The CREATE Statement Consider the EMPLOYEE relation discussed earlier. The relation
scheme is dened in SQL by the following command.
INSERT and DELETE Statements The EMPLOYEE table is initially empty. Tuples are inserted
into it by means of the SQL INSERT statement. For example, the last tuple of the relation
instance discussed above is inserted by the following statement.
The remaining tuples can be similarly inserted. Insertion of the tuples for Brown and Jones must
respectively precede insertion of the tuples for Kaplan and Rao, so as to maintain referential
integrity. Alternately, these tuples can be inserted in any order with NULL managers which are
later updated to their actual values. There is a DELETE statement to delete tuples from a
relation.
. For example, the NAME, SALARY and SUPERVISOR data for employees in the Computer
Sci department is extracted as follows
SELECT NAME, SALARY, SUPERVISOR FROM EMPLOYEE WHERE DEPT =
`Computer Sci'
The WHERE clause in a SELECT statement is optional. SQL also allows the retrieved records to
be grouped together for statistical computations by means of built-in statistical functions. For
example, the following query gives the average salary for employees in each department.
The UPDATE Statement Finally the UPDATE statement allows one or more attributes
of existing tuples in a relation to be modified.
For example, the following statement gives all employees in the ComputerSci department a raise
of $1000.
Sci' This statement selects those tuples in EMPLOYEE which have the value of Computer Sci
for the DEPT attribute.
It then increases the value of the SALARY attribute for all these tuples by $1000 each.
The GRANT Statement The owner of a relation can grant one or more access privileges to
another user. This can be done with or without the GRANT OPTION. If the owner grants, say,
SELECT with the GRANT OPTION the user receiving this grant can further grant SELECT to
other users.
The latter GRANT can be done in turn with or without the GRANT OPTION at the granting
user's discretion. The general format of a grant operation in SQL is as follows.
RESULT:
Implementing access control in relational database was successfully done