Professional Documents
Culture Documents
DBMS Record
DBMS Record
: 1 BASIC SQL
Suppose you are given a relation grade points(grade, points), which provides a conversion
from letter grades in the takes relation to numeric scores; for example an A grade could be
specified to correspond to 4 points, an A to 3.7 points, a B+ to 3.3 points, a B to 3 points, and
so on. The grade points earned by a student for a course offering (section) is defined as the number of
credits for the course multiplied by the numeric points for the grade that the student received. Given
the above relation, and our university schema, write each of the following queries in SQL. You can
assume for simplicity that no takes tuple has the null value for grade.
a. Find the total grade-points earned by the student with ID 12345, across all courses taken
by the student.
b. Find the grade-point average (GPA) for the above student, that is, the total grade-points
divided by the total credits for the associated courses.
Aim
To create a student database and write sql queries for different operations using basic SQL
command.
Theory
SQL
SQL SELECT
Program/Procedure :
Database Creation:
use University;
Table Creation:
GradeP :
CourseD :
Values Insertion:
GradeP Table:
Answer:
a. Find the total number of people who owned cars that were involved in accidents in
2009.
b. Add a new accident to the database; assume any values for required attributes.
Aim
To create university database and write sql queries for different operations using basic SQL
command.
Theory
SQL
SQL SELECT
The COUNT() function returns the number of rows that matches a specified criteria.
Syntax -
The MIN() function returns the smallest value of the selected column.
Syntax
Syntax
Syntax
Program/Procedure
Database Creation:
use InsurDB;
Table Creation:
Person:
Car:
Acc:
Owns:
Participated:
Values Insertion:
Person Table :
Car Table :
Acc Table:
Owns Table:
delete from Car where Model='Mazda' and license in (select License from Owns where Driver_ID
in(select Driver_ID from Person where Name='John Smith'));
Result
Insurance database created and successfully executed and query results obtained.
Database Question
The SHROY computer service center is owned by the SPARK computer dealer; the
SHROY services only SPARK computers. Five SHROY computer service center provide services
and assembles for the entire state. Each center is independently managed by a shop manager; a
receptionist and at least ten service engineers. Each center also maintains about, the history of
services made, parts used, costs, service dates, owner etc. Also there is a need to keep track about
inventory, purchasing, billing, employees hours and payroll.
CREATING SEQUENCE
Write a query that will automatically produce customer id and invoice number as
sequence in customer and billing relations respectively.
Aim:
To create an Employee database and execute SQL queries to achieve the desired results.
Theory
SQL
SQL is a standard language for accessing and manipulating databases.
SQL stands for Structured Query Language
SQL lets you access and manipulate databases
SQL is an ANSI (American National Standards Institute) standard
SQL can execute queries against a database
SQL can retrieve data from a database
SQL can insert records in a database
SQL can update records in a database
SQL SELECT
The PRIMARY KEY constraint uniquely identifies each record in a database table.
Primary keys must contain UNIQUE values, and cannot contain NULL values.
A table can have only one primary key, which may consist of single or multiple fields.
Database Creation:
use shroy_db;
Table Creation:
Center:
Employee:
Customer:
Inventory :
Services:
Purchase :
Billing:
Values Insertion:
Center Table:
Employee Table:
Inventory Table:
Services Table:
Purchase Table :
Answer:
insert into Billing (Cu_id, Pname,Pid, Paid_amt, Service_Chrg, Cus_Bal) values ('Cu20', 'Pandu',
'P000',2000, 100, 2100);
Result:
Database Question
The SHROY computer service center is owned by the SPARK computer dealer; the
SHROY services only SPARK computers. Five SHROY computer service center provide services
and assembles for the entire state. Each center is independently managed by a shop manager; a
receptionist and at least ten service engineers. Each center also maintains about, the history of
services made, parts used, costs, service dates, owner etc. Also there is a need to keep track about
inventory, purchasing, billing, employees hours and payroll.
Creating Sequence
To create a table for center relation which should automatically fix the value for an
attribute no_of_emp as some default value (say 20) in all the tuples.
Aim:
To create an Employee database and execute SQL queries to achieve the desired results.
Theory
SQL
SQL is a standard language for accessing and manipulating databases.
SQL SELECT
The PRIMARY KEY constraint uniquely identifies each record in a database table.
Primary keys must contain UNIQUE values, and cannot contain NULL values.
A table can have only one primary key, which may consist of single or multiple fields.
Program/Procedure:
Database Creation:
use shroy_db;
Table Creation:
Center:
Employee:
Customer:
Inventory :
Services:
Purchase :
Billing:
Center Table:
Employee Table:
Inventory Table:
Services Table:
Answer :
Result:
1. List all products, with barcode and name, and the sale id and quantity for the sales
containing that product, if any (products that were never sold should still be listed in your result)
Hint: use a left join
2. Create a view called AllProductsSales based on the query in the Q.No.1.
3. Write a query against the AllProductsSales view as if it was a table:
select everything from the AllProductsSales, ordered
by BarCode and SaleID.
5. Write a query on the ProductProfit view to show the top 5 products based on total profit
on order of highest profit to lowest profit.
Aim:
To create an Online Store Database and execute SQL queries to achieve the desired results.
Theory
SQL VIEWS
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
You can add SQL functions, WHERE, and JOIN statements to a view and present the data as if the
data were coming from one single table.
CREATE VIEW
Syntax
Syntax
Syntax
DDL
Data Definition Language (DDL) statements are used to define the database structure or schema.
Some examples:
TRUNCATE - remove all records from a table, including all spaces allocated for the records are
removed.
DML
Data Manipulation Language (DML) statements are used for managing data within schema
objects. Some examples:
DCL
TCL
Transaction Control (TCL) statements are used to manage the changes made by DML statements.
It allows statements to be grouped together into logical transactions.
SAVEPOINT - identify a point in a transaction to which you can later roll back
SET TRANSACTION - Change transaction options like isolation level and what rollback
segment to use.
Program/Procedure
Database Creation
use online_store;
Table Creation:
Product :
create table customer (cid int ,primary key(cid),phone varchar(20),email varchar(50), fname
varchar(50), lname varchar(50));
Sale :
Saleitem :
create table saleitem (sid int, barcode int,quantity int,foreign key(sid) references sale(sid), foreign
key(barcode) references product(barcode));
Values Insertion:
Product Table :
Sale Table :
Aim:
To create an Online Store Database and execute SQL queries to achieve the desired results.
Theory:
Triggers
Triggers are stored programs, which are automatically executed or fired when some events occur.
Triggers are, in fact, written to be executed in response to any of the following events
Triggers can be defined on the table, view, schema, or database with which the event is associated.
Program/Procedure :
Table Creation:
Product :
create table product(barcode int, primary key(barcode), pname varchar(50),price float,
quantityInStock int);
Customer :
create table customer (cid int ,primary key(cid),phone varchar(20),email varchar(50), fname
varchar(50), lname varchar(50));
Sale :
create table sale(sidd int, primary key(sidd), deliveryAddress varchar(50), credit_card varchar(50),
cid int, foreign key(cid) references customer(cid));
Saleitem :
create table saleitem (sidd int, barcode int,quantity int,foreign key(sid) references sale(sidd),
foreign key(barcode) references product(barcode));
Product Table :
Customer Table :
Answer :
Begin
update product
set quantityInStock=product.quantityInStock-NEW.quantity
where product.barcode=New.barcode;
end;
Date: 17.02.17
Aim:
To draw the ER diagram for the company databse.
Theory:
A relationship is how the data is shared between entities. There are three types of relationships
between entities:
1. One-to-One
One instance of an entity (A) is associated with one other instance of another entity (B). For
example, in a database of employees, each employee name (A) is associated with only one social
security number (B).
2. One-to-Many
One instance of an entity (A) is associated with zero, one or many instances of another entity (B),
but for one instance of entity B there is only one instance of entity A. For example, for a company
Answer :
Result:
Date: 10.03.17
Question: Reduce the following to BCNF, showing all the steps involved.
Identify any repeating groups and functional dependences in the PATIENT relation.
Show all the intermediate steps to derive the third normal form for PATIENT.
PATIENT(Patno,Patname,Gpno,Gpname,Appdate,Consultant,Conaddr,Sample)
Supplier(sno,sname,saddress,(partno, partdesc,(custid,custname,custaddr,quantity)))
sno -> sname,saddr
partno -> partdesc
sno,partno,custid -> quantity
sname -> sno
custid -> custname,custaddr
Suppliers supply many parts to many customers. Each customer deals with only one supplier.
Supplier names are unique. Customer names are not unique.
Aim
To perform normalization on the given database table.
Theory
1NF:
An attribute (column) of a table cannot hold multiple values. It should hold only atomic
values.
2NF:
A table is said to be in 2NF if both the following conditions hold.
Table is 1NF
No non-prime attribute is dependent on the proper subset of any candidate key of table.
Procedure:
1) Functional Dependencies
a) Patno -> Patname,Gpno,Gpname,Adddate,Consultant,Conaddr,Sample
b) Patname -> Patno,Gpno,Gpname,Adddate,Consultant,Conaddr,Sample
c) Gpno -> Patname,Patno,Gpname,Adddate,Consultant,Conaddr,Sample
d) Gpname -> Patname,Gpno,Patno,Adddate,Consultant,Conaddr,Sample
e) Appdate->Consultant,Consaddr
f) Consultant->Appdate,Conaddr
g) Conaddr->Appdate,Consultant
In the above F.D a,b,c,d are in 2 NF,as the keys in LHS are not part of any key
In the above F.D e,f,g there are no attributes which are part of any key.
So.it is in 2NF
3>For 3NF-If it satisfies 2 NF & there is no transitive dependency.
A FD X->Y in a relation schema R is a transitive dependency if there exists a set of attributes Z in
R that is neither a candidate key nor a subset of any key of R & both X->Y &Z->Y hold.
Therefore we can say that either the LHS should be Superkey or RHS should be prime attribute
In F.D a,b,c,d ,LHS is a key, so that they are in 3NF.But on the other hand in e,f,g LHS is not a
key ,hence they are not in 3NF& there is transitive dependency also.
Appdate->Consultant,Consaddr
Consultant->Consaddr
Consaddr->Appdate
We need to decompose tables-
Table 1:
(Pat no.,Patname,Gpno,Gpname,Appdate,sample)
Answer
1) For making given relation in 3NF we need to decompose into:
RELATION1 (Pat no.,Patname,Gpno,Gpname,Appdate,sample)
RELATION2(Appdate,Consultant,consaddr)
Therefore ,table have been formed in 3 NF successfully.
Aim
To develop a web application using PHP and MySQL for Restaurant managent system.
Theroy
PHP is a server-side scripting language designed primarily for web development but also
used as a general-purpose programming language. Originally created by Rasmus Lerdorf in
1994,the PHP reference implementation is now produced by The PHP Development Team.[5]
PHP originally stood for Personal Home Page, but it now stands for the recursive acronym PHP:
Hypertext Preprocessor.
PHP code may be embedded into HTML or HTML5 markup, or it can be used in
combination with various web template systems, web content management systems and web
frameworks. PHP code is usually processed by a PHP interpreter implemented as a module in the
web server or as a Common Gateway Interface (CGI) executable. The web server software
combines the results of the interpreted and executed PHP code, which may be any type of data,
including images, with the generated web page. PHP code may also be executed with a command-
line interface (CLI) and can be used to implement standalone graphical applications.
The standard PHP interpreter, powered by the Zend Engine, is free software released under
the PHP License. PHP has been widely ported and can be deployed on most web servers on almost
every operating system and platform, free of charge.
The PHP language evolved without a written formal specification or standard until 2014,
leaving the canonical PHP interpreter as a de facto standard. Since 2014 work has gone on to
create a formal PHP specification.
PHP stores integers in a platform-dependent range, either a 64-bit or 32-bit signed integer
equivalent to the C-language long type. Unsigned integers are converted to signed values in certain
situations; this behavior is different from that of other programming languages.Integer variables
can be assigned using decimal (positive and negative), octal, hexadecimal, and binary notations.
Floating point numbers are also stored in a platform-specific range. They can be specified
using floating point notation, or two forms of scientific notation.PHP has a native Boolean type
that is similar to the native Boolean types in Java and C++. Using the Boolean type conversion
rules, non-zero values are interpreted as true and zero as false, as in Perl and C++.
The null data type represents a variable that has no value; NULL is the only allowed value for this
data type.
Variables of the "resource" type represent references to resources from external sources. These are
typically created by functions from a particular extension, and can only be processed by functions
from the same extension; examples include file, image, and database resources.
Program:
Home.php :
<?php require_once 'db_connection.php';
if(isset($_SESSION['email']))
redirectTo('food.php');
?>
<html>
<head>
<title>NITPY Restaurant:Home</title>
<link href="stylesheets/user_styles.css" rel="stylesheet" type="text/css">
<body> <div id="page"> <div id="header">
<div id="company_name">NITPY Restaurant</div>
Home Page
Food Page
MyAccount.php
<?php session_start(); ?>
<html><head>
Logout.php
<?php
require_once('db_connection.php');
$_SESSION[] = array();
if(isset($_COOKIE['admin'])) {
setcookie('admin',"",time()-2000,"/");
}
session_destroy();
redirectTo('Home.php?done');
?>
Register.php
<?php
require_once 'db_connection.php';
if(isset($_POST['Submit']))
{
$conn=OpenCon();
$Fname=$_POST['fname'];
$Lname=$_POST['lname'];
$Email=$_POST['email'];
$Password=$_POST['password'];
$Cpassword=$_POST['cpassword'];
//if(!$_POST['Submit']) {
$qur = mysqli_query($conn,"INSERT INTO `user`(`FName`,`LName`,
`Email`, `Pswd`) VALUES ('$Fname','$Lname','$Email','$Cpassword')");
Registration Page
Result:
Developed restaurant management system successfully and output verified.
Aim
This practical intends to explain the basic concept of big data techniques and also
implementation of mapper and reducer program.
Software Required
Theory
Big Data is the application of specialized techniques and technologies to process very
large sets of data. These data sets are often so large and complex that it becomes difficult to
process using on-hand database management tools. Examples include web logs, call records,
medical records, military surveillance, photography archives, video archives and large-scale e-
commerce.
Hadoop System: Bring the power of Apache Hadoop to the enterprise with
application accelerators, analytics, visualization, development tools, performance
and security features.
Performing computation on large volumes of data has been done before, usually in a
distributed setting. What makes Hadoop unique is its simplified programming model which allows
the user to quickly write and test distributed systems, and its efficient, automatic distribution of
data and work across machines and in turn utilizing the underlying parallelism of the CPU cores.
Data Distribution
In a Hadoop cluster, data is distributed to all the nodes of the cluster as it is being loaded
in. The Hadoop Distributed File System (HDFS) will split large data files into chunks which are
managed by different nodes in the cluster. In addition to this each chunk is replicated across
several machines, so that a single machine failure does not result in any data being unavailable. An
active monitoring system then re-replicates the data in response to system failures which can result
in Participatedial storage. Even though the file chunks are replicated and distributed across several
machines, they form a single namespace, so their contents are universally accessible.
MapReduce
Hadoop limits the amount of communication which can be performed by the processes, as
each individual record is processed by a task in isolation from one another. While this sounds like
a major limitation at first, it makes the whole framework much more reliable. Hadoop will not run
just any program and distribute it across a cluster. Programs must be written to conform to a
Particular programming model, named "MapReduce". In MapReduce, records are processed in
isolation by tasks called Mappers. The output from the Mappers is then brought together into a
second set of tasks called Reducers, where results different mappers can be merged. Separate
nodes in a Hadoop cluster still communicate with one another. However, in contrast to more
conventional distributed systems where application developers explicitly marshal byte streams
from node to node over sockets or through MPI buffers, communication in Hadoop is performed
implicitly. Pieces of data can be tagged with key names which inform Hadoop how to send related
bits of information to a common destination node. Hadoop internally manages all of the data
transfer and cluster topology issues.
Flat Scalability
One of the major benefits of using Hadoop in contrast to other distributed systems is its flat
scalability curve. Executing Hadoop on a limited amount of data on a small number of nodes may
not demonstrate Particularly stellar performance as the overhead involved in starting Hadoop
programs is relatively high. Other parallel/distributed programming paradigms such as MPI
(Message Passing Interface) may perform much better on two, four, or perhaps a dozen machines.
A program written in distributed frameworks other than Hadoop may require large amounts of
refactoring when scaling from ten to one hundred or one thousand machines.
Procedure/ Program
Mapper:
Mapper maps input key/value pairs to a set of intermediate key/value pairs.
The Hadoop Map/Reduce framework spawns one map task for each InputSplit
generated by the InputFormat for the job.
Reducer:
Reducer reduces a set of intermediate values which share a key to a smaller set of
values.
The number of reduces for the job is set by the user via
JobConf.setNumReduceTasks(int). Overall, Reducer implementations are passed
the JobConf for the job via the JobConfigurable.configure(JobConf) method and
can override it to initialize themselves.
Apache Hadoop
The core of Apache Hadoop consists of a storage Part (Hadoop Distributed File System
(HDFS)) and a processing Part (MapReduce). Hadoop splits files into large blocks and distributes
them amongst the nodes in the cluster. To process the data, Hadoop MapReduce transfers
packaged code for nodes to process in parallel, based on the data each node needs to process. This
approach takes advantage of data locality - nodes manipulating the data that they have on handto
allow the data to be processed faster and more efficiently than it would be in a more conventional
supercomputer architecture that relies on a parallel file system where computation and data are
connected via high-speed networking.
Hadoop Common contains libraries and utilities needed by other Hadoop modules.
The term "Hadoop" has come to refer not just to the base modules above, but also to the
"ecosystem" or collection of additional software packages that can be installed on top of or
alongside Hadoop, such as Apache Pig, Apache Hive, Apache HBase, Apache Spark, and others.
The Hadoop framework itself is mostly written in the Java programming language, with
some native code in C and command line utilities written as Shell script. For end-users, though
MapReduce Java code is common, any programming language can be used with "Hadoop
Streaming" to implement the "map" and "reduce" Parts of the user's program.
Sample Program
Hadoop Environment:
1. The hadoop name node information runs on /localhost:50070. To start the hadoop
environment, run start-dfs.sh and start-yarn.sh.
2. Add files to the hadoop file system using
Hadoop dfs -CopyToLocal </hadoop_directory> </OS_directory>
This is the Hadoop Distributed File System running. This is an example for word count.
Keerthi Vasan Gounder.
import java.io.IOException;
import java.util.StringTokenizer;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.*;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.GenericOptionsParser;
public class WordCount {
public static class Map
extends Mapper<LongWritable, Text, Text, IntWritable>{
private final static IntWritable one = new IntWritable(1); // type of output value
private Text word = new Text(); // type of output key
public void map(LongWritable key, Text value, Context context
) throws IOException, InterruptedException {
StringTokenizer itr = new StringTokenizer(value.toString()); // line to string
while (itr.hasMoreTokens()) {
word.set(itr.nextToken()); // set word as each input keyword
context.write(word, one); }}}
public static class Reduce
extends Reducer<Text,IntWritable,Text,IntWritable> {
private IntWritable result = new IntWritable();
public void reduce(Text key, Iterable<IntWritable> values,
Context context ) throws IOException, InterruptedException {
int sum = 0; // initialize the sum for each keyword
Result:
Thus we have studied the different big data techniques and their implementation using
hadoop 2.6.0