Dbms Lab Manual
Dbms Lab Manual
Department of
Information Technology
Lab Manual
414459: Software
Laboratory - I
SL-I Laboratory Manual (17-18) Department of Information Technology
ASSIGNMENT NO.1
TITLE: Study and design a database with suitable example using following database systems:
Relational: SQL / PostgreSQL / MySQL
Key-value: Riak / Redis
Columnar: Hbase
Document: MongoDB / CouchDB
Graph: Neo4J
Compare the different database systems based on points like efficiency,
scalability, characteristics and performance.
OBJECTIVE:
1. To understand the different type of databases.
2. To understand the difference between the different database systems
considering efficiency, scalability etc.
THEORY:
Relational
MySQL: MySQL, the most popular Open Source SQL database management system, is
developed, distributed, and supported by Oracle Corporation.
A database is a structured collection of data. It may be anything from a simple shopping list to
a picture gallery or the vast amounts of information in a corporate network. To add, access, and
process data stored in a computer database, you need a database management system such as
MySQL Server. Since computers are very good at handling large amounts of data, database
management systems play a central role in computing, as standalone utilities, or as parts of
other applications.
A relational database stores data in separate tables rather than putting all the data in one big
storeroom. The database structures are organized into physical files optimized for speed. The
logical model, with objects such as databases, tables, views, rows, and columns, offers a
flexible programming environment
Open Source means that it is possible for anyone to use and modify the software. Anybody can
download the MySQL software from the Internet and use it without paying anything. If you
wish, you may study the source code and change it to suit your needs. The MySQL software
uses the GPL (GNU General Public License).
The MySQL Database Server is very fast, reliable, scalable, and easy to use.
If that is what you are looking for, you should give it a try. MySQL Server can run comfortably
on a desktop or laptop, alongside your other applications, web servers, and so
On, requiring little or no attention. If you dedicate an entire machine to MySQL, you can adjust
the settings to take advantage of all the memory, CPU power, and I/O capacity available.
MySQL can also scale up to clusters of machines, networked together.
MySQL Commands:
Create a database on the sql server.
mysql> create database [databasename];
Switch to a database.
mysql> use [db name];
To delete a db.
mysql> drop database [database name];
To delete a table.
mysql> drop table [table name];
Key-value:
Riak: Riak is a distributed NoSQL key-value data store that offers high availability, fault
tolerance, operational simplicity, and scalability.[4] In addition to the open-source version, it
comes in a supported enterprise version and a cloud storage version.
Riak KV :With a key/value design that delivers powerful – yet simple – data models for
storing massive amounts of unstructured data, Riak KV is built to handle a variety of
challenges facing Big Data applications that include tracking user or session information,
storing connected device data and replicating data across the globe.
Riak KV automates data distribution across the cluster to achieve fast performance and robust
business continuity with a masterless architecture that ensures high availability, and scales near
linearly using commodity hardware so you can easily add capacity without a large operational
burden.
Riak TS is the only enterprise-grade NoSQL time series database optimized specifically for
IoT and Time Series data. It ingests, transforms, stores, and analyzes massive amounts of time
series data.
Features:
Fault-tolerant availability:
Riak replicates key/value stores across a cluster of nodes with a default n_val of three.
In the case of node outages due to network partition or hardware failures, data can still
be written to a neighboring node beyond the initial three, and read-back due to its
"masterless" peer-to-peer architecture.
Queries:
Riak provides a REST-ful API through HTTP and Protocol Buffers for basic PUT,
GET, POST, and DELETE functions. More complex queries are also possible,
including secondary indexes, search (via Apache Solr), and MapReduce. MapReduce
has native support for both JavaScript (using the SpiderMonkey runtime) and Erlang.
Predictable latency:
Riak distributes data across nodes with hashing and can provide latency profile, even in
the case of multiple node failures.
Storage options:
Keys/values can be stored in memory, disk, or both.
Multi-datacenter replication
In multi-datacenter replication, one cluster acts as a "primary cluster." The primary
cluster handles replication requests from one or more "secondary clusters" (generally
located in other regions or countries). If the datacenter with the primary cluster goes
down, a second cluster can take over as the primary cluster.
Tunable consistency
Option to choose between eventual and strong consistency for each bucket.
Redis:
Redis is an open source, advanced key-value store and an apt solution for building high-
performance, scalable web applications.
Redis holds its database entirely in the memory, using the disk only for persistence.
Redis has a relatively rich set of data types when compared to many key-value data
stores.
Redis Advantages
Following are certain advantages of Redis.
Exceptionally fast − Redis is very fast and can perform about 110000 SETs per
second, about 81000 GETs per second.
Supports rich data types − Redis natively supports most of the datatypes that
developers already know such as list, set, sorted set, and hashes. This makes it easy to
solve a variety of problems as we know which problem can be handled better by which
data type.
Operations are atomic − All Redis operations are atomic, which ensures that if two
clients concurrently access, Redis server will receive the updated value.
Multi-utility tool − Redis is a multi-utility tool and can be used in a number of use
cases such as caching, messaging-queues (Redis natively supports Publish/Subscribe),
any short-lived data in your application, such as web application sessions, web page hit
counts, etc.
Columnar:
Hbase: HBase is a distributed column-oriented database built on top of the Hadoop file
system. It is an open-source project and is horizontally scalable.HBase is a data model that is
similar to Google‟s big table designed to provide quick random access to huge amounts of
structured data. It leverages the fault tolerance provided by the Hadoop File System (HDFS).It
is a part of the Hadoop ecosystem that provides random real-time read/write access to data in
the Hadoop File System.
HBase is a column-oriented database and the tables in it are sorted by row. The table schema
defines only column families, which are the key value pairs. A table have multiple column
families and each column family can have any number of columns. Subsequent column values
are stored contiguously on the disk. Each cell value of the table has a timestamp. In short, in an
HBase:
col1 col2 col3 col1 col2 col3 col1 col2 col3 col1 col2 col3
Features of HBase
Applications of HBase
Document:
MONGODB:
Database
Database is a physical container for collections. Each database gets its own set of files on the
file system. A single MongoDB server typically has multiple databases.
Collection
Document
A document is a set of key-value pairs. Documents have dynamic schema. Dynamic schema
means that documents in the same collection do not need to have the same set of fields or
structure, and common fields in a collection's documents may hold different types of data.
Below given table shows the relationship of RDBMS terminology with MongoDB
RDBMS MongoDB
Database Database
Table Collection
Tuple/Row Document
Column Field
Table Join Embedded Documents
Primary Key (Default key _id provided by
Primary Key
mongodb itself)
Database Server and Client
Mysqld/Oracle Mongod
mysql/sqlplus Mongo
Sample document
Below given example shows the document structure of a blog site which is simply a comma
separated key value pair.
{
_id: ObjectId(7df78ad8902c)
title: 'MongoDB Overview',
description: 'MongoDB is no sql database',
by: 'tutorials point',
url: 'http://www.tutorialspoint.com',
tags: ['mongodb', 'database', 'NoSQL'],
likes: 100,
comments: [
{
user:'user1',
message: 'My first comment',
dateCreated: new Date(2011,1,20,2,15),
like: 0
},
{
user:'user2',
message: 'My second comments',
dateCreated: new Date(2011,1,25,7,45),
like: 5
}
]
}
_id is a 12 bytes hexadecimal number which assures the uniqueness of every document. You
can provide _id while inserting the document. If you didn't provide then MongoDB provide a
unique id for every document. These 12 bytes first 4 bytes for the current timestamp, next 3
bytes for machine id, next 2 bytes for process id of mongodb server and remaining 3 bytes are
simple incremental value.
Any relational database has a typical schema design that shows number of tables and the
relationship between these tables. While in MongoDB there is no concept of relationship
Schema less : MongoDB is document database in which one collection holds different
different documents. Number of fields, content and size of the document can be differ
from one document to another.
Structure of a single object is clear
No complex joins
Deep query-ability. MongoDB supports dynamic queries on documents using a
document-based query language that's nearly as powerful as SQL
Tuning
Ease of scale-out: MongoDB is easy to scale
Conversion / mapping of application objects to database objects not needed
Uses internal memory for storing the (windowed) working set, enabling faster access of
data
Document Oriented Storage : Data is stored in the form of JSON style documents
Index on any attribute
Replication & High Availability
Auto-Sharding
Rich Queries
Fast In-Place Updates
Professional Support By MongoDB
Big Data
Content Management and Delivery
Mobile and Social Infrastructure
User Data Management
Data Hub
COUCH DB:
Graph database is a database used to model the data in the form of graph. In here, the nodes of
a graph depict the entities while the relationships depict the association of these nodes.
Relational databases store highly structured data which have several records storing the same
type of data so they can be used to store structured data and, they do not store the relationships
between the data.
Unlike other databases, graph databases store relationships and connections as first-class
entities.
The data model for graph databases is simpler compared to other databases and, they can be
used with OLTP systems. They provide features like transactional integrity and operational
availability.
High availability − Neo4j is highly available for large enterprise real-time applications
with transactional guarantees.
Connected and semi structures data − Using Neo4j, you can easily represent
connected and semi-structured data.
Easy retrieval − Using Neo4j, you can not only represent but also easily retrieve
(traverse/navigate) connected data faster when compared to other databases.
Features of Neo4j
Data model (flexible schema) − Neo4j follows a data model named native property
graph model. Here, the graph contains nodes (entities) and these nodes are connected
with each other (depicted by relationships). Nodes and relationships store data in key-
value pairs known as properties.
In Neo4j, there is no need to follow a fixed schema. You can add or remove properties
as per requirement. It also provides schema constraints.
ACID properties − Neo4j supports full ACID (Atomicity, Consistency, Isolation, and
Durability) rules.
Scalability and reliability − You can scale the database by increasing the number of
reads/writes, and the volume without effecting the query processing speed and data
integrity. Neo4j also provides support for replication for data safety and reliability.
Built-in web application − Neo4j provides a built-in Neo4j Browser web application.
Using this, you can create and query your graph data.
o REST API to work with programming languages such as Java, Spring, Scala
etc.
o It supports two kinds of Java API: Cypher API and Native Java API to develop
Java applications. In addition to these, you can also work with other databases
such as MongoDB, Cassandra, etc.
B batch
1. Explain the use of MongoDB.
2. What is RDBMS?
3. Explain different data models with example.
4. Compare Neo4j Vs RDBMS
C batch
1. Name the subsystems of RDBMS.
2. How do you communicate with a RDBMS?
3. What is a database transaction?
4. Compare MongoDB VS CouchDB?
D batch
1. What are the advantages of DBMS over traditional file system?
2. Explain the differences between structured data and unstructured data.
3. What are the major functions of database administrator?
4. Compare HBASE Vs RDBMS?
ASSIGNMENT NO.2
TITLE: Install and configure client and server for MySQL and MongoDB (Show all
commands and
necessary steps for installation and configuration).
OBJECTIVE:
1. To understand the Installation and configuration of database in client-server
architecture.
Theory:
Steps in installation of MySQL Server and Configuration of Client
[Note:
1. I have implemented all following steps on Fedora 19 x86_64 machine.
2. All steps to be implemented as ‘root’ login.
3. Internet connection is must.
4. Update your machine using command ‘yum update’.]
> exit
5. Restart MySQL service.
# systemctl stop mysqld.service
# systemctl start mysqld.service
On Client:
1. Locate „my.cnf‟ file.
# locate my.cnf
(It results in „/etc/my.cnf‟.)
2. Add following line below „[mysqld]‟ line using editor.
bind-address = 10.5.2.47
(Comment „skip-networking‟ if exists. i.e., „#skip-networking‟.)
3. Restart MySQL service.
# systemctl stop mysqld.service
# systemctl start mysqld.service
(This step may give you an error message. Ignore it.)
4. Log in to the remote server.
# mysql –h 10.5.2.47 –u user001 –p user001_db
Password:
(Enter password.)
Installing MongoDB
Installing MongoDB is a simple process on most platforms. Precompiled binaries are
available for Linux, Mac OS X, Windows, and Solaris. This means that, on most platforms,
you can download the archive from http://www.mongodb.org, inflate it, and run
the binary. The MongoDB server requires a directory it can write database files to and
a port it can listen for connections on. This section covers the entire install on the two
variants of system: Windows and everything else (Linux, Max, Solaris).
When we speak of “installing MongoDB,” generally what we are talking about is setting
up mongod, the core database server. mongod is used in a single-server setup as either
master or slave, as a member of a replica sets, and as a shard.
Stepwise Installation
1) You must create a directory for the database to put its files. By default, the database
will use /data/db, although you can specify any other directory.
You can create the directory and set the permissions by running the following:
$ mkdir -p /data/db
$ chown -R $USER:$USER /data/db
mkdir -p creates the directory and all its parents, if necessary (i.e., if the /data directory
didn‟t exist, it will create the /data directory and then the /data/db directory). chown
changes the ownership of /data/db so that your user can write to it.
2)Decompress the .tar.gz file you downloaded from http://www.mongodb.org.
$ tar zxf mongodb-linux-i686-1.6.0.tar.gz
$ cd mongodb-linux-i686-1.6.0
3)Now you can start the database:
$ bin/mongod
Or if you‟d like to use an alternate database path, specify it with the --dbpath option:
$ bin/mongod --dbpath ~/db
Conclusion: We have studied how to install and configure mysql and mongodb on fedora 20
International Institute of Information Technology, Hinjawadi, Pune. Page 13
SL-I Laboratory Manual (17-18) Department of Information Technology
ASSIGNMENT NO.3
TITLE: Study the SQLite database and its uses. Also elaborate on building and installing of
SQLite.
OBJECTIVE:
1. To understand the SQLite Database and Their Installation on Fedora 20.
Theory:
SQLite:
SQLite is an in-process library that implements a self-contained, serverless, zero-configuration,
transactional SQL database engine. It is a database, which is zero-configured, which means like
other databases you do not need to configure it in your system.
SQLite engine is not a standalone process like other databases, you can link it statically or
dynamically as per your requirement with your application. SQLite accesses its storage files
directly.
Features:
SQLite does not require a separate server process or system to operate (serverless).
SQLite is very small and light weight, less than 400KiB fully configured or less than
250KiB with optional features omitted.
SQLite transactions are fully ACID-compliant, allowing safe access from multiple
processes or threads.
SQLite supports most of the query language features found in SQL92 (SQL2) standard.
SQLite is available on UNIX (Linux, Mac OS-X, Android, iOS) and Windows (Win32,
WinCE, WinRT).
2011 - Hipp announced to add UNQl interface to SQLite DB and to develop UNQLite
(Document oriented database).
SQLite is often used as the on-disk file format for desktop applications such as version
control systems, financial analysis tools, media cataloging and editing suites, CAD
packages, record keeping programs, and so forth. There are many benefits to this
approach, including improved application performance, reduced cost and complexity,
and improved reliability..
Websites
SQLite works great as the database engine for most low to medium traffic websites
(which is to say, most websites). The amount of web traffic that SQLite can handle
depends on how heavily the website uses its database. Generally speaking, any site that
gets fewer than 100K hits/day should work fine with SQLite. The 100K hits/day figure
is a conservative estimate, not a hard upper bound. SQLite has been demonstrated to
work with 10 times that amount of traffic.
Data analysis
People who understand SQL can employ the sqlite3 command-line shell (or various
third-party SQLite access programs) to analyze large datasets. Raw data can be
imported from CSV files, then that data can be sliced and diced to generate a myriad of
summary reports. More complex analysis can be done using simple scripts written in
Tcl or Python (both of which come with SQLite built-in) or in R or other languages
using readily available adaptors.
Server-side database
Systems designers report success using SQLite as a data store on server applications
running in the data center, or in other words, using SQLite as the underlying storage
engine for an application-specific database server.
International Institute of Information Technology, Hinjawadi, Pune. Page 15
SL-I Laboratory Manual (17-18) Department of Information Technology
File archives
The SQLite Archiver project shows how SQLite can be used as a substitute for ZIP
archives or Tarballs. An archive of files stored in SQLite is only very slightly larger,
and in some cases actually smaller, than the equivalent ZIP archive. And an SQLite
archive features incremental and atomic updating and the ability to store much richer
metadata.
Many programs use fopen(), fread(), and fwrite () to create and manage files of data in
home-grown formats. SQLite works particularly well as a replacement for these ad hoc
data files.
For programs that have a lot of data that must be sifted and sorted in diverse ways, it is
often easier and quicker to load the data into an in-memory SQLite database and use
queries with joins and ORDER BY clauses to extract the data in the form and order
needed rather than to try to code the same operations manually. Using an SQL database
internally in this way also gives the program greater flexibility since new columns and
indices can be added without having to recode every query.
Client applications typically use a generic database interface that allows connections to
various SQL database engines. It makes good sense to include SQLite in the mix of
supported databases and to statically link the SQLite engine in with the client. That way
the client program can be used standalone with an SQLite data file for testing or for
demonstrations.
Because it is simple to setup and use (installation is trivial: just copy the sqlite3 or
sqlite3.exe executable to the target machine and run it) SQLite makes a good database
engine for use in teaching SQL. Students can easily create as many databases as they
like and can email databases to the instructor for comments or grading. For more
advanced students who are interested in studying how an RDBMS is implemented, the
modular and well-commented and documented SQLite code can serve as a good basis.
The simple, modular design of SQLite makes it a good platform for prototyping new,
experimental database language features or ideas.
Installation on Fedora 20
root:~$ sudo dnf install sqlite
root:~$ sudo dnf install sqlite-devel sqlite-tcl sqlite-jdbc
SQLite Commands
The standard SQLite commands to interact with relational databases are similar to SQL. They
are CREATE, SELECT, INSERT, UPDATE, DELETE and DROP.
FAQ:
A batch
1) What is the difference between SQL and SQLite?
2) List out the standard SQLite commands?
3) How would you drop a table in SQLite database?
B batch
1) List out the advantages of SQLite?
2) How to insert data in a table in SQLite?
3) What is the use of UPADTE query in SQLIte?
C batch
1) Mention what are the SQLite storage classes?
2) How would you create a database in SQLite?
3) How can you delete the existing records from a table in SQLite?
D batch
1|)Mention what is the command used to create a database in SQLite?
2)How would you create a table in SQLite database?
3) What is the use of UPADTE query in SQLIte?
OBJECTIVE:
1. To understand the DDL commands and DCL commands.
THEORY:
DDL commands:
The DDL part of SQL permits database tables to be created or deleted. It also define
indexes (keys), specify links between tables, and impose constraints between tables.
Create Database:
You would need special privileges to create or to delete a MySQL database. So
assuming you have access to root user, you can create any database using
MySQL.
Example:
Here is a simple example to create database called TUTORIALS:
Example:
Here is an example to select database called TUTORIALS:
mysql> use TUTORIALS;
Database changed
mysql>
Now, you have selected TUTORIALS database and all the subsequent operations will
be performed on TUTORIALS database.
Creating Table/Relation:
1. The Create Table Command: - it defines each column of the table uniquely. Each
column has minimum of three attributes, a name , data type and size.
NOTE: MySQL does not terminate a command until you give a semicolon (;) at the
end of SQL command.
It is very easy to drop an existing MySQL table, but you need to be very careful while
deleting any existing table because data lost will not be recovered after deleting a
table.
Syntax:
Here is generic SQL syntax to drop a MySQL table:
DROP TABLE table_name ;
Dropping Tables from Command Prompt:
This needs just to execute DROP TABLE SQL command at mysql> prompt.
Example:
Here is an example, which deletes tutorials_tbl:
A DROP will not work if the column is the only one left in the table.
To add a column, use ADD and specify the column definition. The following
statement restores the icolumn to testalter_tbl:
After issuing this statement, testalter will contain the same two columns that it
had when you first created the table, but will not have quite the same structure.
That's because new columns are added to the end of the table by default. So
even though i originally was the first column in mytbl, now it is the last one.
To indicate that you want a column at a specific position within the table, either
use FIRST to make it the first column or AFTER col_name to indicate that the
new column should be placed after col_name. Try the following ALTER TABLE
statements, using SHOW COLUMNS after each one to see what effect each one
has:
The FIRST and AFTER specifiers work only with the ADD clause. This means
that if you want to reposition an existing column within a table, you first must
DROP it and then ADD it at the new position.
Renaming a Table:
To rename a table, use the RENAME option of the ALTER TABLE statement. Try
out the following example to rename testalter_tbl to alter_tbl.
DEFAULT Constraint:
The DEFAULT constraint provides a default value to a column when the INSERT
INTO statement does not provide a specific value. Example:
For example, the following SQL creates a new table called CUSTOMERS and adds
five columns. Here, SALARY column is set to 5000.00 by default, so in case
INSERT INTO statement does not provide a value for this column, then by default
this column would be set to 5000.00.
If CUSTOMERS table has already been created, then to add a DFAULT constraint to
SALARY column, you would write a statement similar to the following:
UNIQUE Constraint:
The UNIQUE Constraint prevents two records from having identical values in a
particular column.
For example, the following SQL creates a new table called CUSTOMERS and adds
five columns. Here, AGE column is set to UNIQUE, so that you can not have two
records with same age:
If CUSTOMERS table has already been created, then to add a UNIQUE constraint
to AGE column, you would write a statement similar to the following:
You can also use following syntax, which supports naming the constraint in
multiple columns as well:
If you are using MySQL, then you can use the following syntax:
PRIMARY Key:
A primary key is a field in a table which uniquely identifies each row/record in a
database table. Primary keys must contain unique values. A primary key column
cannot have NULL values.
A table can have only one primary key, which may consist of single or multiple
fields. When multiple fields are used as a primary key, they are called a composite
key.
If a table has a primary key defined on any field(s), then you cannot have two
records having the same value of that field(s).
To create a PRIMARY KEY constraint on the "ID" column when CUSTOMERS table
already exists, use the following SQL syntax:
NOTE: If you use the ALTER TABLE statement to add a primary key, the primary
key column(s) must already have been declared to not contain NULL values (when
the table was first created).
For defining a PRIMARY KEY constraint on multiple columns, use the following
SQL syntax:
To create a PRIMARY KEY constraint on the "ID" and "NAMES" columns when
CUSTOMERS table already exists, use the following SQL syntax:
FOREIGN Key:
A foreign key is a key used to link two tables together. This is sometimes called a
referencing key.
Foreign Key is a column or a combination of columns whose values match a
Primary Key in a different table.
The relationship between 2 tables matches the Primary Key in one of the
tables with a Foreign Key in the second table.
If a table has a primary key defined on any field(s), then you cannot have two
records having the same value of that field(s). Example:
CUSTOMERS table:
CREATE TABLE CUSTOMERS(
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);
ORDERS table:
If ORDERS table has already been created, and the foreign key has not yet been
set, use the syntax for specifying a foreign key by altering a table.
CHECK Constraint
The CHECK Constraint enables a condition to check the value being entered into
a
record. If the condition evaluates to false, the record violates the constraint and
isn't entered into the table.
Example:
For example, the following SQL creates a new table called CUSTOMERS and
adds five columns. Here, we add a CHECK with AGE column, so that you can
not have any CUSTOMER below 18 years:
If CUSTOMERS table has already been created, then to add a CHECK constraint
to
AGE column, you would write a statement similar to the following:
You can also use following syntax, which supports naming the constraint in
multiple columns as well:
The INDEX is used to create and retrieve data from the database very quickly.
Index can be created by using single or group of columns in a table. When index
is created, it is assigned a ROWID for each row before it sorts out the data.
Proper indexes are good for performance in large databases, but you need to be
careful while creating index. Selection of fields depends on what you are using in
your SQL queries.
Example:
For example, the following SQL creates a new table called CUSTOMERS and
adds five columns:
CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID));
Now, you can create index on single or multiple columns using the following
syntax:
System : creating session, table etc are all types of system privilege.
Object : any command or query to work on tables comes under object privilege.
GRANT privilege_name
ON object_name
TO {user_name |PUBLIC |role_name}
[WITH GRANT OPTION];
privilege_name is the access right or privilege granted to the user. Some of the access
rights are ALL, EXECUTE, and SELECT.
object_name is the name of an database object like TABLE, VIEW, STORED PROC
and SEQUENCE.
user_name is the name of the user to whom an access right is being granted.
user_name is the name of the user to whom an access right is being granted.
PUBLIC is used to grant access rights to all users.
ROLES are a set of privileges grouped together.
WITH GRANT OPTION - allows a user to grant access rights to other users.
The REVOKE command removes user access rights or privileges to the database objects.
REVOKE privilege_name
ON object_name
FROM {user_name |PUBLIC |role_name}
CONCLUSION: We have studied and implemented various DDL and DCL statements in
SQL.
FAQ: A batch
1. What are super, primary, foreign and candidate keys?
2. What is the difference between a primary key and a unique constraint?
3. What is DML compiler?
B batch
1. What is a query?
2. Explain different types of SQL statements.
3. What is the use of DCL command?
C batch
1. What is DCL?
2. Explain Different Notations of ER Diagram?
3. Explain the difference between delete, truncate and drop command.
D batch
1. Explain the Referential Integrity Constraint?.
2. What are the properties of a relational table?
3. What is on delete cascade?
ASSIGNMENT NO.2
TITLE: Design and implement a database and apply at least 10 different DML queries for the
following task. For a given input string display only those records which match the
given pattern or a phrase in the search string. Make use of wild characters and LIKE
operator for the same. Make use of Boolean and arithmetic operators wherever
necessary.
OBJECTIVE:
1. To understand the DML commands.
THEORY:
DML commands:
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 Insert,
Select, Update, Delete
Insert Command
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.
Select Commands
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.
Update Command
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.
Delete command
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.
The SQL SELECT statement returns a result set of records from one or
more tables. A SELECT statement retrieves zero or more rows from one or
more database tables or database views. In most applications, SELECT is the most commonly
used Data Manipulation Language (DML) command. As SQL is a declarative programming
language, SELECT queries specify a result set, but do
not specify how to calculate it. The database translates the query into a "query plan" which
may vary between executions, database versions and database software. This functionality is
called the "query optimizer" as it is responsible for
finding the best possible execution plan for the query, within applicable
constraints.
The SELECT statement has many optional clauses:
WHERE specifies which rows to retrieve.
GROUP BY groups rows sharing a property so that an aggregate
function can be applied to each group.
HAVING selects among the groups defined by the GROUP BY
clause.
ORDER BY specifies an order in which to return the rows.
AS provides an alias which can be used to temporarily rename
tables or columns.
WHERE Clause
We have seen SQL SELECT command to fetch data from MySQL table.
We can use a conditional clause called WHERE clause to filter out
results. Using WHERE clause, we can specify a selection criteria to select
required records from a table.
Syntax:
Here is generic SQL syntax of SELECT command with WHERE clause to
fetch data from MySQL table:
The WHERE clause is very useful when you want to fetch selected rows
from a table, especially when you use MySQL Join.
It is a common practice to search records using Primary Key to make
search fast.
If given condition does not match any record in the table, then query
would not return any row.
mysql>
mysql>
LIKE Clause
We have seen SQL SELECT command to fetch data from MySQL table. We
can also use a conditional clause called WHERE clause to select required
records.
A WHERE clause with equals sign (=) works fine where we want to do an
exact match. Like if "tutorial_author = 'Sanjay'". But there may be a
requirement where we want to filter out all the results where tutorial_author
name should contain "jay". This can be handled using SQL LIKE clause
along with WHERE clause.
If SQL LIKE clause is used along with % characters, then it will work like a
meta character (*) in UNIX while listing out all the files or directories at
command prompt.
Without a % character, LIKE clause is very similar to equals sign along with
WHERE clause.
Syntax:
Here is generic SQL syntax of SELECT command along with LIKE clause to
fetch data from MySQL table:
mysql>
To insert string data types, it is required to keep all the values into double or single
quote, for example:-"value".
Inserting Data from Command Prompt:
This will use SQL INSERT INTO command to insert data into MySQL table
tutorials_tbl.
Example:
Following example will create 3 records into tutorials_tbl table:
NOTE: Please note that all the arrow signs (->) are not part of SQL command; they are indicating a
new line and they are created automatically by MySQL prompt while pressing enter key without
giving a semicolon at the end of each line of the command.
In the above example, we have not provided tutorial_id because at the time of table creation, we
had given AUTO_INCREMENT option for this field. So MySQL takes care of inserting these IDs
automatically. Here, NOW() is a MySQL function, which returns current date and time.
UPDATE Query
There may be a requirement where existing data in a MySQL table needs to
be modified. You can do so by using SQL UPDATE command. This will
modify any field value of any MySQL table. Syntax:
Here is generic SQL syntax of UPDATE command to modify data into MySQL
table:
UPDATE table_name SET field1=new-value1, field2=new-value2
[WHERE Clause]
You can update one or more field altogether.
You can specify any condition using WHERE clause.
You can update values in a single table at a time.
The WHERE clause is very useful when you want to update selected rows in
a table.
Updating Data from Command Prompt:
This will use SQL UPDATE command with WHERE clause to update selected
data into MySQL table tutorials_tbl.
Example:
Following example will update tutorial_title field for a record having
tutorial_id as 3.
mysql>
DELETE Query
If you want to delete a record from any MySQL table, then you can use SQL
command DELETE FROM. You can use this command at mysql> prompt as
well as in any script like PHP.
Syntax:
Here is generic SQL syntax of DELETE command to delete data from a
MySQL table:
If WHERE clause is not specified, then all the records will be deleted
from the given MySQL table.
You can specify any condition using WHERE clause.
You can delete records in a single table at a time.
The WHERE clause is very useful when you want to delete selected rows in a
table.
Deleting Data from Command Prompt:
This will use SQL DELETE command with WHERE clause to delete selected
data into MySQL table tutorials_tbl.
Example:
Following example will delete a record into tutorial_tbl whose tutorial_id is 3.
CONCLUSION: We have studied and implemented various DML statements in SQL with
like clause and operators.
FAQ:
A batch
1. Write SQL Statement for awarding 5 bonus marks to all student following
schema are? Student_Branch (roll_no, student_name, branch, address, marks)
2. Which command allow us to add to our database file?
3. How many type of SQL Domain?
B batch
1. Can you tell name of commercial query language?
2. What is procedural and non-procedural DML?
3. Write example of delete query?
C batch
1. What is wild card characters?
2. Define various constraints.
3. Define aggregate and scalar functions.
D batch
1. What are Boolean opeartors?
2. Write example of update query.
3. How many types of relationships exist in database design?
ASSIGNMENT NO.3
TITLE: Execute the aggregate functions like count, sum, avg etc. on the suitable database.
Make use of built in functions according to the need of the database chosen.
Retrieve the data from the database based on time and date functions like now (),
date (), day (), time () etc.Use group by and having clauses.
OBJECTIVE:
1. To understand the aggregate, Date –time functions and group by, having clause.
THEORY:
Aggregate Functions:
COUNT Function
MySQL COUNT Function is the simplest function and very useful in counting the
number of records, which are expected to be returned by a SELECT statement.
To understand COUNT function, consider an employee_tbl table, which is
having the following records:
mysql> SELECT * FROM employee_tbl;
+------ +------ +------------ +-------------------- +
| id | name | work_date | daily_typing_pages |
+------ +------ +------------ +-------------------- +
| 1 | John | 2007-01-24 | 250 |
| 2 | Ram | 2007-05-27 | 220 |
| 3 | Jack | 2007-05-06 | 170 |
| 3 | Jack | 2007-04-06 | 100 |
220
| 4 | Jill | 2007-04-06 | |
| 5 | Zara | 2007-06-06 | 300 |
| 5 | Zara | 2007-02-06 | 350 |
+------ +------ +------------ +-------------------- +
Now, suppose based on the above table you want to count total number of rows
in this table, then you can do it as follows:
Similarly, if you want to count the number of records for Zara, then it can be
done as follows:
| COUNT(*)
International Institute of Information Technology, Hinjawadi, Pune. Page 38
SL-I Laboratory Manual (17-18) Department of Information
Technology
|
+
+----------
| 2|
+
+----------
MAX Function
MySQL MAX function is used to find out the record with maximum value
among a record set.
To understand MAX function, consider an employee_tbl table, which is having
the following records:
Now, suppose based on the above table you want to fetch maximum value of
daily_typing_pages, then you can do so simply using the following command:
|
MAX(daily_typing_pages)
|
+
+-------------------------
| 350 |
+
+-------------------------
You can find all the records with maximum value for each name using GROUP
BY clause as follows:
+------ +-------------------------
+------ +
5 rows in set (0.00 sec)
MIN Function
MySQL MIN function is used to find out the record with minimum value among
a record set.
To understand MIN function, consider an employee_tbl table, which is having
the following records:
Now, suppose based on the above table you want to fetch minimum value of
daily_typing_pages, then you can do so simply using the following command:
| MIN(daily_typing_pages)
|
+
+-------------------------
| 100 |
+
+-------------------------
You can find all the records with minimum value for each name using GROUP
BY clause as follows:
AVG Function
MySQL AVG function is used to find out the average of a field in various
records. To understand AVG function, consider an employee_tbl table, which
is having following records:
mysql> SELECT * FROM employee_tbl;
+------ +------+------------+-------------------- +
| id | name | work_date | daily_typing_pages |
+------ +------+------------+-------------------- +
| 1 | John | 2007-01-24 | 250 |
| 2 | Ram | 2007-05-27 | 220 |
International Institute of Information Technology, Hinjawadi, Pune. Page 40
SL-I Laboratory Manual (17-18) Department of Information
Technology
Now, suppose based on the above table you want to calculate average of all the
dialy_typing_pages, then you can do so by using the following command:
| AVG(daily_typing_pages) |
+
+-------------------------
| 230.0000 |
+
+-------------------------
You can take average of various records set using GROUP BY clause. Following
example will take average all the records related to a single person and you will
have average typed pages by every person.
SUM Function
MySQL SUM function is used to find out the sum of a field in various records.
To understand SUM function, consider an employee_tbl table, which is having
the following records:
Now, suppose based on the above table you want to calculate total of all the
dialy_typing_pages, then you can do so by using the following command:
| SUM(daily_typing_pages) |
+
+-------------------------
| 1610 |
+
+-------------------------
You can take sum of various records set using GROUP BY clause. Following
example will sum up all the records related to a single person and you will have
total typed pages by every person.
GROUP BY Clause
You can use GROUP BY to group values from a column, and, if you wish,
perform calculations on that column. You can use COUNT, SUM, AVG, etc.,
functions on the grouped column.
To understand GROUP BY clause, consider an employee_tbl table, which is
having the following records:
Now, suppose based on the above table we want to count number of days each
employee did work.
If we will write a SQL query as follows, then we will get the following result:
But this is not serving our purpose, we want to display total number of pages
typed by each person separately. This is done by using aggregate functions in
conjunction with a GROUP BY clause as follows:
| Jill | 1|
| John | 1|
| Ram | 1|
| Zara | 2|
+------ +---------- +
5 rows in set (0.04 sec)
We will see more functionality related to GROUP BY in other functions like SUM,
AVG, etc.
HAVING clause
The MySQL HAVING clause is used in the SELECT statement to specify filter
conditions for group of rows or aggregates.
The MySQL HAVING clause is often used with the GROUP BY clause. When using
with the GROUP BY clause, you can apply a filter condition to the columns that
appear in the GROUP BY clause. If the GROUP BY clause is omitted, the MySQL
HAVING clause behaves like the WHERE clause. Notice that the MySQL HAVING
clause applies the condition to each group of rows, while the WHERE clause
applies the condition to each individual row.
Examples of using MySQL HAVING clause
Let’s take a look at an example of using MySQL HAVING clause.
We will use the orderdetails table in the sample database for the sake of
demonstration.
We can use the MySQL GROUP BY clause to get order number, the number of
items sold per order and total sales for each:
SELECT ordernumber,
SUM(quantityOrdered) AS itemsCount,
SUM(priceeach) AS total
FROM orderdetails
GROUP BY ordernumber
Now, we can find which order has total sales greater than $1000. We use the
MySQL HAVING clause on the aggregate as follows:
SELECT ordernumber,
SUM(quantityOrdered) AS itemsCount,
SUM(priceeach) AS total
FROM orderdetails
GROUP BY ordernumber
HAVING total > 1000
We can construct a complex condition in the MySQL HAVING clause using logical
operators such as OR and AND. Suppose we want to find which order has total
sales greater than $1000 and contains more than 600 items, we can use the
following query:
SELECT ordernumber,
sum(quantityOrdered) AS
itemsCount, sum(priceeach) AS total
FROM orderdetails
GROUP BY ordernumber
HAVING total > 1000 AND itemsCount > 600
The MySQL HAVING clause is only useful when we use it with the GROUP BY
clause to generate the output of the high-level reports. For example, we can use the
MySQL HAVING clause to answer some kinds of queries like give me all the orders
in this month, this quarter and this year that have total sales greater than 10K.
Date-Time Functions
DATE(expr)
Extracts the date part of the date or datetime expression expr.
m ysql> SELECT DATE('2003-12-31 01:02:03');
+---------------------------------------------------------+
| DATE('2003-12-31 01:02:03') |
+---------------------------------------------------------+
| 2003-12-31 |
+---------------------------------------------------------+
DAY(date)
DAY() is a synonym for DAYOFMONTH().
NOW ()
Returns the current date and time as a value in 'YYYY-MM-DD HH:MM:SS' or
YYYYMMDDHHMMSS format, depending on whether the function is used in a string or
numeric context. The value is expressed in the current time zone.
TIME(expr)
Extracts the time part of the time or datetime expression expr and returns it as a string.
m ysql> SELECT TIME('2017-12-31 01:02:03');
+---------------------------------------------------------+
| TIME('2017-12-31 01:02:03') |
+---------------------------------------------------------+
| 01:02:03 |
+---------------------------------------------------------+
DAYOFMONTH(date)
Returns the day of the month for date, in the range 0 to 31.
m ysql> SELECT DAYOFMONTH('1998-02-03');
+---------------------------------------------------------+
| DAYOFMONTH('1998-02-03') |
+---------------------------------------------------------+
|3|
+---------------------------------------------------------+
1 row in set (0.00 sec)
CONCLUSION: We have studied Aggregate and Date Time Functions and Clauses.
ASSIGNMENT NO.4
TITLE:
Implement nested sub queries. Perform a test for set membership (in, not in), set
comparison (<some, >=some, <all etc.) and set cardinality (unique, not unique).
OBJECTIVE:
1. To understand concept of sub-queries
THEORY:
SUBQUERIES:
A Subquery or Inner query or Nested query is a query within another SQL query
and embedded within the WHERE 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. There are a few rules
that subqueries must follow:
Subqueries must be enclosed within parentheses.
A subquery can have only one column in the SELECT clause, unless multiple
columns are in the main query for the subquery to compare its selected columns.
An ORDER BY cannot be used in a subquery, although the main query can use an
ORDER BY. The GROUP BY can be used to perform the same function as the
ORDER BY in a subquery.
International Institute of Information Technology, Hinjawadi, Pune. Page 46
SL-I Laboratory Manual (17-18) Department of Information
Technology
Subqueries that return more than one row can only be used with multiple value
operators, such as the IN operator.
The SELECT list cannot include any references to values that evaluate to a BLOB,
ARRAY, CLOB, or NCLOB.
A subquery cannot be immediately enclosed in a set function.
The BETWEEN operator cannot be used with a subquery; however, the
BETWEEN operator can be used within the subquery.
Subqueries with the SELECT Statement:
Subqueries are most frequently used with the SELECT statement. The basic syntax is
as follows:
SELECT column_name [, column_name ]
FROM table1 [, table2 ]
WHERE column_name OPERATOR
(SELECT column_name [, column_name ]
FROM table1 [, table2 ]
[WHERE])
Subqueries with the INSERT Statement:
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 basic syntax is as
follows:
INSERT INTO table_name [ (column1 [, column2 ]) ]
SELECT [ *|column1 [, column2 ]
FROM table1 [, table2 ]
[ WHERE VALUE OPERATOR ]
Example:
Consider a table CUSTOMERS_BKP with similar structure as CUSTOMERS table. Now to
copy complete CUSTOMERS table into CUSTOMERS_BKP, following is the syntax:
SQL> INSERT INTO CUSTOMERS_BKP
SELECT * FROM CUSTOMERS
WHERE ID IN (SELECT ID FROM CUSTOMERS) ;
Subqueries with the UPDATE Statement:
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 basic syntax is as follows:
UPDATE table
SET column_name = new_value
[ WHERE OPERATOR [ VALUE ]
(SELECT COLUMN_NAME
FROM TABLE_NAME)
[ WHERE) ]
Example:
Assuming, we have CUSTOMERS_BKP table available which is backup of
CUSTOMERS table.
Following example updates SALARY by 0.25 times in CUSTOMERS table for all the
customers whose AGE is greater than or equal to 27: SQL> UPDATE CUSTOMERS
SET SALARY = SALARY * 0.25
WHERE AGE IN (SELECT AGE FROM
CUSTOMERS_BKP WHERE AGE >= 27 );
Subqueries with the DELETE Statement:
The subquery can be used in conjunction with the DELETE statement like with any other
statements mentioned above.
The basic syntax is as follows:
DELETE FROM TABLE_NAME
You can use a subquery after a comparison operator, followed by the keyword ALL, ANY, or
SOME.
The ALL operator compares value to every value returned by the subquery. Therefore ALL
operator (which must follow a comparison operator) returns TRUE if the comparison is
TRUE for ALL of the values in the column that the subquery returns.
Syntax :
operand comparison_operator ALL (subquery)
NOT IN is an alias for <> ALL. Thus, these two statements are the same :
Traditionally, an EXISTS subquery starts with SELECT *, but it could begin with SELECT
5 or SELECT column1 or anything at all. MySQL ignores the SELECT list in such a
subquery, so it makes no difference.
For the preceding example, if t2 contains any rows, even rows with nothing but NULL
values, the EXISTS condition is TRUE. This is actually an unlikely example because a
[NOT] EXISTS subquery almost always contains correlations. Here are some more realistic
examples:
Correlated Subqueries
A correlated subquery is a subquery that contains a reference to a table that also appears in
the outer query. For example:
SELECT * FROM t1
WHERE column1 = ANY (SELECT column1 FROM t2
WHERE t2.column2 = t1.column2);
Notice that the subquery contains a reference to a column of t1, even though the subquery's
FROM clause does not mention a table t1. So, MySQL looks outside the subquery, and finds
t1 in the outer query.
SQL includes a boolean function for testing whether a subquery has duplicate
tuples in its result. The unique construct9 returns the value true if the argument
subquery contains no duplicate tuples. Using the unique construct, we can write
the query “Find all courses that were offered at most once in 2009” as follows:
Note that if a course is not offered in 2009, the subquery would return an empty
result, and the unique predicate would evaluate to true on the empty set.
ASSIGNMENT NO.5
TITLE:
Write and execute suitable database triggers .Consider row level and statement level
triggers.
OBJECTIVE:
1. To understand the concept of Triggers in PL/SQL .
THEORY:
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.
Benefits of Triggers
Triggers can be written for the following purposes −
Creating Triggers
The syntax for creating a trigger is −
{BEFORE | AFTER | INSTEAD OF} − This specifies when the trigger will be
executed. The INSTEAD OF clause is used for creating trigger on a view.
{INSERT [OR] | UPDATE [OR] | DELETE} − This specifies the DML operation.
[OF col_name] − This specifies the column name that will be updated.
[ON table_name] − This specifies the name of the table associated with the trigger.
[REFERENCING OLD AS o NEW AS n] − This allows you to refer new and old
values for various DML statements, such as INSERT, UPDATE, and DELETE.
[FOR EACH ROW] − This specifies a row-level trigger, i.e., the trigger will be
executed for each row being affected. Otherwise the trigger will execute just once
when the SQL statement is executed, which is called a table level trigger.
WHEN (condition) − This provides a condition for rows for which the trigger would
fire. This clause is valid only for row-level triggers.
Example
To start with, we will be using the CUSTOMERS table we had created and used in the
previous chapters −
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
+----+----------+-----+-----------+----------+
The following program creates a row-level trigger for the customers table that would fire for
INSERT or UPDATE or DELETE operations performed on the CUSTOMERS table. This
trigger will display the salary difference between the old values and new values −
Trigger created.
The following points need to be considered here −
OLD and NEW references are not available for table-level triggers, rather you can use
them for record-level triggers.
If you want to query the table in the same trigger, then you should use the AFTER
keyword, because triggers can query the table or change it again only after the initial
changes are applied and the table is back in a consistent state.
The above trigger has been written in such a way that it will fire before any DELETE
or INSERT or UPDATE operation on the table, but you can write your trigger on a
single or multiple operations, for example BEFORE DELETE, which will fire
whenever a record will be deleted using the DELETE operation on the table.
Triggering a Trigger
Let us perform some DML operations on the CUSTOMERS table. Here is one INSERT
statement, which will create a new record in the table −
Old salary:
New salary: 7500
International Institute of Information Technology, Hinjawadi, Pune. Page 52
SL-I Laboratory Manual (17-18) Department of Information
Technology
Salary difference:
Because this is a new record, old salary is not available and the above result comes as null.
Let us now perform one more DML operation on the CUSTOMERS table. The UPDATE
statement will update an existing record in the table −
UPDATE customers
SET salary = salary + 500
WHERE id = 2;
When a record is updated in the CUSTOMERS table, the above create trigger,
display_salary_changes will be fired and it will display the following result −
ASSIGNMENT NO.6
TITLE:
Write and execute PL/SQL stored procedure and function to perform a suitable task
on the database. Demonstrate its use.
OBJECTIVE:
1. To understand the PL/SQL.
THEORY:
PL/SQL is the procedural extension to SQL with design features of programming languages.
Data manipulation and query statements of SQL are included within procedural units of code.
Benefits of PL/SQL:
PL/SQL can improve the performance of an application. The benefits differ depending on
the execution environment:
PL/SQL can be used to group SQL statements together within a single block and to send
the entire block to the server in a single call thereby reducing networking traffic. Without
PL/SQL, the SQL statements are sent to the Oracle server one at a time. Each SQL
statement results in another call to the Oracle server and higher performance overhead. In
a network environment, the overhead can become significant.
PL/SQL can also operate with Oracle server application development tools such
as Oracle forms and Oracle reports.
Every unit of PL/SQL comprises one or more blocks. These blocks can be entirely separate or
nested one within another. The basic units (procedures, functions, and anonymous blocks)
that make up a PL/SQL program are logical blocks which can contain any number of nested
sub-blocks. Therefore one block can represent a small part of another block, which in turn
can be part of the whole unit of code.
Modularized program development:
Group logically related statements within blocks.
Nest sub-blocks inside larger blocks to build powerful programs.
Break down a complex problem into a set of manageable well defined logical
modules and implement the modules with blocks.
Place reusable PL/SQL code in libraries to be shared between Oracle forms and
Oracle reports, applications, or store it in a Oracle server to make it accessible to any
application that can interact with an Oracle database.
Declare variables, cursors, constants and exceptions and then use them in SQL and
procedural statements.
Declare variables belonging to scalar, reference, composite and large object
(LOB) data types.
Declare variables dynamically based on the data structure of tables and columns in the
database.
PL/SQL Block Syntax:
DECLARE [Optional]
Variables, cursors, user defined exceptions
BEGIN [Mandatory]
- SQL Statements –
- PL/SQL
Statements –
Exception
[Optional]
ASSIGNMENT NO.7
TITLE:
Write a PL/SQL block to implement all types of cursor.
OBJECTIVE:
1. To understand the PL/SQL cursors.
THEORY:
Cursors: Every SQL statement executed by the Oracle server has an individual
cursor associated with it and are called implicit cursors. There are two types of
cursors. Implicit cursors: Declared for all DML and PL/SQL SELECT statements.
Explicit cursors: Declared and names by the programmer.
Explicit Cursors:
Individually process each row returned by a multiple row select statement. A
PL/SQL program opens a cursor, processes rows returned by a query, and
then
closes the cursor. The cursor marks the current position in the active set.
Can process beyond the first row returned by the query, row by row.
Keep track of which row is currently being processed.
Allow the programmer to manually control explicit cursors in the
PL/QL block.
Declare the cursor by naming it and defining the structure of the query to be
performed. Within it.
Open the cursor: The OPEN statement executes the query and binds the variables
that are referenced. Rows identified by the query are called the active set and are now
available for fetching.
Fetch data from the cursor: After each fetch, you test the cursor for any existing
row. If there are no more rows to process, then you must close the cursor.
Close the cursor: The CLOSE statement releases the active set of rows. It is now
possible to reopen the cursor to establish a fresh active set.
Working with MySQL cursor
The cursor declaration must be after any variable declaration. If you declare
a cursor before variables declaration, MySQL will issue an error. A cursor
must always be associated with a SELECT statement.
o Next, you open the cursor by using the OPEN statement. The OPEN
statement initializes the result set for the cursor therefore you must call the
OPEN statement before fetching rows from the result set.
o
OPEN cursor_name;
Then, you use the FETCH statement to retrieve the next row pointed by the
cursor and move the cursor to the next row in the result set.
FETCH cursor_name INTO variables list;
After that, you can check to see if there is any row available before fetching
it.
Finally, you call the CLOSE statement to deactivate the cursor and release
the memory associated with it as follows:
CLOSE cursor_name;
Because each time you call the FETCH statement, the cursor attempts to
read the next row in the result set. When the cursor reaches the end of the
result set, it will not be able to get the data, and a condition is raised. The
handler is used to handle this condition.
To declare a NOT FOUND handler, you use the following syntax:
DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
We are going to develop a stored procedure that builds an email list of all
employees in the employees table in the company sample database provided
with this assignment
o
First, we declare some variables, a cursor for looping over the emails of
employees, and a NOT FOUND handler:
o
DECLARE finished INTEGER DEFAULT 0; o
DECLARE email varchar(255) DEFAULT ""; o
o -- declare cursor for employee email o
DEClARE email_cursor CURSOR FOR o
SELECT email FROM employees; o
After that, inside the loop we used the v_finished variable to check if there is
any email in the list to terminate the loop.
Finally, we close the cursor using the CLOSE statement:
o
o CLOSE email_cursor;
o
o The build_email_list stored procedure is as
follows: o
o DELIMITER $$
o
o CREATE PROCEDURE build_email_list (INOUT email_list varchar(4000))
o BEGIN
o
oDECLARE v_finished INTEGER DEFAULT 0;
o DECLARE v_email varchar(100) DEFAULT ""; o
o OPEN email_cursor; o
o get_email: LOOP o
IF v_finished = 1 THEN
LEAVE get_email;
END IF;
Syntax:
Declaring a cursor:
CURSOR cursor_name IS
Select_statement;
Opening a cursor:
International Institute of Information Technology, Hinjawadi, Pune. Page 58
SL-I Laboratory Manual (17-18) Department of Information
Technology
OPEN cursor_name;
Fetch data from a cursor:
FETCH cursor_name INTO [variable1, variable2,….]| record_name];
Closing a cursor: Close cursor_name;
Attributes of an Explicit Cursor:
%ISOPEN [is cursor open]
%NOTFOUND [is row not found] o
%FOUND [is row found]
o %ROWCOUNT [rows returned so far]
Cursors can be passed parameters. Cursors also have FOR UPDATE option which allows
more fine grained control of locking at a table level. WHERE CURRENT OF can be used
to apply the update or delete operation to current row in the cursor.
1. Write a Cursor to display the first five records on the following
2. Write a Cursor to display the employee number, name, department and salary
of first employee getting the highest salary.
FAQ:
A batch
1. What is Mysql cursor?
2. Explain the properties of Mysql cursor.
3. How to create cursor in Mysql explain with proper example
ASSIGNMENT NO.8
TITLE:
Execute DDL statements which demonstrate the use of views. Try to update the
base table using its corresponding view. Also consider restrictions on updatable views and
perform view creation from multiple tables.
OBJECTIVE:
1) To understand the concept of view and implementation
THEORY:
A view is nothing more than a SQL statement that is stored in the database with an associated
name. A view is actually a composition of a table in the form of a predefined SQL query.
A view can contain all rows of a table or select rows from a table. A view can be created
from one or many tables which depends on the written SQL query to create a view.
Views, which are a type of virtual tables allow users to do the following −
Structure data in a way that users or classes of users find natural or intuitive.
Restrict access to the data in such a way that a user can see and (sometimes) modify
exactly what they need and no more.
Summarize data from various tables which can be used to generate reports.
Creating Views
Database views are created using the CREATE VIEW statement. Views can be created from
a single table, multiple tables or another view.
To create a view, a user must have the appropriate system privilege according to the specific
implementation.
Example
Consider the CUSTOMERS table having the following records −
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
+----------+-----+
| name | age |
+----------+-----+
| Ramesh | 32 |
| Khilan | 25 |
| kaushik | 23 |
| Chaitali | 25 |
| Hardik | 27 |
| Komal | 22 |
| Muffy | 24 |
+----------+-----+
The WITH CHECK OPTION
The WITH CHECK OPTION is a CREATE VIEW statement option. The purpose of the
WITH CHECK OPTION is to ensure that all UPDATE and INSERTs satisfy the condition(s)
in the view definition.
If they do not satisfy the condition(s), the UPDATE or INSERT returns an error.
The following code block has an example of creating same view CUSTOMERS_VIEW with
the WITH CHECK OPTION.
Updating a View
A view can be updated under certain conditions which are given below −
All NOT NULL columns from the base table must be included in the view in order for
the INSERT query to function.
So, if a view satisfies all the above-mentioned rules then you can update that view. The
following code block has an example to update the age of Ramesh.
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 35 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Here, we cannot insert rows in the CUSTOMERS_VIEW because we have not included all
the NOT NULL columns in this view, otherwise you can insert rows in a view in a similar
way as you insert them in a table.
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 35 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Dropping Views
Obviously, where you have a view, you need a way to drop the view if it is no longer needed.
The syntax is very simple and is given below −
Group C: MongoDB
ASSIGNMENT NO.1
TITLE: Create a database with suitable example using MongoDB and implement
Inserting and saving document (batch insert, insert validation)
Removing document
Updating document (document replacement, using modifiers, upserts, updating
multiple documents, returning updated documents)
OBJECTIVE:
1. To understand the basic queries used in mongodb.
THEORY:
Connect to a Database
Connect to the database server, which runs as mongod, and begin using the mongo shell to
select a logical database within the database instance and access the help text in the
mongo shell.
Connect to a mongod
From a system prompt, start mongo by issuing the mongo command, as follows:
mongo
By default, mongo looks for a database server listening on port 27017 on the localhost
interface. To connect to a server on a different port or interface, use the --port and --host
options.
Select a Database
After starting the mongo shell your session will use the test database by default. At any time,
issue the following operation at the mongo to report the name of the current database: db
1. From the mongo shell, display the list of databases, with the following operation:
2. show dbs
3. Switch to a new database named mydb, with the following operation:
4. use mydb
5. Confirm that your session has the mydb database as context, by checking the value of
the db object, which returns the name of the current database, as follows:
6. db
At this point, if you issue the show dbs operation again, it will not include the mydb
database. MongoDB will not permanently create a database until you insert data into that
database. The Create a Collection and Insert Documents section describes the process for
inserting data. New in version 2.4: show databases also returns a list of databases.
Display mongo Help
At any point, you can access help for the mongo shell using the following operation:
help
Furthermore, you can append the .help() method to some JavaScript methods, any
cursor object, as well as the db and db.collection objects to return additional help
information. Create a Collection and Insert Documents
In this section, you insert documents into a new collection named testData within the new
database named mydb.
MongoDB will create a collection implicitly upon its first use. You do not need to create a
collection before inserting data. Furthermore, because MongoDB uses dynamic schemas,
you also need not specify the structure of your documents before inserting them into the
collection.
1. From the mongo shell, confirm you are in the mydb database by issuing
the following:
2. db
3. If mongo does not return mydb for the previous operation, set the context to the
mydb database, with the following operation:
4. use mydb
5. Create two documents named j and k by using the following sequence of
JavaScript operations:
6. j = { name : "mongo" }
7. k = { x : 3 }
8. Insert the j and k documents into the testData collection with the following
sequence of operations:
9. db.testData.insert( j )
10. db.testData.insert( k )
When you insert the first document, the mongod will create both the mydb database and the
testData collection.
11. Confirm that the testData collection exists. Issue the following operation:
12. show collections
The mongo shell will return the list of the collections in the current (i.e. mydb) database.
At this point, the only collection is testData. All mongod databases also have a
system.indexes collection.
13. Confirm that the documents exist in the testData collection by issuing a query on the
collection using the find() method:
14. db.testData.find()
This operation returns the following results. The ObjectId values will be unique:
{ "_id" : ObjectId("4c2209f9f3924d31102bd84a"), "name" : "mongo" }
{ "_id" : ObjectId("4c2209fef3924d31102bd84b"), "x" : 3 }
All MongoDB documents must have an _id field with a unique value. These operations do
not explicitly specify a value for the _id field, so mongo creates a unique ObjectId value for
the field before inserting it into the collection.
In MongoDB, the db.collection.find() method retrieves documents from a collection.
The createCollection() Method
MongoDB db.createCollection(name, options) is used to create collection.
Syntax:
Basic syntax of createCollection() command is as follows
db.createCollection(name, options)
The use Command
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 create a database with name <mydb>, then use DATABASE statement would
be as follows:
>use mydb
switched to db mydb
Syntax
Basic syntax of insert () command is as follows:
>db.COLLECTION_NAME.insert(document)
MongoDB Update () method
The update () method updates values in the existing document.
Syntax:
Basic syntax of update() method is as follows
>db.COLLECTION_NAME.update(SELECTIOIN_CRITERIA, UPDATED_DATA)
Batch Insert:
db.car.insert(
... [
... { _id:1,name:"Audi",color:"Red",cno:"H101",mfdcountry:"Germany",speed:75 },
... { _id:2,name:"Swift",color:"Black",cno:"H102", speed:60 },
... {name:"Maruthi800",color:"Blue",cno:"H103",mfdcountry:"India",speed:70 },
... ])
db.car.insert(
...{ _id:2,name:“EEco",color:“White", speed:75 },
...)
Duplicate ID error
Validation of data:
db.collection.validate(full)
Validates a collection. The method scans a collection‟s data structures for
correctness.
MongoDB provides the capability to validate documents during updates and
insertions. Validation rules are specified on a per-collection basis using the validator
option, which takes a document that specifies the validation rules or expressions.
You can specify document validation rules when creating a new collection using
db.createCollection () with the validator option. When you add validation to a
collection, existing documents do not undergo validation checks until modification
Update:
Upsert: To insert rows into a database table if they do not already exist, or update
them if they do.
db.collection.save()
Updates an existing document or inserts a new document, depending on its document
parameter. If the document does not contain an _id field, then the save() method calls the
insert() method. During the operation, the mongo shell will create an ObjectId and assign it to
the _id field. If the document contains an _id field, then the save() method is equivalent to an
update with the upsert option set to true and the query predicate on the _id field.
Examples:
db.products.save( { item: "book", qty: 40 } )
{ "_id" : ObjectId("50691737d386d8fadbd6b01d"), "item" : "book", "qty" : 40 }
db.products.save( { _id: 100, item: "water", qty: 30 } )
{ "_id" : 100, "item" : "water", "qty" : 30 }
db.products.save( { _id : 100, item : "juice" } )
Because the _id field holds a value that exists in the collection, the operation
performs an update to replace the document and results in the following document:
{ "_id" : 100, "item" : "juice" }
remove () Method:
MongoDB's remove () method is used to remove document from the collection. remove()
method accepts two parameters. One is deletion criteria and second is justOne flag
1. deletion criteria: (Optional) deletion criteria according to documents will be
removed.
2. justOne : (Optional) if set to true or 1, then remove only one document.
Syntax:
Basic syntax of remove () method is as follows
db.COLLECTION_NAME.remove(DELLETION_CRITTERIA)
FAQ:
What platforms does MongoDB support?
ASSIGNMENT NO.2
TITLE: Execute at least 10 queries on any suitable MongoDB database that demonstrates
following querying techniques
find and findOne (specific values)
Query criteria (Query conditionals, OR queries, $not, Conditional semantics)
Type-specific queries (Null, Regular expression, Querying arrays)
OBJECTIVE:
1. To understand the querying technique used in mongodb.
THEORY:
find and findOne (specific values): The find method is used to perform queries in
MongoDB. Querying returns a subset of documents in a collection, from no documents at all
to the entire collection. Which documents get returned is determined by the first argument to
find, which is a document specifying the query to be performed.
An empty query document (i.e., {}) matches everything in the collection. If find isn‟t
given a query document, it defaults to {}.
For example, the following:
>1)db.c.find()
returns everything in the collection c.
2)where the value for "age" is 27, we can add that key/value pair to the query document:
> db.users.find({"age" : 27})
3) to get all users who are 27-year-olds with the username
“joe,” we can query for the following:
> db.users.find({"username" : "joe", "age" : 27})
Specifying Which Keys to Return: Sometimes, you do not need all of the key/value pairs in
a document returned. If this is the case, you can pass a second argument to find (or findOne)
specifying the keys you want. This reduces both the amount of data sent over the wire and the
time and memory used to decode documents on the client side.
For example, if you have a user collection and you are interested only in the "user
name" and "email" keys, you could return just those keys with the following query:
> db.users.find({}, {"username" : 1, "email" : 1})
{
"_id" : ObjectId("4ba0f0dfd22aa494fd523620"),
"username" : "joe",
"email" : [email protected]
}
Query Criteria:
1) Query Conditionals:
"$lt", "$lte", "$gt", and "$gte" are all comparison operators, corresponding to <, <=,
>, and >=, respectively. They can be combined to look for a range of values.
For example,
1) to look for users who are between the ages of 18 and 30 inclusive, we can do this:
> db.users.find ({"age" : {"$gte" : 18, "$lte" : 30}})
2) to find people who registered before January 1, 2017, we can do this:
> start = new Date("01/01/2017")
> db.users.find({"registered" : {"$lt" : start}})
3) If you want to find all users who do not have the username “joe,” you can query for them
using this:
> db.users.find ({"username" : {"$ne”: "joe"}})
"$ne" can be used with any type.
OR Queries:
There are two ways to do an OR query in MongoDB. "$in" can be used to query for a
variety of values for a single key. "$or" is more general; it can be used to query for any
of the given values across multiple keys.
For instance,
1)suppose we were running a raffle and the winning
ticket numbers were 725, 542, and 390. To find all three of these documents, we can
construct the following query:
> db.raffle.find({"ticket_no" : {"$in" : [725, 542, 390]}})
$not:
"$not" is a metaconditional: it can be applied on top of any other criteria. As an example,
let‟s consider the modulus operator, "$mod". "$mod" queries for keys whose values, when
divided by the first value given, have a remainder of the second value:
> db.users.find({"id_num" : {"$mod" : [5, 1]}})
The previous query returns users with "id_num"s of 1, 6, 11, 16, and so on. If we want,
instead, to return users with "id_num"s of 2, 3, 4, 5, 7, 8, 9, 10, 12, and so on, we can
use "$not":
> db.users.find({"id_num" : {"$not" : {"$mod" : [5, 1]}}})
Type-Specific Queries:
null:
null behaves a bit strangely. It does match itself, so if we have a collection with the
following documents:
> db.c.find()
{ "_id" : ObjectId("4ba0f0dfd22aa494fd523621"), "y" : null }
{ "_id" : ObjectId("4ba0f0dfd22aa494fd523622"), "y" : 1 }
{ "_id" : ObjectId("4ba0f148d22aa494fd523623"), "y" : 2 }
we can query for documents whose "y" key is null in the expected way:
> db.c.find({"y" : null})
{ "_id" : ObjectId("4ba0f0dfd22aa494fd523621"), "y" : null }
Regular Expressions:
Regular expressions are useful for flexible string matching.
db.users.find({"name": /m/}) Hema, Madhu, Jamila
db.users.find({name: /^pa/}) Starts with pa
db.users.find({name: /ro$/}) Ends with ro
db.collection.find({name:{'$regex' : 'string$', '$options' : 'i'}})
Querying Arrays:
Querying for elements of an array is simple. An array can mostly be treated as though
each element is the value of the overall key.
Example:
db.bios.find( { contribs: "UNIX" } )
"contribs" : [ "Fortran", "ALGOL", "Backus-Naur Form", "FP" ]
$all
If you need to match arrays by more than one element, you can use "$all".
$size
A useful conditional for querying arrays is "$size", which allows you to query for arrays
of a given size.
suppose we had a blog post document and we wanted to return the first 10 comments:
> db.blog.posts.findOne(criteria, {"comments" : {"$slice" : 10}})
ASSIGNMENT NO.3
TITLE: Execute at least 10 queries on any suitable MongoDB database that demonstrates
following:
$ where queries
Cursors (Limits, skips, sorts, advanced query options)
Database commands
OBJECTIVE:
1. To understand the advanced querying technique used in mongodb.
THEORY:
$where Queries:
Key/value pairs are a fairly expressive way to query, but there are some queries that
they cannot represent. For queries that cannot be done any other way, there are
"$where" clauses, which allow you to execute arbitrary JavaScript as part of your query.
This allows you to do (almost) anything within a query.
> db.foo.insert({"apple" : 1, "banana" : 6, "peach" : 3})
> db.foo.insert({"apple" : 8, "spinach" : 4, "watermelon" : 4})
In the second document, "spinach" and "watermelon" have the same value, so we‟d like
that document returned. It‟s unlikely MongoDB will ever have a $ conditional for this,
so we can use a "$where" clause to do it with JavaScript:
> db.foo.find({"$where" : function () {
... for (var current in this) {
... for (var other in this) {
... if (current != other && this[current] == this[other]) {
... return true;
... }
... }
... }
... return false;
... }});
If the function returns true, the document will be part of the result set; if it returns
false, it won‟t be.
We used a function earlier, but you can also use strings to specify a "$where" query; the
following two "$where" queries are equivalent:
> db.foo.find({"$where" : "this.x + this.y == 10"})
> db.foo.find({"$where" : "function() { return this.x + this.y == 10; }"})
Cursors:
The database returns results from find using a cursor. The client-side implementations
of cursors generally allow you to control a great deal about the eventual output of a
query.
we create a very simple collection and query it, storing the results in the cursor
variable:
> for(i=0; i<100; i++) {
... db.c.insert({x : i});
... }
> var cursor = db.collection.find();
Example:
To set a limit, chain the limit function onto your call to find. For example, to only
return three results, use this:
> db.c.find().limit(3)
There are two types of queries: wrapped and plain. A plain query is something like this:
> var cursor = db.foo.find({"foo" : "bar"})
There are a couple options that “wrap” the query. For example, suppose we perform
a sort:
> var cursor = db.foo.find({"foo" : "bar"}).sort({"x" : 1})
Instead of sending {"foo" : "bar"} to the database as the query, the query gets wrapped
in a larger document. The shell converts the query from {"foo" : "bar"} to {"$query" :
{"foo" : "bar"}, "$orderby" : {"x" : 1}}.
ASSIGNMENT NO.4
TITLE: IMPLEMENT MAP REDUCES OPERATION WITH SUITABLE
EXAMPLE USING MONGODB
OBJECTIVE:
1. To understand the what is map reduce function in mongodb.
THEORY:
Map-reduce is a data processing paradigm for condensing large volumes of data into useful
aggregated results. For map-reduce operations, MongoDB provides the mapReduce database
command. MongoDB applies the map phase to each input document (i.e. the documents in
the collection that match the query condition). The map function emits key-value pairs. For
those keys that have multiple values, MongoDB applies the reduce phase, which collects and
condenses the aggregated data. MongoDB then stores the results in a collection. Optionally,
the output of the reduce function may pass through a finalize function to further condense or
process the results of the aggregation.
All map-reduce functions in MongoDB are JavaScript and run within the mongod process.
Map-reduce operations take the documents of a single collection as the input and can perform
any arbitrary sorting and limiting before beginning the map stage. mapReduce can return the
results of a map-reduce operation as a document, or may write the results to collections. The
input and the output collections may be sharded.
Example of map reduce function: Return the Total Price Per Customer
Perform the map-reduce operation on the orders collection to group by the cust_id, and
calculate the sum of the price for each cust_id:
1. Define the map function to process each input document:
In the function, this refers to the document that the map-reduce operation is
processing.
o The function maps the price to the cust_id for each document and emits the
cust_id and price pair.
2. var mapFunction1 = function() {
3. emit(this.cust_id, this.price);
4. };
5. Define the corresponding reduce function with two arguments keyCustId and
valuesPrices:
o The valuesPrices is an array whose elements are the price values emitted by the
map function and grouped by keyCustId.
o The function reduces the valuesPrice array to the sum of its elements.
6. var reduceFunction1 = function(keyCustId, valuesPrices) {
7. return Array.sum(valuesPrices);
8. };
9. Perform the map-reduce on all documents in the orders collection using the
mapFunction1 map function and the reduceFunction1 reduce function.
10. db.orders.mapReduce(
11. mapFunction1,
12. reduceFunction1,
13. { out: "map_reduce_example" }
14. )
ASSIGNMENT NO.5
TITLE:
IMPLEMENT AGGREGATION AND INDEXING WITH SUITABLE
EXAMPLE USING MONGODB
OBJECTIVE:
1. To understand the aggregation operation and indexing.
THEORY: Aggregation:
Aggregations operations process data records and return computed results. Aggregation
operations group values from multiple documents together, and can perform a variety of
operations on the grouped data to return a single result. In sql count(*) and with group by is
an equivalent of mongodb aggregation.
The aggregate() Method
For the aggregation in mongodb you should use aggregate() method.
>db.COLLECTION_NAME.aggregate(AGGREGATE_OPERATION)
> db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$sum : 1}}}])
{
result" : [
{
"_id" : "tutorials point",
"num_tutorial" : 2
},
{
"_id" : "tutorials point",
"num_tutorial" : 1
}
],
"ok" : 1
Expression Description Example
db.mycol.aggregate([{$group : {_id
$sum: Sums up the defined value from all : "$by_user", num_tutorial : {$sum
documents in the collection. : "$likes"}}}])
db.mycol.aggregate([{$group : {_id
$avg: Calculates the average of all given
: "$by_user", num_tutorial : {$avg :
values from all documents in the collection
"$likes"}}}])
db.mycol.aggregate([{$group : {_id
$min: Gets the minimum of the
: "$by_user", num_tutorial : {$min :
corresponding values from all documents in
"$likes"}}}])
the collection.
$max: Gets the maximum of the db.mycol.aggregate([{$group : {_id
corresponding values from all documents in : "$by_user", num_tutorial : : "$likes"}}}])
the collection. {$max
For queries that cannot use an index, MongoDB must scan all documents in a
collection for documents that match the query.
FAQ:
A batch
1. What is aggregation? Write aggregate() method with proper example.
2. Write a mongo query to calculate average marks of a student in 5 subjects
3. Write use of “project” operator with proper example.
B batch
1. What is indexing? How to create a unique index?
2. Write a mongo query to find minimum and maximum salary of a employee from
employee collection.
3. Write query to drop the index.
C batch
1. Explain “match” and “group” operator with proper example.
2. How to create an index on a single field explain with suitable example.
3. Explain “push” operator with example.
D batch
1. What is aggregation pipeline?
2. Write the query which will count all the documents in the collection.
3. How to use project operator to create new field?