Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
622 views

cp4152 Database Practices Lab

The document discusses creating tables and adding constraints in SQL. It provides 5 examples of creating tables with different fields, data types, primary keys, foreign keys, and other constraints. For each table creation, it shows the correct SQL statement and describes the table. The overall aim is to write SQL statements to create tables with constraints.

Uploaded by

Suganya C
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
622 views

cp4152 Database Practices Lab

The document discusses creating tables and adding constraints in SQL. It provides 5 examples of creating tables with different fields, data types, primary keys, foreign keys, and other constraints. For each table creation, it shows the correct SQL statement and describes the table. The overall aim is to write SQL statements to create tables with constraints.

Uploaded by

Suganya C
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 73

lOMoARcPSD|31391250

CP4152 Database Practices Lab

Business Management (Thiruvalluvar University)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by Suganya C (suganyac@srmist.edu.in)
lOMoARcPSD|31391250

Ex. No: 1
Date :
Data Definition Language : Table Creation, Constraints.
Aim

To write SQL Statements using Data Definition Language (DDL) to Create Table with Constraints.

Theory

Data Definition Language

The Data Definition Language (DDL) is used to


• Creating a table
• Altering table structure by adding, deleting or modifying columns Destroy
databases and database objects.
These commands will primarily be used by database administrators during the setup and removal phases of
a database project.

CREATE COMMAND

CREATE command is used to Create tables that will contain data.

Syntax

CREATE TABLE [table name] ( [column definitions] );

CREATE TABLE student (studname varchar2(20) not null, studid number not null) ;

establishes a table titled "student" in the current database. In our example, the table contains two attributes:
studname and studid.

ALTER
Once table created within a database, one may wish to modify the definition of it. The ALTER
command allows you to make changes to the structure of a table without deleting and recreating it. For
example, the command to add a column named branch to an existing table named student would be:

ALTER TABLE student ADD branch varchar2(3);

The above command adds a new attribute branch to the student table.

DROP
The final command of the Data Definition Language, DROP, allows us to remove entire database
objects from DBMS. For example, if we want to permanently remove the student table that we created,
following command is used:

DROP TABLE student;


Practice Exercise

Downloaded by Suganya C (suganyac@srmist.edu.in)


lOMoARcPSD|31391250

1. Create a table named BRANCH with following Structure

Data Field Name Data Type Constraint

Branch Number branchno number(1) Primary Key Branch


branchname varchar2(30) Not Null

SQL> describe Branch;


Name Null? Type
----------------------------------------- -------- ----------------------------
BRANCHNO NOT NULL NUMBER(1)
BRANCHNAME NOT NULL VARCHAR2(30)
(Note: Make a copy of Correct SQL Statement in a Notepad and Save the File as 1.txt)

2 Create a table named STUDENT with following Structure


Data Field Name Data Type Constraint
Student Name name varchar2(30) Not Null
Student Number registerno number(11) Primary
Key
Branch Number branchno number(1) Foreign Key
Section sec varchar2(1) Not Null
Joined Date joindate date Not Null
Mark mark number(5,2) Not Null
SQL> desc student;
Name Null? Type
----------------------------------------- -------- ----------------------------
NAME NOT NULL VARCHAR2(30)
REGISTERNO NOT NULL NUMBER(11)
BRANCHNO NUMBER(1)
SECTION NOT NULL VARCHAR2(1)
JOINDATE NOT NULL DATE
MARK NOT NULL NUMBER(5,2)
(Note: Make a copy of Correct SQL Statement and Append to Notepad File 1.txt)

3. Add the column emailid to table student with Constraint UNIQUE.

SQL> desc student;


Name Null? Type
----------------------------------------- -------- ----------------------------
NAME NOT NULL VARCHAR2(30)
REGISTERNO NOT NULL NUMBER(11)
BRANCHNO NUMBER(1)
SECTION NOT NULL VARCHAR2(1)
JOINDATE NOT NULL DATE
MARK NOT NULL NUMBER(5,2)
EMAILID VARCHAR2(30)
(Note: Make a copy of Correct SQL Statement and Append to Notepad File 1.txt)

Downloaded by Suganya C (suganyac@srmist.edu.in)


lOMoARcPSD|31391250

4. Create a table named MARKGRADE with following Structure


Data Field Name Data Type Constraint
Grade grade varchar2(1) Not Null
Lowest Mark lowmark number(5,2) Not Null
Highest Mark highmark number(5,2) Not Null
SQL> desc Markgrade;
Name Null? Type
----------------------------------------- -------- ---------------
GRADE NOT NULL VARCHAR2(1)
LOWMARK NOT NULL NUMBER(5,2)
HIGHMARK NOT NULL NUMBER(5,2)
(Note: Make a copy of Correct SQL Statement and Append to Notepad File 1.txt)

5. Create a table named PROJECT with following Structure


Data Field Name Data Type Constraint
Primary
Project Number pno number(3) Key
Project Name pname varchar2(60)
Project Manager pmgr number(4) Not Null
Persons persons number(3)
Budjet budjet number(8,2)
Project Start date pstart date Not Null
Project End Date pend date
SQL> desc project
Name Null? Type
----------------------------------------- -------- -----------------
PNO NOT NULL NUMBER(3)
PNAME VARCHAR2(2)
PMGR NUMBER(4)
PERSONS NUMBER(3)
BUDJET NUMBER(8,2)
PSTART DATE
PEND DATE
(Note: Make a copy of Correct SQL Statement and Append to Notepad File 1.txt)

Result

Thus the SQL Statements using Data Definition Language (DDL) to Create Table with Constraints

is successfully Implemented.

Downloaded by Suganya C (suganyac@srmist.edu.in)


lOMoARcPSD|31391250

Ex. No: 2
Date :
Insert, Select , Update and Delete Commands.
Aim

To write queries using Insert, Select, Update, and Delete Commands in Data Manipulation Language

(DML).

Theory

• Data Retrieval: Select

• Data Manipulation Language (DML): Insert, Delete, Update

Data Manipulation Language (Insert, Delete, Update)

Data Manipulation Language (DML) is used by computer programs or database users to retrieve,
insert, delete and update data in a database. Currently, the most popular data manipulation language is that
of SQL, which is used to retrieve and manipulate data in a Relational database

Data Manipulation Languages have their functional capability organized by the initial word in a
statement, which is almost always a verb. In the case of SQL, these verbs are:

• SELECT

An SQL SELECT statement returns a result set of records from one or more tables. It retrieves zero
or more rows from one or more base tables or views in a database. In most applications, SELECT is
the most commonly used Data Manipulation Language (DML) command.

Example:

SELECT * FROM student;

* means all columns in a table

Note :
Use the following command to print Your Register Number in 11 Digit Format
SQL >COLUMN registerno FORMAT 99999999999

Use the following command to print Your section with size of 7


SQL > column section format a7

The SELECT statement has many optional clauses:

o WHERE specifies which rows to retrieve.

A WHERE clause in SQL specifies that a SQL Data Manipulation Language (DML)
statement should only affect rows that meet a specified criteria. WHERE clauses are not
mandatory clauses of SQL DML statements, but should be used to limit the number of rows
affected by a SQL DML statement or returned by a query. WHERE is an SQL reserved word.

Downloaded by Suganya C (suganyac@srmist.edu.in)


lOMoARcPSD|31391250

EXAMPLE : SELECT * FROM student WHERE mark > 90

o GROUP BY groups rows sharing a property so that an aggregate function can be applied to
each group.

A GROUP BY statement in SQL specifies that a SQL SELECT statement returns a list
that is grouped by one or more columns, usually in order to apply some sort of aggregate
function to certain columns.

Common grouping (aggregation) functions include:


• Count(expression) - Quantity of matching records (per group)
• Sum(expression) - Summation of given value (per group)
1. Min(expression) - Minimum of given value (per group)
• Max(expression) - Maximum of given value (per group)
• Avg(expression) - Average of given value (per group)

SELECT branchno, AVG(mark) FROM student


GROUP BY branchno;

o HAVING selects among the groups defined by the GROUP BY clause.

A HAVING statement in SQL specifies that a SQL SELECT statement should only
return rows where aggregate values meet the specified conditions.

Example:

SELECT branchno, AVG(mark) FROM student


GROUP BY branchno
HAVING AVG(mark) > 80;

o ORDER BY specifies an order in which to return the rows.

An ORDER BY clause in SQL specifies that a SQL SELECT statement returns a result set
with the rows being sorted by the values of one or more columns. ORDER BY is the only way to
sort the rows in the result set. Without this clause, the relational database system may return the
rows in any order. If an ordering is required, the ORDER BY must be provided in the SELECT
statement sent by the application.

Example:

SELECT * FROM student ORDER BY registerno;

SELECT * FROM student ORDER BY mark;

• INSERT
The number of columns and values must be the same. The values specified (or implied) by the INSERT
statement must satisfy all the applicable constraints (such as primary keys, CHECK constraints, and NOT
NULL constraints). If a syntax error occurs or if any constraints are violated, the new row is not added to
the table and an error returned instead.

Downloaded by Suganya C (suganyac@srmist.edu.in)


lOMoARcPSD|31391250

Syntax:

INSERT INTO table (column1, [column2, ... ]) VALUES (value1, [value2, ...])

INSERT INTO table VALUES (value1, [value2, ...])

Example:

• INSERT INTO
student(name,registerno,branchno,section,joindate,mark,emailid) VALUES
('Aarthi',11306205001,1,'A','01-apr-2006',99, 'abc@gmail.com')

• INSERT INTO student VALUES ('Aarthi',11306205001,1,'A','01-apr-


2006',99,
'abc@gmail.com')

Note that there are six values specified for the record. These correspond to the table attributes in
the order they were defined: name, registerno, branchno, section, joindate, mark

• UPDATE

A SQL UPDATE statement that changes the data of one or more records in a table. Either all the
rows can be updated, or a subset may be chosen using a condition.

Syntax:

UPDATE table_name SET column_name = value [, column_name = value ...] [WHERE condition]

For the UPDATE to be successful, the user must have data manipulation privileges (UPDATE privilege) on
the table or column, the updated value must not conflict with all the applicable constraints (such as
primary keys, unique indexes, CHECK constraints, and NOT NULL constraints).

Example:

UPDATE student
SET mark = mark + 2
WHERE registerno = 11306205001;

DELETE

An SQL DELETE statement removes one or more records from a table. A subset may be defined for deletion
using a condition, otherwise all records are removed.

Syntax:

DELETE FROM table_name [WHERE condition]

Any rows that match the WHERE condition will be removed from the table. If the WHERE clause is omitted,
all rows in the table are removed. The DELETE statement should thus be used with caution!

Downloaded by Suganya C (suganyac@srmist.edu.in)


lOMoARcPSD|31391250

The DELETE statement does not return any rows; that is, it will not generate a result set.

Example :

DELETE FROM student


WHERE registerno = 11306205001;
Practice Exercise

1. Insert following Values into the Table Branch.

BRANCHNO BRANCHNAME

1 Civil
2 Computer Science
3 Electrical
4 Electronics
5 Information Technology
6 Instrumentation
7 Mechanical
8 MBA
9 MCA
2. Insert following Values into the Table Student.
NAME REGISTERNO BRANCHNO SECTION JOINDATE MARK EMAILID

ADITYA KUMAR 11305104001 2 A 24-JUL-2005 99 ADITYA KUMAR@GMAIL.COM


NANDAKUMARAN 11305104061 2 B 30-MAY-2005 80 NANDAKUMARAN@YAHOO.COM
AASHA RANI 11308104001 2 A 02-AUG-2008 99 AASHA RANI M@YMAIL.COM
MANDYAM HARIKA 11308106061 4 B 04-AUG-2008 75 MANDYAMHARIKA@YAHOO.COM
ABDUL SAMAD 11308205001 5 A 02-AUG-2008 100 ABDUL SAMAD@REDIFFMAIL.COM
PRIYADHARSHINI 11308205062 5 B 18-SEP-2008 90 PRIYADHARSHINI@HOTMAIL.COM
AISHWARYA 11308103001 1 A 09-AUG-2008 78 AISHWARYA@GMAIL.COM
RAMMANOHAR 11308103030 1 A 01-AUG-2008 65 RAMMANOHAR@REDIFFMAIL.COM
AHAMED THAHA 11308114001 7 A 25-JUL-2008 90 AHAMED THAHA@GMAIL.COM
PRAVEEN 11308114025 7 A 28-JUL-2008 75 PRAVEEN@REDIFFMAIL.COM
ABINAYA 11308105001 3 A 01-AUG-2008 90 ABINAYA@YAHOO.COM
ANISH KUMAR 11308107001 6 A 26-JUL-2008 90 ANISH KUMAR@HOTMAIL.COM
KANIMOZHI 11308107027 6 A 06-AUG-2008 80 KANIMOZHI@GMAIL.COM
MADHUUSOODHANA11308105023 3 A 28-JUL-2008 90 MADHUUSOODHANA@YAHOO.COM

3. Insert following Values into the Table Markgrade.

Grade Lowmark Highmark


S 91 100
4. Display the contents of Branch Table.
BRANCHNO BRANCHNAME
---------- ------------------------------
1 Civil
2 Computer Science
3 Electrical
4 Electronics
5 Information Technology
6 Instrumentation
7 Mechanical

Downloaded by Suganya C (suganyac@srmist.edu.in)


lOMoARcPSD|31391250

8 MBA
9 MCA

9 rows selected.

5. Display the contents of Student Table.


NAME REGISTERNO BRANCHNO SECTION JOINDATE MARK EMAILID
--------------- ------------ ---------- ------- --------- ---------- ---------------------------
ADITYA KUMAR 11305104001 2 A 24-JUL-05 99 ADITYA KUMAR@GMAIL.COM
NANDAKUMARAN 11305104061 2 B 30-MAY-05 80 NANDAKUMARAN@YAHOO.COM
AASHA RANI 11308104001 2 A 02-AUG-08 99 AASHA RANI M@YMAIL.COM
MANDYAM HARIKA 11308106061 4 B 04-AUG-08 75 MANDYAMHARIKA@YAHOO.COM
ABDUL SAMAD 11308205001 5 A 02-AUG-08 100 ABDUL SAMAD@REDIFFMAIL.COM
PRIYADHARSHINI 11308205062 5 B 18-SEP-08 90 PRIYADHARSHINI@HOTMAIL.COM
AISHWARYA 11308103001 1 A 09-AUG-08 78 AISHWARYA@GMAIL.COM
RAMMANOHAR 11308103030 1 A 01-AUG-08 65 RAMMANOHAR@REDIFFMAIL.COM
AHAMED THAHA 11308114001 7 A 25-JUL-08 90 AHAMED THAHA@GMAIL.COM
PRAVEEN 11308114025 7 A 28-JUL-08 75 PRAVEEN@REDIFFMAIL.COM
ABINAYA 11308105001 3 A 01-AUG-08 90 ABINAYA@YAHOO.COM
ANISH KUMAR 11308107001 6 A 26-JUL-08 90 ANISH KUMAR@HOTMAIL.COM
KANIMOZHI 11308107027 6 A 06-AUG-08 80 KANIMOZHI@GMAIL.COM MADHUUSOODHANA
11308105023 3 A 28-JUL-08 90 MADHUUSOODHANA@YAHOO.COM

14 rows selected.

6. Display the contents of Markgrade Table.


GRADE LOWMARK HIGHMARK
----- ---------- ---------S
91 100 A
81 90
B 71 80
C 61 70
D 51 60
E 45 50
U 0 44

7 rows selected.

7. Make all the Informations Permanent to the Database.


Commit complete.

8. Display the details of students who are in branchnumber 2.


NAME REGISTERNO BRANCHNO SECTION JOINDATE MARK EMAILID
--------------- ------------ ---------- ------- --------- ---------- --------------------------
ADITYA KUMAR 11305104001 2 A 24-JUL-05 99 ADITYA KUMAR@GMAIL.COM
NANDAKUMARAN 11305104061 2 B 30-MAY-05 80 NANDAKUMARAN@YAHOO.COM
AASHA RANI 11308104001 2 A 02-AUG-08 99 AASHA RANI M@YMAIL.COM

9. Display the detail of grade for the mark between 81 and 90.
GRADE LOWMARK HIGHMARK

Downloaded by Suganya C (suganyac@srmist.edu.in)


lOMoARcPSD|31391250

----- ---------- ---------A


81 90

10. Display the name of the branch with branch number 5.


BRANCHNO BRANCHNAME
---------- ------------------------------
5 Information Technology

11. Display the Number of students in each branch.


Number of Students BRANCHNO
------------------ ----------
2 1
3 2
2 3
1 4
2 5
2 6
2 7

12. Display the Average mark of each branch.


Average Marks BRANCHNO
------------- ----------
71.5 1
92.6666667 2
90 3
75 4
95 5
85 6
82.5 7

7 rows selected.78 8
99 9
90 17
75 17
100 17
90 35

13. Display the Maximum mark of each branch.


Maximum Marks BRANCHNO
------------- ----------
90 7

7 rows selected.

14. Display the Maximum mark of branch where Maximum Mark greater than 90.
Maximum Marks BRANCHNO
------------- ----------
99 2
100 5

Downloaded by Suganya C (suganyac@srmist.edu.in)


lOMoARcPSD|31391250

15. Display the Name, Register Number, E-Mail ID and Join Date of Students who have joined later

25th July 2008.

NAME REGISTERNO EMAILID JOINDATE


--------------- ------------ ------------------------------ ---------
AASHA RANI 11308104001 AASHA RANI M@YMAIL.COM 02-AUG-08
MANDYAM HARIKA 11308106061 MANDYAMHARIKA@YAHOO.COM 04-AUG-08
ABDUL SAMAD 11308205001 ABDUL SAMAD@REDIFFMAIL.COM 02-AUG-08
PRIYADHARSHINI 11308205062 PRIYADHARSHINI@HOTMAIL.COM 18-SEP-08
AISHWARYA 11308103001 AISHWARYA@GMAIL.COM 09-AUG-08
RAMMANOHAR 11308103030 RAMMANOHAR@REDIFFMAIL.COM 01-AUG-08
PRAVEEN 11308114025 PRAVEEN@REDIFFMAIL.COM 28-JUL-08
ABINAYA 11308105001 ABINAYA@YAHOO.COM 01-AUG-08
ANISH KUMAR 11308107001 ANISH KUMAR@HOTMAIL.COM 26-JUL-08
KANIMOZHI 11308107027 KANIMOZHI@GMAIL.COM 06-AUG-08
MADHUUSOODHANA 11308105023 MADHUUSOODHANA@YAHOO.COM 28-JUL-08
11 rows selected.
Note : Display the Details from Student Table and make the changes Permanent.

Select * from student;

Commit;

16. Update the Section to C where section is B.


Result after Update

NAME REGISTERNO BRANCHNO SECTION JOINDATE MARK EMAILID


--------------- ------------ ---------- ------- --------- ---------- ---------------------------
ADITYA KUMAR 11305104001 2 A 24-JUL-05 99 ADITYA KUMAR@GMAIL.COM
NANDAKUMARAN 11305104061 2 C 30-MAY-05 80 NANDAKUMARAN@YAHOO.COM
AASHA RANI 11308104001 2 A 02-AUG-08 99 AASHA RANI M@YMAIL.COM
MANDYAM HARIKA 11308106061 4 C 04-AUG-08 75 MANDYAMHARIKA@YAHOO.COM
ABDUL SAMAD 11308205001 5 A 02-AUG-08 100 ABDUL SAMAD@REDIFFMAIL.COM
PRIYADHARSHINI 11308205062 5 C 18-SEP-08 90 PRIYADHARSHINI@HOTMAIL.COM
AISHWARYA 11308103001 1 A 09-AUG-08 78 AISHWARYA@GMAIL.COM
RAMMANOHAR 11308103030 1 A 01-AUG-08 65 RAMMANOHAR@REDIFFMAIL.COM
AHAMED THAHA 11308114001 7 A 25-JUL-08 90 AHAMED THAHA@GMAIL.COM
PRAVEEN 11308114025 7 A 28-JUL-08 75 PRAVEEN@REDIFFMAIL.COM
ABINAYA 11308105001 3 A 01-AUG-08 90 ABINAYA@YAHOO.COM
ANISH KUMAR 11308107001 6 A 26-JUL-08 90 ANISH KUMAR@HOTMAIL.COM
KANIMOZHI 11308107027 6 A 06-AUG-08 80 KANIMOZHI@GMAIL.COM
MADHUUSOODHANA 11308105023 3 A 28-JUL-08 90 MADHUUSOODHANA@YAHOO.COM

14 rows selected.
Note : Display the Details from Student Table. Check for Updation, Undo the Update Operation and make the changes Permanent.

Select * from student;

Rollback;

Commit;

Downloaded by Suganya C (suganyac@srmist.edu.in)


lOMoARcPSD|31391250

17. Update the marks of Student with Branch Number 5 to 100.

Note : Display the Details from Student Table. Check for Updation and make the changes Permanent.

Select * from student;

Commit;

18. Delete the details of student with register number 11305104001.


Note : Display the Details from Student Table. Check for Deleted Record.

19. Delete All records from Student Table.


Note : Display the Details from Student Table. Check for Deleted Records. Undo the Previous 2 Delete Operations and make the changes

Permanent.

20. Delete records from branch where branch Name is Electrical.

Whether the row is deleted? Give reasons

ERROR at line 1:
ORA-02292: integrity constraint (I7205312.STUD_BNO_FK) violated - child record found

Result

Thus to write queries using Insert, Select, Update, and Delete Commands in Data Manipulation

Language is successfully Completed.

Downloaded by Suganya C (suganyac@srmist.edu.in)


lOMoARcPSD|31391250

Ex. No: 3
Date :
Nested Queries and & Join Queries
Aim

To write Nested queries and Join Operation Supported by SQL.

Theory

Subquery

A subquery is a query within a query. Sub queries are also known as nested queries and are used to
answer multi-part questions. These subqueries can reside in the WHERE clause, the FROM clause, or the
SELECT clause. Sub queries and joins are often interchangeable and in fact the Oracle optimiser may well
treat a query containing a sub-query exactly as if it were a join.

Let's use a trivial example of finding the names of everybody who studies in the same branch as a
person called NANDAKUMARAN to illustrate this point. The SQL could be written using a sub query as
follows:

SELECT name FROM student WHERE branchno =

(SELECT branchno FROM student WHERE name = 'NANDAKUMARAN');

or as a join statement, like this:-


SELECT s1.name FROM student s1, student s2

WHERE s1.branchno = s2.branchno AND s2.name = 'NANDAKUMARAN';

With a trivial example like this there would probably be very little difference in terms of performance
of the SQL for such a simple query, but with more complex queries there could well be performance
implications.

Join
An SQL JOIN clause combines records from two or more tables in a database. It creates a set that
can be saved as a table or used as is. A JOIN is a means for combining fields from two tables by using values
common to each. SQL specifies different types of JOINs: Equi-Join, Non Equi-Join, Left Outer Join, ,Right
Outer Join. In special cases, a table (base table, view, or joined table) can JOIN to itself in a self-join.
Equi-join
An equi-join, also known as an equijoin, is a specific type of comparator-based join, that uses only
equality comparisons in the join-predicate.
Non Equi Join

Downloaded by Suganya C (suganyac@srmist.edu.in)


lOMoARcPSD|31391250

Non equi join is used to return result from two or more tables where exact join is not possible.For
example we have student table and Markgrade table. The Markgrade table contains grade and their low
Mark and high Mark. Suppose you want to find the grade Non Equi Join Can be used
Left outer join
The result of a left outer join (or simply left join) for table A and B always contains all records of the
"left" table (A), even if the join-condition does not find any matching record in the "right" table (B). This
means that a left outer join returns all the values from the left table, plus matched values from the right table
(or NULL in case of no matching join predicate).
To write a query that performs an outer join of tables A and B and returns all rows from A (a left
outer join), use the ANSI LEFT [OUTER] JOIN syntax, or apply the outer join operator (+) to all columns
of B in the join condition. For all rows in A that have no matching rows in B, Oracle returns null for any
select list expressions containing columns of B.
Right outer joins
A right outer join (or right join) closely resembles a left outer join, except with the treatment of the
tables reversed. Every row from the "right" table (B) will appear in the joined table at least once. If no
matching row from the "left" table (A) exists, NULL will appear in columns from A for those records that
have no match in A. Right outer join returns all the values from the right table and matched values from the
left table (NULL in case of no matching join predicate).
To write a query that performs an outer join of tables A and B and returns all rows from B (a right
outer join), use the ANSI RIGHT [OUTER] syntax, or apply the outer join operator (+) to all columns of A
in the join condition. For all rows in B that have no matching rows in A, Oracle returns null for any select
list expressions containing columns of A.

Full Outer Join


A full outer join combines the results of both left and right outer joins. The joined table will contain
all records from both tables, and fill in NULLs for missing matches on either side
Practice Exercise

1. Find the Names and Branch Number of all Students in the same branch as PRAVEEN and
PRIYADHARSHINI.
2. Find the Names and Branch Number of all Students who are not in the same branch as
KANIMOZHI.

3. Find the Branches that have Students with a Mark higher than the Average Student Mark.

4. Find the Names of all the Students who scored mark greater than the mark of student with
Register Number 11308103001.

Downloaded by Suganya C (suganyac@srmist.edu.in)


lOMoARcPSD|31391250

5. Find the Names of all the Students,mark who scored mark same as the mark of student with
Register Number 11305104061 or the mark of student with Name AISHWARYA.
Note : As the Sub Query returns multiple rows as output IN Operator should be Used

6. Display the Name of Student, Register Number, Branch Number, Branch Name from respective
tables.
Note : Equi join

7. Display the Name of Student, Mark, Grade from respective tables.


Note : Non Equi join
Marks in the Student table must be between lowest mark and highest mark in the Markgrade table.

8. Display Name of the Student, Register Number and Branch Name from respective Tables using
Right Outer Join
Note : Right Outer Join

9. Display Name of the Student, Register Number and Branch Name from respective Tables using
Left Outer Join
Note : Left Outer Join

10. Display Name of the Student, Register Number and Branch Name from respective Tables using
Full Outer Join
Note : Full Outer Join (Approach in Oracle 8i)

Result

Thus to write Nested queries and Join Operation Supported by SQL is Successfully Completed.

Downloaded by Suganya C (suganyac@srmist.edu.in)


lOMoARcPSD|31391250

Ex. No: 4
Date :
Views
Aim

To Implement Simple Views and Complex Views.

Theory

1. A view is a predefined query on one or more tables.


2. Retrieving information from a view is done in the same manner as retrieving from a table.
3. With some views you can also perform DML operations (delete, insert, update) on the base tables.
4. Views don't store data, they only access rows in the base tables.
5. user_tables, user_sequences, and user_indexes are all views.
6. View Only allows a user to retrieve data.
7. View can hide the underlying base tables.
8. By writing complex queries as a view, we can hide complexity from an end user.
9. View only allows a user to access certain rows in the base tables.

Syntax

CREATE [OR REPLACE] VIEW view_name


AS subquery

OR REPLACE specifies the view is to replace an existing view if present. subquery


specifies the subquery that retrieves from the base tables.

There are two basic types of views:

Simple views, which contain a subquery that retrieves from one base table

Complex views, which contain a subquery that:


o Retrieves from multiple base tables
o Groups rows using a GROUP BY or DISTINCT clause o Contains a
function call

A view is simply the representation of a SQL statement that is stored in memory so that it can easily
be re-used. For example, if we frequently issue the following query

SELECT registerno FROM student;

To create a view use the create view command as seen in this example

CREATE VIEW view_stud

Downloaded by Suganya C (suganyac@srmist.edu.in)


lOMoARcPSD|31391250

AS
SELECT registerno FROM student;
This command creates a new view called VIEW_STUD. Note that this command does not result in
anything being actually stored in the database at all except for a data dictionary entry that defines this view.
This means that every time you query this view, Oracle has to go out and execute the view and query the
database data. We can query the view like this:

SELECT * FROM view_stud WHERE registerno BETWEEN 11305205001 AND 11305205060;

And Oracle will transform the query into this:

SELECT * FROM (select registerno from student) WHERE registerno BETWEEN 11305205001
AND
11305205060;

Practice Exercise

Simple Views

1. Create a View that holds only the Branch Name. Name the View as BranchNameView

SQL> select * from BranchNameView;


BRANCHNAME
------------------------------
Civil
Computer Science
Electrical
Electronics
Information Technology
Instrumentation
Mechanical
MBA
MCA
9 rows selected.

2. Create a View that holds Student Name, Register Number of student who are in branch
number 2. Name the View as StudentView.
Give alias name for columns as follow
Column Alias Name
Name - Student Name
Registerno - Register Number
SQL> select * from StudentView;
Student Name Register Number ----------------------------
-- ---------------
ABDUL SAMAD 11308205001
PRIYADHARSHINI 11308205062

Note : Use the following command to print Your Register Number in 11 Digit Format
COLUMN "Register Number" format 99999999999

Downloaded by Suganya C (suganyac@srmist.edu.in)


lOMoARcPSD|31391250

Complex Views

3. Create a View that holds Branch Number and Average Mark of Each Branch. Name the view
as AverageMarkView.
Give alias name for columns as follow
Column Alias Name
Avg(Mark) - Average Mark
SQL> select * from AverageMarkView;
BRANCHNO Average Mark
---------- ------------
1 71.5
2 92.6666667
3 90
4 75
5 100
6 85
7 82.5

7 rows selected.
4. Create a View that holds Branch Number Branch Name and Average Mark of Each Branch.
Name the view as AverageBranchMarkView.
Give alias name for columns as follow
Column Alias Name
Avg(Mark) - Average Mark
SQL> select * from AverageBranchMarkView;

BRANCHNO BRANCHNAME Average Mark


---------- ------------------------------ ------------
1 Civil 71.5
2 Computer Science 92.6666667
3 Electrical 90
4 Electronics 75
5 Information Technology 100
6 Instrumentation 85
7 Mechanical 82.5

7 rows selected.
5. Create a View that holds Branch Number, Branch Name and Number of Students in each branch.
Name the view as NOSBranchView.
SQL> select * from NOSBranchView;
BRANCHNO BRANCHNAME Number of Students
---------- ------------------------------ ------------------
1 Civil 2
2 Computer Science 3
3 Electrical 2
4 Electronics 1
5 Information Technology 2

Downloaded by Suganya C (suganyac@srmist.edu.in)


lOMoARcPSD|31391250

6 Instrumentation 2
7 Mechanical 2

7 rows selected.
6. Create a View that holds Student Name, Register Number, Mark and Grade. Name the view as
StudentGradeView
Give alias name for columns as follow
Column Alias Name
Name - Student Name
Registerno - Register Number
Mark - Mark
Grade - Grade
SQL> select * from StudentGradeView;

Student Name Register Number Mark Grade


------------------------------ --------------- ---------- -----
ADITYA KUMAR 11305104001 99 S
AASHA RANI 11308104001 99 S
ABDUL SAMAD 11308205001 100 S
PRIYADHARSHINI 11308205062 100 S
AHAMED THAHA 11308114001 90 A
ABINAYA 11308105001 90 A
ANISH KUMAR 11308107001 90 A
MADHUUSOODHANA 11308105023 90 A
NANDAKUMARAN 11305104061 80 B
MANDYAM HARIKA 11308106061 75 B
AISHWARYA 11308103001 78 B
PRAVEEN 11308114025 75 B
KANIMOZHI 11308107027 80 B

RAMMANOHAR 11308103030 65 C

14 rows selected.

Result

Thus to Create View on tables are successfully completed.

Downloaded by Suganya C (suganyac@srmist.edu.in)


lOMoARcPSD|31391250

Ex. No: 5
Date :

High Level Programming Language Extensions


(Control Structures, Procedures and Functions).

Aim

To write Procedures, Functions to retrieve or manipulate data from the table and to use Control

Structures.

Theory

PL/SQL subprograms

A subprogram is a named block of PL/SQL. There are two types of subprograms in PL/SQL namely
Procedures and Functions. Every subprogram will have a declarative part, an executable part or body, and
an exception handling part, which is optional.

Declarative part contains variable declarations. Body of a subprogram contains executable statements
of SQL and PL/SQL. Statements to handle exceptions are written in exception part.

When client executes a procedure are function, the processing is done in the server. This reduces
network traffic. The subprograms are compiled and stored in the Oracle database as stored programs and
can be invoked whenever required. As they are stored in compiled form when called they only need to be
executed. Hence they save time needed for compilation.

Subprograms provide the following advantages

1. They allow you to write PL/SQL program that meet our


need 2. They allow you to break the program into manageable
modules.
3. They provide reusability and maintainability for the code.

Procedures

Procedure is a subprogram used to perform a specific action. A procedure contains two parts
specification and the body. Procedure specification begins with CREATE and ends with procedure name
or parameters list. Procedures that do not take parameters are written without a parenthesis. The body of
the procedure starts after the keyword IS or AS and ends with keyword END.

Downloaded by Suganya C (suganyac@srmist.edu.in)


lOMoARcPSD|31391250

In the above given syntax things enclosed in between angular brackets (“< > “) are user defined and
those enclosed in square brackets (“[ ]”) are optional.

• OR REPLACE is used to overwrite the procedure with the same name if there is any.
• AUTHID clause is used to decide whether the procedure should execute with invoker (current-user
or person who executes it) or with definer (owner or person created) rights

Example:

SQL> run;

Procedure created.

SQL> execute hello;

Hello… This is my First Procedure

PL/SQL procedure successfully completed.

Downloaded by Suganya C (suganyac@srmist.edu.in)


lOMoARcPSD|31391250

Practice Exercise (Procedures):

1. Create a Procedure to Delete a record from Student table for a given Register Number

(Note: The Oracle dbms_output.put_line procedure allows you to write data to flat file or to
direct your PL/SQL output to a screen.To see the output of DBMS_OUTPUT.PUT_LINE type

SET SERVEROUTPUT ON at the SQL> Prompt)

2. Create a Procedure to Delete a record from Student table for a given Student Name

Functions:

A function is a PL/SQL subprogram, which is used to compute a value. Function is same like a procedure
except for the difference that it have RETURN clause.

The syntax for a function is:

Downloaded by Suganya C (suganyac@srmist.edu.in)


lOMoARcPSD|31391250

CREATE [OR REPLACE] FUNCTION function_name


[ (parameter [,parameter]) ]
RETURN return_datatype
IS | AS
[declaration_section]
BEGIN
executable_section
[EXCEPTION
exception_section]
END [function_name];

When you create a procedure or function, you may define parameters. There are three types of parameters
that can be declared:

1. IN - The parameter can be referenced by the procedure or function. The value of the parameter can
not be overwritten by the procedure or function.
2. OUT - The parameter can not be referenced by the procedure or function, but the value of the
parameter can be overwritten by the procedure or function.
3. IN OUT - The parameter can be referenced by the procedure or function and the value of the
parameter can be overwritten by the procedure or function.
Practice Exercise (Function) :

1. Write a function to Display Average Mark of the students from the Student table.

Downloaded by Suganya C (suganyac@srmist.edu.in)


lOMoARcPSD|31391250

2. Write a function to Display Mark of a Student with the given Student Register Number.

More about Procedures and Functions

To grant EXECUTE privilege to some user on a procedure we write

GRANT EXECUTE ON <procedure-name> TO <user-name>

SQL> SELECT * FROM USER_PROCEDURES;


Lists all the procedures, functions in current user.

SQL> SELECT * FROM USER_PROCEDURES;


Lists all the procedures, functions in all users.

SQL> DROP PROCEDURE <procedure-name> ;


Drops or Removes a procedure from database

SQL> DROP FUNCTION <function-name> ;


Drops or Removes a function from database
Practice Exercise (Oracle SQL Functions)

1. Write a SQL statement using Rank() function to Display Rank of all the students using Student
table. Display the columns Name, Register Number, Branch Number, Section, Mark and Rank.

2. Write a SQL statement using Rank() function to Display Rank of all the students Branch Wise
using Student table. Display the columns Name, Register Number, Branch Number, Section,
Mark and Rank.

3. Write a SQL statement using Rank() function to Display Rank of all the students Branch,
Section Wise using Student table. Display the columns Name, Register Number, Branch
Number, Section, Mark and Rank.

Downloaded by Suganya C (suganyac@srmist.edu.in)


lOMoARcPSD|31391250

Control Structures:

Control structures in PL/SQL can be divided into selection or conditional, iterative and sequential.
Conditional Control (Selection): This structure tests a condition, depending on the condition is true or false
it decides the sequence of statements to be executed. Example IF – THEN Syntax for IF-THEN-ELSE:

IF THEN

Statements

ELSE

staements

END IF;

Example:
SQL > declare n number; begin
dbms_output.put_line('Enter a number'); n:=&number; if n
> 5 then dbms_output.put_line('Entered Number is Greater
than 5'); else dbms_output.put_line('Entered Number is
Less than 5'); end if; end;

Practice Exercise (Control Structures)

1. Use the Control Structure IF-THEN-ELSE to print Remarks on the Marks Secured by the
Student.

Mark Remarks

> 90 - Excellent
>80 and < 90 - Very Good
>70 and < 80 - Good
>60 and < 80 - Fair
>50 and < 80 - Poor
>44 and < 70 - Very Poor
< 45 - Fail

Downloaded by Suganya C (suganyac@srmist.edu.in)


lOMoARcPSD|31391250

2. Use the Control Structure IF-THEN-ELSE to print Remarks on the Grade Secured by the
Student.

Grade Remarks

S Excellent
A Very Good
B Good
C Fair
D Poor
E Very Poor
U Fail

Downloaded by Suganya C (suganyac@srmist.edu.in)


lOMoARcPSD|31391250

Result

Thus to write Procedures, Functions to retrieve or manipulate data from the table and to use Control

Structures are successfully completed.

Downloaded by Suganya C (suganyac@srmist.edu.in)


lOMoARcPSD|31391250

Ex. No: 6
Date :
Triggers
Aim

To write triggers using Oracle PL/SQL.

Theory

In a DBMS, a trigger is a SQL procedure that initiates an action (i.e., fires an action) when an event
(INSERT, DELETE or UPDATE) occurs. Since triggers are event-driven specialized procedures, they are
stored in and managed by the DBMS. A trigger cannot be called or executed; the DBMS automatically fires
the trigger as a result of a data modification to the associated table.

A trigger can also contain INSERT, UPDATE and DELETE logic within itself, so when the trigger
is fired because of data modification it can also cause another data modification, thereby firing another
trigger. A trigger that contains data modification logic within itself is called a nested trigger.

Syntax

The CREATE TRIGGER command defines and names a trigger that will be stored in the database.

CREATE [ OR REPLACE ] TRIGGER name


{ BEFORE | AFTER } { INSERT | UPDATE | DELETE } [ OR { INSERT | UPDATE | DELETE }
]... ON
table
[ FOR EACH ROW ]
[DECLARE
declarations ]
BEGIN
statements
END;

name is the name of the trigger. If [ OR REPLACE ] is specified and a trigger with the same name already
exists in the schema, the new trigger replaces the existing one. If [ OR REPLACE ] is not specified, the new
trigger will not be allowed to replace an existing one with the same name in the same schema. If BEFORE is
specified, the trigger is defined as a before trigger. If AFTER is specified, the trigger is defined as an after
trigger. One of INSERT, UPDATE, or DELETE must be specified defining the triggering event as an insert,
update, or deletion, respectively. One or both of the remaining triggering event keywords may also be
specified separated by the keyword, OR, in which case these are also defined as triggering events. table is the
name of the table on which a triggering event will cause the trigger to fire. If [ FOR EACH ROW ] is specified,
the trigger is defined as a row-level trigger. If [ FOR EACH ROW ] is omitted, the trigger is defined as a

Downloaded by Suganya C (suganyac@srmist.edu.in)


lOMoARcPSD|31391250

statement-level trigger. declarations are variable, cursor, or type declarations. statements are SPL program
statements. The BEGIN - END block may contain an EXCEPTION section.
Types of Triggers

Oracle supports both row-level and statement-leveltriggers. A row-level trigger fires once for each
row that is affected by a triggering event. For example, if deletion is defined as a triggering event on a table
and a single DELETE command is issued that deletes five rows from the table, then the trigger will fire five
times, once for each row.

In contrast, a statement-level trigger fires once per triggering statement regardless of the number of
rows affected by the triggering event. In the prior example of a single DELETE command deleting five rows,
a statement-level trigger would fire only once.

The sequence of actions can be defined regarding whether the trigger code block is executed before
or after the triggering statement, itself, in the case of statement-level triggers; or before or after each row is
affected by the triggering statement in the case of row-level triggers.

In a before row-level trigger, the trigger code block is executed before the triggering action is carried
out on each affected row. In a before statement-level trigger, the trigger code block is executed before the
action of the triggering statement is carried out.

In an after row-level trigger, the trigger code block is executed after the triggering action is carried
out on each affected row. In an after statement-level trigger, the trigger code block is executed after the
action of the triggering statement is carried out.

Example:
SQL>CREATE OR REPLACE TRIGGER student_alert_trig
BEFORE INSERT ON student
BEGIN
DBMS_OUTPUT.PUT_LINE('New Student Record is about to be added');
END;

Sample Output :
SQL> INSERT INTO Student VALUES('ADITYA KUMAR',11305104005,2,'A','24-JUL-
2005',99,'ADITYAKUMAR@GMAIL.com'); New
Student Record is about to be added 1
row created.

The message, “New Student Record is about to be added”, is displayed once by the firing of the trigger
even though the result is the addition of three new rows.

Downloaded by Suganya C (suganyac@srmist.edu.in)


lOMoARcPSD|31391250

Practice Exercise

1. Write a after statement-level trigger. Whenever an insert, update, or delete operation occurs
on the Student table, a row is added to the Studentauditlog table recording the date, user, and
Action. Name the Trigger as Student_Audit_trig.

Step 1: Create a table Studentauditlog with following Fields

Field Name Data Type

Audit_date Date
Audit_user Varchar2(25)
Audit_desc VARCHAR2(50)

Step 2: Create Trigger Named student_audit_trig

Step 3: Verify Trigger

Downloaded by Suganya C (suganyac@srmist.edu.in)


lOMoARcPSD|31391250

2. Write a Before row-level trigger that displays a message 'New Students are added to Branch
Number 3' before every new student belonging to Branch Number 3 is inserted into the student
table. Name the Trigger as Student_Branch3_trig.

NOTE : Trigger Variables

In the trigger code block, several special variables are available for use.

NEW

NEW is a pseudo-record name that refers to the new table row for insert and update operations in row-level triggers. This
variable is not applicable in statement-level triggers and in delete operations of row-level triggers.

Its usage is: :NEW.column where column is the name of a column in the table on which the trigger is defined.

The initial content of :NEW.column is the value in the named column of the new row to be inserted or of the new row that
is to replace the old one when used in a before row-level trigger. When used in an after row-level trigger, this value has
already been stored in the table since the action has already occurred on the affected row.

In the trigger code block, :NEW.column can be used like any other variable. If a value is assigned to :NEW.column, in the
code block of a before row-level trigger, the assigned value will be used in the new inserted or updated row.

3. Write a Row level Trigger that displays a message prior to Delete operation on the Student table.
Name the Trigger as Student_DeleteAlert_trig.

Result

Thus to write triggers using Oracle PL/SQL is successfully Completed.

Downloaded by Suganya C (suganyac@srmist.edu.in)


lOMoARcPSD|31391250

Ex. No: 7
Date :

Reports.
Aim

To generate Oracle SQL Reports.

Theory

Formatting Columns
Through the SQL*Plus COLUMN command, We can change the column headings and reformat the
column data in our query results.

Changing Column Headings


When displaying column headings, we can either use the default heading or we can change it using
the COLUMN command.
Default Headings
SQL*Plus uses column or expression names as default column headings when displaying query results.
Column names are often short and cryptic, however, and expressions can be hard to understand.
Example :
Registerno
Branchno

Changing Default Headings


We can define a more useful column heading with the HEADING clause of the COLUMN command, in
the following format:

SQL> COLUMN column_name HEADING column_heading

Example 1: Changing a Column Heading


To produce a report from AverageBranchMarkView with new headings specified for branchno and
branchname, enter the following commands:
SQL> COLUMN BRANCHNO HEADING 'Branch Number'
SQL> COLUMN BRANCHNAME HEADING 'Branch Name'
SQL> select * from AverageBranchMarkView;
Branch Number Branch Name Average Mark
------------- ------------------------------ ------------
1 Civil 71.5
2 Computer Science 94.25
3 Electrical 90
4 Electronics 75

Downloaded by Suganya C (suganyac@srmist.edu.in)


lOMoARcPSD|31391250

5 Information Technology 100


6 Instrumentation 85
7 Mechanical 82.5

Example 2: Splitting a Column Heading


To give the columns BRANCHNO ,BRANCHNAME, Average Mark the headings BRANCH
NUMBER, BRANCH NAME, AVERAGEMARK respectively, and to split the new headings onto two
lines, enter
SQL> COLUMN BRANCHNO HEADING 'Branch|Number'
SQL> COLUMN BRANCHNAME HEADING 'Branch|Name'
SQL> COLUMN "Average Mark" HEADING 'Average|Mark'

Now rerun the query with the slash (/) command:


Branch Branch Average
Number Name Mark
---------- ------------------------------ ----------
1 Civil 71.5
2 Computer Science 94.25
3 Electrical 90
4 Electronics 75
5 Information Technology 100
6 Instrumentation 85
7 Mechanical 82.5

Example 3: Setting the Underline Character


To change the character used to underline headings to an equal sign and rerun the query, enter the
following commands:
SQL> SET UNDERLINE =
SQL> /

Now change the underline character back to a dash:


SQL> SET UNDERLINE '-'

Example 4: Formatting a Character Column

To set the width of the column SECTION to 24 characters and rerun the current query, enter
SQL> COLUMN BRANCHNAME FORMAT A24
SQL> select * from AverageBranchMarkView;

Formatting NUMBER Columns

Example 5: Changing the Default Display


The COLUMN command identifies the column you want to format and the model you want to use, as
shown:

Downloaded by Suganya C (suganyac@srmist.edu.in)


lOMoARcPSD|31391250

SQL> COLUMN column_name FORMAT model

To display registerno with 11 digit Number , enter the following command:


SQL> COLUMN registerno FORMAT 99999999999
SQL>select registerno from student;
REGISTERNO
------------
11305104001
11305104061
.
.
.

To display “Average Mark with 2 Decimal Places , enter the following command:
SQL> COLUMN "Average Mark"FORMAT 999.99

Listing and Resetting Column Display Attributes


To list the current display attributes for a given column, use the COLUMN command followed by the
column name only, as shown:
SQL> COLUMN column_name

To list the current display attributes for all columns, enter the COLUMN command with no column
names or clauses after it:
SQL> COLUMN

To reset the display attributes for a column to their default values, use the CLEAR clause of the
COLUMN command as shown:
SQL> COLUMN column_name CLEAR

Example 5:Resetting Column Display Attributes to their Defaults

To reset all column display attributes to their default values, enter:


SQL> CLEAR COLUMNS
columns cleared

Setting the Top and Bottom Titles and Headers and Footers

We can set a title to display at the top of each page of a report. We can also set a title to display at
the
bottom of each page. The TTITLE command defines the top title; the BTITLE command defines the bottom
title. We can also set a header and footer for each report. The REPHEADER command defines the report

header; the REPFOOTER command defines the report footer.

Downloaded by Suganya C (suganyac@srmist.edu.in)


lOMoARcPSD|31391250

A TTITLE, BTITLE, REPHEADER or REPFOOTER command consists of the command name followed
by one or more clauses specifying a position or format and a CHAR value you wish to place in that position
or give that format.

Example 6: Placing a Top and Bottom Title on a Page

To put titles at the top and bottom of each page of a report, enter
TTITLE CENTER "Branch Wise Average Mark"
BTITLE CENTER "Institution Confidential"
Now run the current query:
SQL> select * from AverageBranchMarkView;
Example 7: Placing a Header on a Report

To put a report header on a separate page, and to center it, enter


SQL> REPHEADER PAGE CENTER 'PERFECT REPORTS'

Now run the current query:


SQL> select * from AverageBranchMarkView;

which displays the following two pages of output, with the new REPHEADER displayed on the first
page:
Branch Wise Average Mark
PERFECT REPORTS

Institution Confidential

Branch Wise Average Mark


Branch Branch Average
Number Name Mark
---------- ------------------------------ ----------
1 Civil 71.5
2 Computer Science 94.25
3 Electrical 90
4 Electronics 75
5 Information Technology 100
6 Instrumentation 85
7 Mechanical 82.5

Institution Confidential

Example 8: Displaying the Current Page Number in a Title

To display the current page number at the top of each page, along with the company name, enter the
following command:

SQL> TTITLE LEFT “Branch Wise Average Mark” RIGHT 'PAGE:' SQL.PNO SKIP 2

SQL> select * from AverageBranchMarkView;

Branch Wise Average Mark PAGE: 1

Downloaded by Suganya C (suganyac@srmist.edu.in)


lOMoARcPSD|31391250

PERFECT REPORTS

Institution Confidential

Branch Wise Average Mark PAGE: 2

BRANCHNO BRANCHNAME Average Mark


---------- ------------------------ ------------
1 Civil 71.5 2
Computer Science 94.25 3
Electrical 90
4 Electronics 75
5 Information Technology 100
6 Instrumentation 85
7 Mechanical 82.5

Institution Confidential

Example 9: Sending Results to a File

Next, enter the following commands into the file, using Notepad

Save the file as TEST.SQL

To Execute the SQL File. Enter the following command:


SQL>@"Z:\TEST.SQL"

Note: File Named TEST.SQL should be in the location Z:\

Downloaded by Suganya C (suganyac@srmist.edu.in)


lOMoARcPSD|31391250

Output File :
Branch Wise Average Mark PAGE: 1

PERFECT REPORTS

Institution Confidential

Branch Wise Average Mark PAGE: 2

Branch Branch Average


Number Name Mark
---------- ------------------------------ -------
1 Civil 71.50
2 Computer Science 94.25
3 Electrical 90.00
4 Electronics 75.00
5 Information Technology 100.00
6 Instrumentation 85.00
7 Mechanical 82.50

Institution Confidential

Practice Exercise

1. Use thes NOSBranchView and Create a Report in readable format using SQL *plus
commands. Name the SQL File as Practice1.SQL

2. Use the StudentGradeView and Create a Report in readable format using SQL *plus
commands. Name the SQL File as Practice2.SQL

Note : Make Use of all the Commands to Generate the Report in Neat Format

Result

Thus the reports were created and successfully generated.

Downloaded by Suganya C (suganyac@srmist.edu.in)


lOMoARcPSD|31391250

Ex. No: 8
Date :

Accessing a Relational Database using R.


Aim

To generate Relational Database using R Programming.

Theory
In R programming Language, a number of datasets are passed to the functions to visualize
them using statistical computing. So, rather than creating datasets again and again in the console, we
can pass those normalized datasets from relational databases.
Databases in R Programming Language
R can be connected to many relational databases such as Oracle, MySQL, SQL Server, etc, and
fetches the result as a data frame. Once the result set is fetched into data frame, it becomes very easy
to visualize and manipulate them. In this article, we’ll discuss MySQl as reference to connect with
R, creating, dropping, inserting, updating, and querying the table using R Language.

RMySQL Package
It is a built-in package in R and Its provides connectivity between the R and MySql databases. It can
be installed with the following commands:
install.packages("RMySQL")
Connecting MySQL with R Programming Language
R requires RMySQL package to create a connection object which takes username, password,
hostname and database name while calling the function. dbConnect() function is used to create the
connection object in R.
Syntax: dbConnect(drv, user, password, dbname, host)
Parameter values:
 drv represents Database Driver
 user represents username
 password represents password value assigned to Database server
 dbname represents name of the database
 host represents host name
Example:
 R

# Install package
install.packages("RMySQL")

# Loading library
library("RMySQL")

# Create connection
mysqlconn = dbConnect(MySQL(), user = 'root', password = 'welcome',
dbname = 'GFG', host = 'localhost')

# Show tables in database


dbListTables(mysqlconn)

Tables present in the given database:

Downloaded by Suganya C (suganyac@srmist.edu.in)


lOMoARcPSD|31391250

Output:
Loading required package: DBI
[1] "articles"
Create Tables in MySQL Using R
Tables in MySQL can be created using function dbWriteTable() in R. This function overwrites the
table if table already exists.
Syntax: dbWriteTable(conn, name, value)
Parameter value:
 conn represents connection object
 name represents name of the table in MySQL
 value represents dataframe that has to be presented as MySQL table
Example:
 R

# Create connection object


mysqlconn = dbConnect(MySQL(), user = 'root',
password = 'welcome',
dbname = 'GFG',
host = 'localhost')

# Create new table mtcars


dbWriteTable(mysqlconn, "mtcars",
mtcars[1:10, ],
overwrite = TRUE)

Output:
[1] TRUE
Database table content:

Drop Tables in MySQL Using R


To perform other operations than creating table, dbSendQuery() function is used to execute a query.
Syntax: dbSendQuery(conn, statement)
Parameter values:
Downloaded by Suganya C (suganyac@srmist.edu.in)
lOMoARcPSD|31391250

 conn represents connection object


 statement represents query to be executed in MySQL
Example:
 R

# Create connection object


mysqlconn = dbConnect(MySQL(), user = 'root',
password = 'welcome',
dbname = 'GFG',
host = 'localhost')

# Drop table mtcars from database


dbSendQuery(mysqlconn, 'DROP TABLE mtcars')

Output:
<MySQLResult:745348760, 3, 5>
Database content:

Insert into Table in MySQL Using R


Here we are going to insert a value into a table.
Example:
 R

# Create connection object


mysqlconn = dbConnect(MySQL(), user = 'root',
password = 'welcome',
dbname = 'GFG', host = 'localhost')

# Inserting into articles table


dbSendQuery(mysqlconn, "insert into articles(sno, type)
values(1, 'R language')"
)

Output:
<MySQLResult:745348760, 3, 6>
Database content:

Updating a Table in MySQL Using R


Here we are going to update table in Mysql.
Example:
 R

# Create connection object


mysqlconn = dbConnect(MySQL(), user = 'root',
password = 'welcome',
dbname = 'GFG', host = 'localhost')

Downloaded by Suganya C (suganyac@srmist.edu.in)


lOMoARcPSD|31391250

# Update query
dbSendQuery(mysqlconn, "UPDATE articles SET sno = 10 \
where type = 'R language'")

Output:
<MySQLResult:-1, 3, 7>
Database content:

Querying a Table in MySQL Using R


Here we are going to see how to use query in table.
Example:
 R

# Create connection object


mysqlconn = dbConnect(MySQL(), user = 'root',
password = 'welcome',
dbname = 'GFG', host = 'localhost')

# Select all rows from articles table


res = dbSendQuery(mysqlconn, "SELECT *FROM articles")

# Fetch first 3 rows in data frame


df = fetch(res, n = 3)
print(df)

Output:
sno type
1 1 Data Struc
2 2 Algo
3 3 Java
Database content:

Result

Thus the Relational Database using R Programming were created and successfully generated.

Downloaded by Suganya C (suganyac@srmist.edu.in)


lOMoARcPSD|31391250

Ex. No: 9
Date :

Accessing a Relational Database using PHP.


Aim

To generate Relational Database using PHP Programming.

Theory

The CREATE DATABASE statement is used to create a database in MySQL.

The following examples create a database named "myDB":

(MySQLi Object-oriented)
<?php
$servername = "localhost";
$username = "username";
$password = "password";

// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// Create database
$sql = "CREATE DATABASE myDB";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;
}

$conn->close();
?>

(MySQLi Procedural)
<?php
$servername = "localhost";
$username = "username";
$password = "password";

// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());

Downloaded by Suganya C (suganyac@srmist.edu.in)


lOMoARcPSD|31391250

// Create database
$sql = "CREATE DATABASE myDB";
if (mysqli_query($conn, $sql)) {
echo "Database created successfully";
} else {
echo "Error creating database: " . mysqli_error($conn);
}

mysqli_close($conn);
?>

Note: The following PDO example create a database named "myDBPDO":

Example (PDO)
<?php
$servername = "localhost";
$username = "username";
$password = "password";

try {
$conn = new PDO("mysql:host=$servername", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "CREATE DATABASE myDBPDO";
// use exec() because no results are returned
$conn->exec($sql);
echo "Database created successfully<br>";
} catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}

$conn = null;
?>

Note: A great benefit of PDO is that it has exception class to handle any problems that may occur in our
database queries. If an exception is thrown within the try{ } block, the script stops executing and flows
directly to the first catch(){ } block. In the catch block above we echo the SQL statement and the generated
error message.

Result

Thus the Relational Database using PHP were created and successfully generated.

Downloaded by Suganya C (suganyac@srmist.edu.in)


lOMoARcPSD|31391250

Ex. No: 10
Date :

Accessing a Relational Database using Python.


Aim

To generate Relational Database using Python.

Theory

The Python standard for database interfaces is the Python DB-API. Most Python database
interfaces adhere to this standard.
You can choose the right database for your application. Python Database API supports a wide range of
database servers such as −
 GadFly
 mSQL
 MySQL
 PostgreSQL
 Microsoft SQL Server 2000
 Informix
 Interbase
 Oracle
 Sybase
Here is the list of available Python database interfaces: Python Database Interfaces and APIs. You must
download a separate DB API module for each database you need to access. For example, if you need to
access an Oracle database as well as a MySQL database, you must download both the Oracle and the
MySQL database modules.
The DB API provides a minimal standard for working with databases using Python structures and syntax
wherever possible. This API includes the following −
 Importing the API module.
 Acquiring a connection with the database.
 Issuing SQL statements and stored procedures.
 Closing the connection
We would learn all the concepts using MySQL, so let us talk about MySQLdb module.

What is MySQLdb?
MySQLdb is an interface for connecting to a MySQL database server from Python. It implements the
Python Database API v2.0 and is built on top of the MySQL C API.

How do I Install MySQLdb?


Before proceeding, you make sure you have MySQLdb installed on your machine. Just type the following
in your Python script and execute it −
#!/usr/bin/python

import MySQLdb

Downloaded by Suganya C (suganyac@srmist.edu.in)


lOMoARcPSD|31391250

If it produces the following result, then it means MySQLdb module is not installed −
Traceback (most recent call last):
File "test.py", line 3, in <module>
import MySQLdb
ImportError: No module named MySQLdb
To install MySQLdb module, use the following command −
For Ubuntu, use the following command -
$ sudo apt-get install python-pip python-dev libmysqlclient-dev
For Fedora, use the following command -
$ sudo dnf install python python-devel mysql-devel redhat-rpm-config gcc
For Python command prompt, use the following command -
pip install MySQL-python
Note − Make sure you have root privilege to install above module.

Database Connection
Before connecting to a MySQL database, make sure of the followings −
 You have created a database TESTDB.
 You have created a table EMPLOYEE in TESTDB.
 This table has fields FIRST_NAME, LAST_NAME, AGE, SEX and INCOME.
 User ID "testuser" and password "test123" are set to access TESTDB.
 Python module MySQLdb is installed properly on your machine.
 You have gone through MySQL tutorial to understand MySQL Basics.
Example
Following is the example of connecting with MySQL database "TESTDB"
#!/usr/bin/python

import MySQLdb

# Open database connection


db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )

# prepare a cursor object using cursor() method


cursor = db.cursor()

# execute SQL query using execute() method.


cursor.execute("SELECT VERSION()")

# Fetch a single row using fetchone() method.


data = cursor.fetchone()
print "Database version : %s " % data

# disconnect from server


db.close()
While running this script, it is producing the following result in my Linux machine.
Database version : 5.0.45
If a connection is established with the datasource, then a Connection Object is returned and saved
into db for further use, otherwise db is set to None. Next, db object is used to create a cursor object,

Downloaded by Suganya C (suganyac@srmist.edu.in)


lOMoARcPSD|31391250

which in turn is used to execute SQL queries. Finally, before coming out, it ensures that database
connection is closed and resources are released.

Creating Database Table


Once a database connection is established, we are ready to create tables or records into the database tables
using execute method of the created cursor.
Example
Let us create Database table EMPLOYEE −
#!/usr/bin/python

import MySQLdb

# Open database connection


db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )

# prepare a cursor object using cursor() method


cursor = db.cursor()

# Drop table if it already exist using execute() method.


cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")

# Create table as per requirement


sql = """CREATE TABLE EMPLOYEE (
FIRST_NAME CHAR(20) NOT NULL,
LAST_NAME CHAR(20),
AGE INT,
SEX CHAR(1),
INCOME FLOAT )"""

cursor.execute(sql)

# disconnect from server


db.close()

INSERT Operation
It is required when you want to create your records into a database table.
Example
The following example, executes SQL INSERT statement to create a record into EMPLOYEE table −
#!/usr/bin/python

import MySQLdb

# Open database connection


db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )

# prepare a cursor object using cursor() method


cursor = db.cursor()

Downloaded by Suganya C (suganyac@srmist.edu.in)


lOMoARcPSD|31391250

# Prepare SQL query to INSERT a record into the database.


sql = """INSERT INTO EMPLOYEE(FIRST_NAME,
LAST_NAME, AGE, SEX, INCOME)
VALUES ('Mac', 'Mohan', 20, 'M', 2000)"""
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback()

# disconnect from server


db.close()
Above example can be written as follows to create SQL queries dynamically −
#!/usr/bin/python

import MySQLdb

# Open database connection


db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )

# prepare a cursor object using cursor() method


cursor = db.cursor()

# Prepare SQL query to INSERT a record into the database.


sql = "INSERT INTO EMPLOYEE(FIRST_NAME, \
LAST_NAME, AGE, SEX, INCOME) \
VALUES ('%s', '%s', '%d', '%c', '%d' )" % \
('Mac', 'Mohan', 20, 'M', 2000)
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback()

# disconnect from server


db.close()
Example
Following code segment is another form of execution where you can pass parameters directly −
..................................
user_id = "test123"
password = "password"

con.execute('insert into Login values("%s", "%s")' % \


(user_id, password))
..................................

Downloaded by Suganya C (suganyac@srmist.edu.in)


lOMoARcPSD|31391250

READ Operation
READ Operation on any database means to fetch some useful information from the database.
Once our database connection is established, you are ready to make a query into this database. You can
use either fetchone() method to fetch single record or fetchall() method to fetech multiple values from a
database table.
 fetchone() − It fetches the next row of a query result set. A result set is an object that is returned
when a cursor object is used to query a table.
 fetchall() − It fetches all the rows in a result set. If some rows have already been extracted from
the result set, then it retrieves the remaining rows from the result set.
 rowcount − This is a read-only attribute and returns the number of rows that were affected by
an execute() method.
Example
The following procedure queries all the records from EMPLOYEE table having salary more than 1000

#!/usr/bin/python

import MySQLdb

# Open database connection


db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )

# prepare a cursor object using cursor() method


cursor = db.cursor()

sql = "SELECT * FROM EMPLOYEE \


WHERE INCOME > '%d'" % (1000)
try:
# Execute the SQL command
cursor.execute(sql)
# Fetch all the rows in a list of lists.
results = cursor.fetchall()
for row in results:
fname = row[0]
lname = row[1]
age = row[2]
sex = row[3]
income = row[4]
# Now print fetched result
print "fname=%s,lname=%s,age=%d,sex=%s,income=%d" % \
(fname, lname, age, sex, income )
except:
print "Error: unable to fecth data"

# disconnect from server


db.close()
This will produce the following result −
fname=Mac, lname=Mohan, age=20, sex=M, income=2000

Update Operation
Downloaded by Suganya C (suganyac@srmist.edu.in)
lOMoARcPSD|31391250

UPDATE Operation on any database means to update one or more records, which are already available
in the database.
The following procedure updates all the records having SEX as 'M'. Here, we increase AGE of all the
males by one year.
Example
#!/usr/bin/python

import MySQLdb

# Open database connection


db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )

# prepare a cursor object using cursor() method


cursor = db.cursor()

# Prepare SQL query to UPDATE required records


sql = "UPDATE EMPLOYEE SET AGE = AGE + 1
WHERE SEX = '%c'" % ('M')
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback()

# disconnect from server


db.close()

DELETE Operation
DELETE operation is required when you want to delete some records from your database. Following is
the procedure to delete all the records from EMPLOYEE where AGE is more than 20 −
Example
#!/usr/bin/python

import MySQLdb

# Open database connection


db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )

# prepare a cursor object using cursor() method


cursor = db.cursor()

# Prepare SQL query to DELETE required records


sql = "DELETE FROM EMPLOYEE WHERE AGE > '%d'" % (20)
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()

Downloaded by Suganya C (suganyac@srmist.edu.in)


lOMoARcPSD|31391250

except:
# Rollback in case there is any error
db.rollback()

# disconnect from server


db.close()

Performing Transactions
Transactions are a mechanism that ensures data consistency. Transactions have the following four
properties −
 Atomicity − Either a transaction completes or nothing happens at all.
 Consistency − A transaction must start in a consistent state and leave the system in a consistent
state.
 Isolation − Intermediate results of a transaction are not visible outside the current transaction.
 Durability − Once a transaction was committed, the effects are persistent, even after a system
failure.
The Python DB API 2.0 provides two methods to either commit or rollback a transaction.
Example
You already know how to implement transactions. Here is again similar example −
# Prepare SQL query to DELETE required records
sql = "DELETE FROM EMPLOYEE WHERE AGE > '%d'" % (20)
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback()

COMMIT Operation
Commit is the operation, which gives a green signal to database to finalize the changes, and after this
operation, no change can be reverted back.
Here is a simple example to call commit method.
db.commit()

ROLLBACK Operation
If you are not satisfied with one or more of the changes and you want to revert back those changes
completely, then use rollback() method.
Here is a simple example to call rollback() method.
db.rollback()

Disconnecting Database

Downloaded by Suganya C (suganyac@srmist.edu.in)


lOMoARcPSD|31391250

To disconnect Database connection, use close() method.


db.close()
If the connection to a database is closed by the user with the close() method, any outstanding transactions
are rolled back by the DB. However, instead of depending on any of DB lower level implementation
details, your application would be better off calling commit or rollback explicitly.

An XML Document
Let's have a look at this XML document called "shiporder.xml":

<?xml version="1.0" encoding="UTF-8"?>

<shiporder orderid="889923"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="shiporder.xsd">
<orderperson>John Smith</orderperson>
<shipto>
<name>Ola Nordmann</name>
<address>Langgt 23</address>
<city>4000 Stavanger</city>
<country>Norway</country>
</shipto>
<item>
<title>Empire Burlesque</title>
<note>Special Edition</note>
<quantity>1</quantity>
<price>10.90</price>
</item>
<item>
<title>Hide your heart</title>
<quantity>1</quantity>
<price>9.90</price>
</item>
</shiporder>

The XML document above consists of a root element, "shiporder", that contains a required attribute called
"orderid". The "shiporder" element contains three different child elements: "orderperson", "shipto" and
"item". The "item" element appears twice, and it contains a "title", an optional "note" element, a "quantity",
and a "price" element.

The line above: xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" tells the XML parser that this
document should be validated against a schema. The line:
xsi:noNamespaceSchemaLocation="shiporder.xsd" specifies WHERE the schema resides (here it is in the
same folder as "shiporder.xml").

Result

Thus the Relational Database using Python were created and successfully generated.

Downloaded by Suganya C (suganyac@srmist.edu.in)


lOMoARcPSD|31391250

Ex. No: 11
Date :

Extracting XML Documents from Relational Databases.


Aim

To generate Extracting XML Documents from Relational Databases.

Theory

XML Database is used to store huge amount of information in the XML format. As the use of XML is
increasing in every field, it is required to have a secured place to store the XML documents. The data
stored in the database can be queried using XQuery, serialized, and exported into a desired format.

XML Database Types


There are two major types of XML databases −
 XML- enabled
 Native XML (NXD)

XML - Enabled Database


XML enabled database is nothing but the extension provided for the conversion of XML document. This
is a relational database, where data is stored in tables consisting of rows and columns. The tables contain
set of records, which in turn consist of fields.
Native XML Database
Native XML database is based on the container rather than table format. It can store large amount of
XML document and data. Native XML database is queried by the XPath-expressions.
Native XML database has an advantage over the XML-enabled database. It is highly capable to store,
query and maintain the XML document than XML-enabled database.
Example
Following example demonstrates XML database −
<?xml version = "1.0"?>
<contact-info>
<contact1>
<name>Tanmay Patil</name>
<company>TutorialsPoint</company>
<phone>(011) 123-4567</phone>
</contact1>

<contact2>
<name>Manisha Patil</name>
<company>TutorialsPoint</company>

Downloaded by Suganya C (suganyac@srmist.edu.in)


lOMoARcPSD|31391250

<phone>(011) 789-4567</phone>
</contact2>
</contact-info>
Here, a table of contacts is created that holds the records of contacts (contact1 and contact2), which in
turn consists of three entities − name, company and phone.

Result

Thus Extracting XML Documents from Relational Databases were created and successfully
generated.

Ex. No: 12

Downloaded by Suganya C (suganyac@srmist.edu.in)


lOMoARcPSD|31391250

Date :

XML Querying

Aim

To generate XML Querying.

Theory

SQL, you can query only at the column level. That is, you can return an entire XML document
stored in the column, but you cannot query within the document or return fragments of the document.
To query values within an XML document or return fragments of a document, you must use XQuery.

The queries in this lesson use XQuery in an SQL context and SQL in an XQuery context.

Important: XQuery is case sensitive, but SQL is not. Therefore, when using XQuery, carefully specify names
such as table and SQL schema names, which are both uppercase by default. Even in an SQL context, XQuery
expressions remain case sensitive.

Querying in an SQL context


Retrieving entire XML documents
To retrieve all of the XML documents stored in the column named INFO and values from the CID
primary key column, issue the following SELECT statement:
SELECT cid, info FROM customer~
This query returns the two stored XML documents.
Retrieving and filtering XML values
To query within the XML documents in the INFO column, issue the following SELECT statement,
which uses the XMLQUERY function to invoke an XQuery expression:
SELECT XMLQUERY (
'declare default element namespace "http://posample.org";
for $d in $doc/customerinfo
return <out>{$d/name}</out>'
passing INFO as "doc")
FROM Customer as c
WHERE XMLEXISTS ('declare default element namespace "http://posample.org";
$i/customerinfo/addr[city="Toronto"]' passing c.INFO as "i")~

In the XMLQUERY function, a default namespace is first specified. This namespace matches
the namespace of the documents previously inserted. The for clause specifies iteration through
the <customerinfo> elements in each document from the Info column. The INFO column is
specified by using the passing clause, which binds the INFO column to the variable
named doc that is referenced in the for clause. The return clause then constructs an <out>
element, which contains the <name> element from each iteration of the for clause.

The WHERE clause uses the XMLEXISTS predicate to consider only a subset of the
documents in the Info column. This filtering yields only those documents that have a <city>
element (along the path specified) with a value of Toronto.

The SELECT statement returns the following constructed element:


<out xmlns="http://posample.org"><name>Kathy Smith</name></out>
Using db2-fn:sqlquery with parameters

Downloaded by Suganya C (suganyac@srmist.edu.in)


lOMoARcPSD|31391250

To pass a value to the SQL fullselect in the db2-fn:sqlquery function, run the following query:

VALUES XMLQUERY (
'declare default element namespace "http://posample.org";
for $d in db2-fn:sqlquery(
''SELECT INFO FROM CUSTOMER WHERE Cid = parameter(1)'',
$testval)/customerinfo
return <out>{$d/name}</out>'
passing 1000 as "testval" )~

The XMLQUERY function passes the value 1000 to the XQuery expression by using the
identifier testval. The XQuery expression then passes the value to the db2-fn:sqlquery function
by using the PARAMETER scalar function.

The XQuery expression returns the following constructed element:

<out xmlns="http://posample.org">
<name>Kathy Smith</name>
</out>
Querying in an XQuery context
DB2® XQuery offers two built-in functions specifically for use with DB2 databases: db2-
fn:sqlquery and db2-fn:xmlcolumn. db2-fn:sqlquery retrieves a sequence that is the result table of an
SQL fullselect. db2-fn:xmlcolumn retrieves a sequence from an XML column.

If your query invokes an XQuery expression directly, you must prefix it with the case-insensitive
keyword XQUERY.

Note: There are several options that you can set to customize your command-line processor environment,
particularly for displaying the results of an XQuery expression. For example, set the -i option to make the results
from XQuery expressions easier to read, as follows:
UPDATE COMMAND OPTIONS USING i ON~
Retrieving entire XML documents
To retrieve all of the XML documents previously inserted into the INFO column, you can use XQuery
with either db2-fn:xmlcolumn or db2-fn:sqlquery.
Using db2-fn:xmlcolumn
To retrieve all XML documents in the INFO column, run the following query:
XQUERY db2-fn:xmlcolumn ('CUSTOMER.INFO')~

Names in SQL statements are automatically converted to uppercase by default. Therefore, when
you created the CUSTOMER table by using the CREATE TABLE SQL statement, the names
of the table and columns were made uppercase. Because XQuery is case sensitive, you must be
careful to use the correct case when specifying the table and column names when using db2-
fn:xmlcolumn.

This query is equivalent to the SQL query SELECT Info FROM Customer.

Using db2-fn:sqlquery
To retrieve all XML documents in the INFO column, run the following query:
XQUERY db2-fn:sqlquery ('SELECT Info FROM Customer')~

Downloaded by Suganya C (suganyac@srmist.edu.in)


lOMoARcPSD|31391250

You do not have to specify the INFO and CUSTOMER names in uppercase because the
SELECT statement is processed in an SQL context and is therefore not case sensitive.

Retrieving partial XML documents


Instead of retrieving an entire XML document, you can retrieve fragments of the document and filter
on values present in the document by using XQuery with either db2-fn:xmlcolumn or db2-fn:sqlquery.
Using db2-fn:xmlcolumn
To return elements containing <name> nodes for all documents in the Info column that have a <city>
element (along the path specified) with a value of Toronto, run the following query:
XQUERY declare default element namespace "http://posample.org";
for $d in db2-fn:xmlcolumn('CUSTOMER.INFO')/customerinfo
where $d/addr/city="Toronto"
return <out>{$d/name}</out>~
The db2-fn:xmlcolumn function retrieves a sequence from the INFO column of the CUSTOMER
table. The for clause binds the variable $d to each <customerinfo> element in the CUSTOMER.INFO
column. The where clause restricts the items to only those that have a <city> element (along the path
specified) with a value of Toronto. The return clause constructs the returned XML value. This value
is an element <out> that contains the <name> element for all documents that satisfy the condition
specified in the where clause, as follows:
<out xmlns="http://posample.org">
<name>
Kathy Smith
</name>
</out>
Using db2-fn:sqlquery
To issue a fullselect within an XQuery expression, run the following query:
XQUERY declare default element namespace "http://posample.org";
for $d in db2-fn:sqlquery(
'SELECT INFO
FROM CUSTOMER
WHERE Cid < 2000')/customerinfo
where $d/addr/city="Toronto"
return <out>{$d/name}</out>~

In this example, the set of XML documents being queried is first restricted, in the fullselect, by
particular values in the non-XML CID column. This example demonstrates an advantage
of db2-fn:sqlquery: it allows SQL predicates to be applied within an XQuery expression. The
documents that result from the SQL query are then further restricted in the where clause of the
XQuery expression to those documents that have a <city> element (along the path specified)
with a value of Toronto.

The query yields the same results as in the previous example, which used db2-fn:xmlcolumn:
<out xmlns="http://posample.org">
<name>
Kathy Smith
</name>
</out>
Using db2-fn:sqlquery with parameters

To pass a value to the SQL fullselect in the db2-fn:sqlquery function, run the following query:

XQUERY declare default element namespace "http://posample.org";


let $testval := 1000
for $d in db2-fn:sqlquery(

Downloaded by Suganya C (suganyac@srmist.edu.in)


lOMoARcPSD|31391250

'SELECT INFO FROM CUSTOMER WHERE Cid = parameter(1)',


$testval)/customerinfo
return <out>{$d/name}</out>~

In the XQuery expression, the let clause sets the value of $testval to 1000. In the for clause, the
expression then passes the value to the db2-fn:sqlquery function using the PARAMETER scalar
function.

The XQuery expression returns the following constructed element:

<out xmlns="http://posample.org">
<name>Kathy Smith</name>
</out>

Result

Thus XML Querying were created and successfully generated.

Downloaded by Suganya C (suganyac@srmist.edu.in)


lOMoARcPSD|31391250

Ex. No: 13
Date :

CREATING DATABASES USING MONGODB

Aim

To generate Creating Databases using MongoDB.

Theory

From your cluster page, click on “Browse Collections.”

If there are no databases in this cluster, you will be presented with the option to create your first
database by clicking on the “Add My Own Data” button.

This will open up a modal, asking you for a database name and collection name. Once these fields are
filled, click on “Create” and your database will be created for you.

Downloaded by Suganya C (suganyac@srmist.edu.in)


lOMoARcPSD|31391250

The database is now available to you. You can manually enter new documents, or connect to the
database using any of the MongoDB drivers.

Using the MongoDB Shell


Like most complex software systems, MongoDB can be controlled with what is called a command-line
interface, often referred to as a CLI.

By entering commands into the CLI, you tell MongoDB how to operate, get information about how the
MongoDB cluster is running, and perform fundamental actions like the one we will cover today:
creating a database.

To create a database using a command-line interface, the first task is to get access to the MongoDB
cluster you are using via the MongoDB Shell. A shell is a program that allows you to enter commands
into a software system.

Prerequisites for using the CLI with MongoDB Atlas


If you are using MongoDB Atlas, the steps to getting a shell are as follows:

 Add your IP to the IP access list for your Atlas project


 Make sure you have a database user on the MongoDB cluster you want to use
 Make sure you have the MongoDB Shell installed on your machine
 Open a terminal emulator, run the mongosh command, and log in to the MongoDB Atlas cluster

Find out more at Connect to Atlas via MongoDB Shell

Prerequisites for using the CLI with a self-managed MongoDB cluster


If you are running a self-managed cluster of MongoDB:

 Make sure the MongoDB self-managed cluster is installed and running on your computer or the
computer you are going to connect to
 Make sure you have a database user on the MongoDB cluster you want to use
 Make sure the MongoDB Shell is installed on your computer
 Open a terminal, run the mongosh command and log in to the MongoDB self-managed cluster

Find out more at Connect to a Deployment from the MongoDB Shell

Creating a MongoDB database with the CLI

Downloaded by Suganya C (suganyac@srmist.edu.in)


lOMoARcPSD|31391250

Once you have access to a cluster via the MongoDB Shell, you can see all the databases in the cluster
that you have access to using the “show” command:
> show dbs
admin 0.000GB
local 0.000GB

Note that admin and local are databases that are part of every MongoDB cluster.

There is no “create” command in the MongoDB Shell. In order to create a database, you will first need
to switch the context to a non-existing database using the use command:
> use myshinynewdb

Note that, for now, only the context has been changed. If you enter the show dbs command, the result
should still be the same:
> show dbs
admin 0.000GB
local 0.000GB

Wait a second. Where’s myshinynewdb?

MongoDB only creates the database when you first store data in that database. This data could be
a collection or a document.

To add a document to your database, use the db.collection.insert() command.


> db.user.insert({name: "Ada Lovelace", age: 205})
WriteResult({ "nInserted" : 1 })

The “user” in the command refers to the collection that the document was being inserted in.

Collections can be created just like databases, by writing a document to them. They can also be created
using the createCollection command.

WriteResult({ "nInserted" : 1 }) indicates that the document was added to the collection.

Now, if you run the show dbs command, you will see your database.
> show dbs
admin 0.000GB
myshinynewdb 0.000GB
local 0.000GB

There’s one more thing.

How did the insert command know to put the data into myshinynewdb?

It turns out that when you entered the use command, then myshinynewdb became the current database
on which commands operate.

To find out which database is the current one, enter the db command:
> db

Downloaded by Suganya C (suganyac@srmist.edu.in)


lOMoARcPSD|31391250

myshinynewdb

The db command displays the name of the current database. To switch to a different database, type the
use command and specify that database.

Using the GUI, MongoDB Compass


Some users would rather work with a GUI to create and update their data and collections. The
MongoDB GUI, Compass, offers additional functionality like data visualization and performance
profiling as well as offering CRUD (create, read, update, delete) access to data, databases, and
collections.

Find out more at MongoDB Compass: The Easiest Way to Manage and Explore Your Data

Prerequisites for using Compass with MongoDB Atlas


If you are using MongoDB Atlas, the steps to getting to Compass are as follows:

 Add your IP to the IP access list for your Atlas project


 Make sure you have a database user on the MongoDB cluster you want to use.
 Make sure you have MongoDB Compass installed. If not, download and install Compass for
your operating system.

Prerequisites for using Compass with a self-managed MongoDB cluster


If you are using self-managed MongoDB:

 Make sure the MongoDB self-managed cluster is installed and running on your machine or
server
 Make sure you have a database user on the MongoDB cluster you want to use Make sure you
have MongoDB Compass installed on your computer. If not, download and install Compass for
your operating system.

Creating a MongoDB database with Compass


The Databases tab in MongoDB Compass has a "Create Database" button.

In MongoDB Compass, you create a database and add its first collection at the same time:

 Click "Create Database" to open the dialog

Downloaded by Suganya C (suganyac@srmist.edu.in)


lOMoARcPSD|31391250

 Enter the name of the database and its first collection


 Click "Create Database"

The next step is to insert one or more documents into your database.

Click on your database’s name to see the collection you created, then click on the collection’s name to
see the Documents tab:

Click the "Add Data" button to insert one or more documents into your collection.

You can add JSON documents one at a time, or add multiple documents in an array by enclosing
comma-separated JSON documents in square brackets, as shown in this example:
[
{ "_id" : 8752, "title" : "Divine Comedy", "author" : "Dante", "copies" : 1 },
{ "_id" : 7000, "title" : "The Odyssey", "author" : "Homer", "copies" : 10 },
{ "_id" : 7020, "title" : "Iliad", "author" : "Homer", "copies" : 10 },
{ "_id" : 8645, "title" : "Eclogues", "author" : "Dante", "copies" : 2 },
{ "_id" : 8751, "title" : "The Banquet", "author" : "Dante", "copies" : 2 }
]

Result

Thus Databases using MongoDB were created and successfully generated

Downloaded by Suganya C (suganyac@srmist.edu.in)


lOMoARcPSD|31391250

Ex. No: 14
Date :

CREATING DATABASES USING Neo4j

Aim

To generate Creating Databases Neo4j

Theory

Neo4j supports the management of multiple databases within the same DBMS. The metadata for these
databases, including the associated security model, is maintained in a special database called
the system database. All multi-database administrative commands must be run against the system database.
These administrative commands are automatically routed to the system database when connected to the
DBMS over Bolt.
The syntax of the database management commands is as follows:
The syntax descriptions use the style from access control.
Table 1. Database management command syntax
Command Syntax
SHOW DATABASE SHOW { DATABASE[S] name | DATABASE[S] | DEFAULT DATABASE
| HOME DATABASE }
[WHERE expression]
SHOW { DATABASE[S] name | DATABASE[S] | DEFAULT DATABASE
| HOME DATABASE }
YIELD { * | field[, ...] } [ORDER BY field[, ...]] [SKIP n] [LIMIT n]
[WHERE expression]
[RETURN field[, ...] [ORDER BY field[, ...]] [SKIP n] [LIMIT n]]
CREATE DATABASE CREATE DATABASE name [IF NOT EXISTS]
[TOPOLOGY n PRIMAR{Y|IES} [m SECONDAR{Y|IES}]]
[OPTIONS "{" option: value[, ...] "}"]
[WAIT [n [SEC[OND[S]]]]|NOWAIT]
CREATE OR REPLACE DATABASE name
[TOPOLOGY n PRIMAR{Y|IES} [m SECONDAR{Y|IES}]]
[OPTIONS "{" option: value[, ...] "}"]
[WAIT [n [SEC[OND[S]]]]|NOWAIT]
CREATE COMPOSITE DATABASE CREATE COMPOSITE DATABASE name [IF NOT EXISTS]
[OPTIONS "{" "}"]
[WAIT [n [SEC[OND[S]]]]|NOWAIT]
CREATE OR REPLACE COMPOSITE DATABASE name
[OPTIONS "{" "}"]
[WAIT [n [SEC[OND[S]]]]|NOWAIT]
ALTER DATABASE ALTER DATABASE name [IF EXISTS]
{
SET ACCESS {READ ONLY | READ WRITE} |
SET TOPOLOGY n PRIMAR{Y|IES} [m SECONDAR{Y|IES}]
}
STOP DATABASE STOP DATABASE name [WAIT [n [SEC[OND[S]]]]|NOWAIT]
START DATABASE START DATABASE name [WAIT [n [SEC[OND[S]]]]|NOWAIT]
DROP DATABASE DROP [COMPOSITE] DATABASE name [IF EXISTS]
[{DUMP|DESTROY} [DATA]] [WAIT [n [SEC[OND[S]]]]|NOWAIT]

Listing databases

Downloaded by Suganya C (suganyac@srmist.edu.in)


lOMoARcPSD|31391250

There are four different commands for listing databases:


 Listing all databases.
 Listing a particular database.
 Listing the default database.
 Listing the home database.
These commands return the following columns:
Table 2. Listing databases output
Column Description
name The name of the database. Default Output
type The type of the database: system, standard, or composite. Default Output
aliases The names of any aliases the database may have. Default Output
access The database access mode, either read-write or read-only. Default Output
A database may be described as read-only when using ALTER
DATABASE … SET ACCESS READ ONLY.
databaseID The database unique ID.
serverID The server instance ID.
address Instance address in a clustered DBMS. The default for a standalone database
is neo4j://localhost:7687. Default Output
role The current role of the database (primary, secondary, unknown). Default Output
writer true for the database node that accepts writes (this node is the leader for this database
in a cluster or this is a standalone instance). Default Output
requestedStatus The expected status of the database. Default Output
currentStatus The actual status of the database. Default Output
error An error message explaining why the database is not in the correct state. Default
Output
default Show if this is the default database for the DBMS. Default Output
Not returned by SHOW HOME DATABASE or SHOW
DEFAULT DATABASE.
home Shown if this is the home database for the current user. Default Output
Not returned by SHOW HOME DATABASE or SHOW
DEFAULT DATABASE.
currentPrimariesCount Number of primaries for this database reported as running currently. It is the same as
the number of rows where role=primary and name=this database.
currentSecondariesCount Number of secondaries for this database reported as running currently. It is the same as
the number of rows where role=secondary and name=this database.
requestedPrimariesCount The requested number of primaries for this database. May be lower than current if the
DBMS is currently reducing the number of copies of the database, or higher if it is
currently increasing the number of copies.
requestedSecondariesCount The requested number of secondaries for this database. May be lower than current if
the DBMS is currently reducing the number of copies of the database, or higher if it is
currently increasing the number of copies.
creationTime The date and time at which the database was created.
lastStartTime The date and time at which the database was last started.
lastStopTime The date and time at which the database was last stopped.
store Information about the storage engine and the store format.
The value is a string formatted as:
{storage engine}-{store format}-{major version}.{minor version}
lastCommittedTxn The ID of the last transaction received.

Downloaded by Suganya C (suganyac@srmist.edu.in)


lOMoARcPSD|31391250

Table 2. Listing databases output


Column Description
replicationLag Number of transactions the current database is behind compared to the database on the
primary instance. The lag is expressed in negative integers. In standalone
environments, the value is always 0.
constituents The names of any constituents the database may have. Default Output

1. SHOW DATABASES
A summary of all available databases can be displayed using the command SHOW DATABASES.
Cypher
Query
Copy to ClipboardRun in Neo4j Browser
SHOW DATABASES
Table 3. Result
name aliases access address role requestedStatus currentStatus error default home
"movies" ["films","motion "read- "localhost:7687" "standalone" "online" "online" "" false false
pictures"] write"
"neo4j" [] "read- "localhost:7687" "standalone" "online" "online" "" true true
write"
"system" [] "read- "localhost:7687" "standalone" "online" "online" "" false false
write"
Rows: 3
The results of this command are filtered according to the ACCESS privileges of the user. However, some privileges
enable users to see additional databases regardless of their ACCESS privileges:
 Users with CREATE/DROP/ALTER DATABASE or SET DATABASE ACCESS privileges can see all standard
databases.
 Users with CREATE/DROP COMPOSITE DATABASE or COMPOSITE DATABASE MANAGEMENT privileges
can see all composite databases.
 Users with DATABASE MANAGEMENT privilege can see all databases.
If a user has not been granted ACCESS privilege to any databases nor any of the above special cases, the command
can still be executed but will only return the system database, which is always visible.
Databases hosted on servers that are offline are also returned by the SHOW DATABASES command. For such
databases, the address column displays NULL, the currentStatus column displays unknown, and
the statusMessage displays Server is unavailable.

2. SHOW DATABASES
In this example, the detailed information for a particular database can be displayed using the
command SHOW DATABASE name YIELD *. When a YIELD clause is provided, the full set of columns is
returned.
Cypher
Query
Copy to ClipboardRun in Neo4j Browser
SHOW DATABASE movies YIELD *
Table 4. Result
name aliases access databaseID
"movies" ["films","motion "read- "367221F9021C00CEBFCA25C8E2101F1DCF45C7DB9BF7D7A0949B87745E760E
pictures"] write"

Rows: 1

3. SHOW DATABASES
The number of databases can be seen using a count() aggregation with YIELD and RETURN.

Downloaded by Suganya C (suganyac@srmist.edu.in)


lOMoARcPSD|31391250

Cypher
Query
Copy to ClipboardRun in Neo4j Browser
SHOW DATABASES YIELD *
RETURN count(*) AS count
Table 5. Result
count
3
Rows: 1

4. SHOW DEFAULT DATABASE


The default database can be seen using the command SHOW DEFAULT DATABASE.
Cypher
Query
Copy to ClipboardRun in Neo4j Browser
SHOW DEFAULT DATABASE
Table 6. Result
name aliases access address role requestedStatus currentStatus error
"neo4j" [] "read-write" "localhost:7687" "standalone" "online" "online" ""
Rows: 1

5. SHOW HOME DATABASE


The home database for the current user can be seen using the command SHOW HOME DATABASE.
Cypher
Query
Copy to ClipboardRun in Neo4j Browser
SHOW HOME DATABASE
Table 7. Result
name aliases access address role requestedStatus currentStatus error
"neo4j" [] "read-write" "localhost:7687" "standalone" "online" "online" ""
Rows: 1

6. SHOW DATABASES
It is also possible to filter and sort the results by using YIELD, ORDER BY, and WHERE.
Cypher
Query
Copy to ClipboardRun in Neo4j Browser
SHOW DATABASES YIELD name, currentStatus, requestedStatus
ORDER BY currentStatus
WHERE name CONTAINS 'e'
In this example:
 The number of columns returned has been reduced with the YIELD clause.
 The order of the returned columns has been changed.
 The results have been filtered to only show database names containing 'e'.
 The results are ordered by the currentStatus column using ORDER BY.
It is also possible to use SKIP and LIMIT to paginate the results.
Table 8. Result
name currentStatus requestedStatus
"movies" "online" "online"
"neo4j" "online" "online"
"system" "online" "online"
Rows: 3
Note that for failed databases, the currentStatus and requestedStatus are different. This often implies an error,
but does not always. For example, a database may take a while to transition from offline to online due to
Downloaded by Suganya C (suganyac@srmist.edu.in)
lOMoARcPSD|31391250

performing recovery. Or, during normal operation a database’s currentStatus may be transiently different from
its requestedStatus due to a necessary automatic process, such as one Neo4j instance copying store files from
another. The possible statuses are initial, online, offline, store copying and unknown.
For composite databases the constituents column is particularly interesting as it lists the aliases that make up
the composite database:
Cypher
Query
Copy to ClipboardRun in Neo4j Browser
SHOW DATABASE library YIELD name, constituents
Table 9. Result
name constituents
"library" ["library.sci-fi","library.romance"]
Rows: 1

Creating databases
Databases can be created using CREATE DATABASE.

7. CREATE DATABASE
Cypher
Query
Copy to ClipboardRun in Neo4j Browser
CREATE DATABASE customers
Result
System updates: 1
Rows: 0
Database names are subject to the standard Cypher restrictions on valid identifiers.
The following naming rules apply:
 Database name length must be between 3 and 63 characters.
 The first character must be an ASCII alphabetic character.
 Subsequent characters can be ASCII alphabetic (mydatabase), numeric characters (mydatabase2), dots (main.db),
and dashes (enclosed within backticks, e.g., CREATE DATABASE `main-db`). Using database names with dots
without enclosing them in backticks is deprecated.
 Names cannot end with dots or dashes.
 Names that begin with an underscore or with the prefix system are reserved for internal use.

8.SHOW DATABASES
When a database has been created, it will show up in the listing provided by the command SHOW
DATABASES.
Cypher
Query
Copy to ClipboardRun in Neo4j Browser
SHOW DATABASES
Table 10. Result
name aliases access address role requestedStatus currentStatus error default home
"customers" [] "read- "localhost:7687" "standalone" "online" "online" "" false false
write"
"movies" ["films","motion "read- "localhost:7687" "standalone" "online" "online" "" false false
pictures"] write"
"neo4j" [] "read- "localhost:7687" "standalone" "online" "online" "" true true
write"
"system" [] "read- "localhost:7687" "standalone" "online" "online" "" false false
write"
Rows: 4

Downloaded by Suganya C (suganyac@srmist.edu.in)


lOMoARcPSD|31391250

Cluster topology

In a cluster environment, it may be desirable to control the number of servers used to host a database. The
number of primary and secondary servers can be specified using the following command.
Cypher
Query
Copy to ClipboardRun in Neo4j Browser
CREATE DATABASE `topology-example` TOPOLOGY 1 PRIMARY 0 SECONDARIES
For more details on primary and secondary server roles, see Cluster overview.
TOPOLOGY is only available for standard databases and not composite databases. Composite databases are always
available on all servers.

Creating composite databases

Composite databases do not contain data, but they reference to other databases that can be queried together
through their constituent aliases. For more information about composite databases, see Operations Manual
→ Composite database introduction.
Composite databases can be created using CREATE COMPOSITE DATABASE.
Cypher
Query
Copy to ClipboardRun in Neo4j Browser
CREATE COMPOSITE DATABASE inventory
0 rows, System updates: 1
Composite database names are subject to the same rules as standard databases. One difference is however that the
deprecated syntax using dots without enclosing the name in backticks is not available. Both dots and dashes needs to
enclosed within backticks when using composite databases.
When a composite database has been created, it will show up in the listing provided by the
command SHOW DATABASES.
Cypher
Query
Copy to ClipboardRun in Neo4j Browser
SHOW DATABASES YIELD name, type, access, role, writer, constituents
Table 11. Result
name type access role writer constituents
"customers" "standard" "read-write" "primary" true []
"inventory" "composite" "read-only" <null> false []
"library" "composite" "read-only" <null> false ["library.sci-fi","library.romance"]
"movies" "standard" "read-write" "primary" true []
"neo4j" "standard" "read-write" "primary" true []
"sci-fi-books" "standard" "read-write" "primary" true []
"system" "system" "read-write" "primary" true []
"topology-example" "standard" "read-write" "primary" true []
Rows: 8
In order to create database aliases in the composite database, give the composite database as namespace for
the alias. For information about creating aliases in composite databases, see here.

Handling Existing Databases

These commands are optionally idempotent, with the default behavior to fail with an error if the database
already exists. Appending IF NOT EXISTS to the command ensures that no error is returned and nothing
happens should the database already exist. Adding OR REPLACE to the command will result in any
existing database being deleted and a new one created.
These behavior flags apply to both standard and composite databases (e.g. a composite database may
replace a standard one or another composite.)

Downloaded by Suganya C (suganyac@srmist.edu.in)


lOMoARcPSD|31391250

9. CREATE DATABASE
Cypher
Query
Copy to ClipboardRun in Neo4j Browser
CREATE COMPOSITE DATABASE customers IF NOT EXISTS

10.CREATE OR REPLACE DATABASE


Cypher
Query
Copy to ClipboardRun in Neo4j Browser
CREATE OR REPLACE DATABASE customers
This is equivalent to running DROP DATABASE customers IF EXISTS followed by CREATE DATABASE
customers.
The IF NOT EXISTS and OR REPLACE parts of these commands cannot be used together.

Options

The CREATE DATABASE command can have a map of options, e.g. OPTIONS {key: 'value'}.
There are no available OPTIONS values for composite databases.
Key Value Description
existingData use Controls how the system handles existing data on disk when
creating the database. Currently this is only supported
with existingDataSeedInstance and must be set to use which
indicates the existing data files should be used for the new
database.
existingDataSeedInstance instance ID of the Defines which instance is used for seeding the data of the created
cluster node database. The instance id can be taken from the id column of
the dbms.cluster.overview() procedure. Can only be used in
clusters.
seedURI URI to a backup or Defines an identical seed from an external source which will be
a dump from an used to seed all servers.
existing database.
seedConfig comma separated Defines additional configuration specified by comma
list of separated name=value pairs that might be required by certain seed
configuration providers.
values.
seedCredentials credentials Defines credentials that needs to be passed into certain seed
providers.
The existingData, existingDataSeedInstance, seedURI, seedConfig and seedCredentials options cannot be combined
with the OR REPLACE part of this command. For details about the use of these seeding options, see Operations
Manual → Seed a cluster.

Altering databases
Standard databases can be modified using the command ALTER DATABASE.

Access

By default, a database has read-write access mode on creation. The database can be limited to read-only
mode on creation using the configuration
parameters dbms.databases.default_to_read_only, dbms.databases.read_only, and dbms.database.writable. For
details, see Configuration parameters.

Downloaded by Suganya C (suganyac@srmist.edu.in)


lOMoARcPSD|31391250

A database that was created with read-write access mode can be changed to read-only. To change it to read-
only, you can use the ALTER DATABASE command with the sub-clause SET ACCESS READ ONLY.
Subsequently, the database access mode can be switched back to read-write using the sub-clause SET
ACCESS READ WRITE. Altering the database access mode is allowed at all times, whether a database is
online or offline.
If conflicting modes are set by the ALTER DATABASE command and the configuration parameters, i.e.
one says read-write and the other read-only, the database will be read-only and prevent write queries.
Modifying access mode is only available to standard databases and not composite databases.

11. ALTER DATABASE


Cypher
Query
Copy to ClipboardRun in Neo4j Browser
ALTER DATABASE customers SET ACCESS READ ONLY
Result
System updates: 1
Rows: 0

12. SHOW DATABASES


The database access mode can be seen in the access output column of the command SHOW DATABASES.
Cypher
Query
Copy to ClipboardRun in Neo4j Browser
SHOW DATABASES yield name, access
Table 12. Result
name access
"customers" "read-only"
"movies" "read-write"
"neo4j" "read-write"
"system" "read-write"
Rows: 4

13. ALTER DATABASE


ALTER DATABASE commands are optionally idempotent, with the default behavior to fail with an error if
the database does not exist. Appending IF EXISTS to the command ensures that no error is returned and
nothing happens should the database not exist.
Cypher
Query
Copy to ClipboardRun in Neo4j Browser
ALTER DATABASE nonExisting IF EXISTS
SET ACCESS READ WRITE

Topology

In a cluster environment, it may be desirable to change the number of servers used to host a database. The
number of primary and secondary servers can be specified using the following command:

14. ALTER DATABASE


Cypher
Query
Copy to ClipboardRun in Neo4j Browser
ALTER DATABASE `topology-example`
SET TOPOLOGY 3 PRIMARY 0 SECONDARIES
It is not possible to automatically transition to or from a topology with a single primary host. See the Operations
Manual → Alter topology for more information.

15.SHOW DATABASE

Downloaded by Suganya C (suganyac@srmist.edu.in)


lOMoARcPSD|31391250

Cypher
Query
Copy to ClipboardRun in Neo4j Browser
SHOW DATABASES yield name, currentPrimariesCount, currentSecondariesCount, requestedPrimariesCount,
requestedSecondariesCount
For more details on primary and secondary server roles, see Operations Manual → Clustering overview.
Modifying database topology is only available to standard databases and not composite databases.
ALTER DATABASE commands are optionally idempotent, with the default behavior to fail with an error if
the database does not exist. Appending IF EXISTS to the command ensures that no error is returned and
nothing happens should the database not exist.
Cypher
Query
Copy to ClipboardRun in Neo4j Browser
ALTER DATABASE nonExisting IF EXISTS SET TOPOLOGY 1 PRIMARY 0 SECONDARY
0 rows

Stopping databases
Databases can be stopped using the command STOP DATABASE.

16. STOP DATABASE


Cypher
Query
Copy to ClipboardRun in Neo4j Browser
STOP DATABASE customers
Result
System updates: 1
Rows: 0
Both standard databases and composite databases can be stopped using this command.

17.SHOW DATABASE
The status of the stopped database can be seen using the command SHOW DATABASE name.
Cypher
Query
Copy to ClipboardRun in Neo4j Browser
SHOW DATABASE customers
Table 13. Result
name aliases access address role requestedStatus currentStatus error default home
"customers" [] "read-only" "localhost:7687" "standalone" "offline" "offline" "" false false
Rows: 1

Starting databases
Databases can be started using the command START DATABASE.

18.START DATABASE
Cypher
Query
Copy to ClipboardRun in Neo4j Browser
START DATABASE customers
Result
System updates: 1
Rows: 0
Both standard databases and composite databases can be stopped using this command.

19.SHOW DATABASE
The status of the started database can be seen using the command SHOW DATABASE name.

Downloaded by Suganya C (suganyac@srmist.edu.in)


lOMoARcPSD|31391250

Cypher
Query
Copy to ClipboardRun in Neo4j Browser
SHOW DATABASE customers
Table 14. Result
name aliases access address role requestedStatus currentStatus error default home
"customers" [] "read-only" "localhost:7687" "standalone" "online" "online" "" false false
Rows: 1

Deleting databases
Standard and composite databases can be deleted by using the command DROP DATABASE.

20.DROP DATABASE
Cypher
Query
Copy to ClipboardRun in Neo4j Browser
DROP DATABASE customers
Result
System updates: 1
Rows: 0
It is also possible to ensure that only composite databases are dropped. A DROP COMPOSITE request
would then fail if the targeted database is a standard database.

21.SHOW DATABASES
When a database has been deleted, it will no longer show up in the listing provided by the command SHOW
DATABASES.
Cypher
Query
Copy to ClipboardRun in Neo4j Browser
SHOW DATABASES
Table 15. Result
name aliases access address role requestedStatus currentStatus error default home
"movies" ["films","motion "read- "localhost:7687" "standalone" "online" "online" "" false false
pictures"] write"
"neo4j" [] "read- "localhost:7687" "standalone" "online" "online" "" true true
write"
"system" [] "read- "localhost:7687" "standalone" "online" "online" "" false false
write"
Rows: 3

22.DROP DATABASE
This command is optionally idempotent, with the default behavior to fail with an error if the database does
not exist. Appending IF EXISTS to the command ensures that no error is returned and nothing happens
should the database not exist. It will always return an error, if there is an existing alias that targets the
database. In that case, the alias needs to be dropped before dropping the database.
Cypher
Query
Copy to ClipboardRun in Neo4j Browser
DROP DATABASE customers IF EXISTS
The DROP DATABASE command will remove a database entirely.

23.DROP DATABASE
You can request that a dump of the store files is produced first, and stored in the path configured using
the dbms.directories.dumps.root setting (by default <neo4j-home>/data/dumps). This can be achieved by
appending DUMP DATA to the command (or DESTROY DATA to explicitly request the default behavior).

Downloaded by Suganya C (suganyac@srmist.edu.in)


lOMoARcPSD|31391250

These dumps are equivalent to those produced by neo4j-admin dump and can be similarly restored
using neo4j-admin load.
Cypher
Query
Copy to ClipboardRun in Neo4j Browser
DROP DATABASE customers DUMP DATA
The options IF EXISTS and DUMP DATA/ DESTROY DATA can also be combined. An example could
look like this:
Cypher
Query
Copy to ClipboardRun in Neo4j Browser
DROP DATABASE customers IF EXISTS DUMP DATA
It is also possible to ensure that only composite databases are dropped. A DROP COMPOSITE request
would then fail if the targeted database is a standard database.

24.DROP COMPOSITE DATABASE


Cypher
Query
Copy to ClipboardRun in Neo4j Browser
DROP COMPOSITE DATABASE inventory
0 rows, System updates: 1
To ensure the database to be dropped is standard and not composite, the user first needs to check
the type column of SHOW DATABASES manually.

25. CREATE DATABASE


Cypher
Query
Copy to ClipboardRun in Neo4j Browser
CREATE DATABASE slow WAIT 5 SECONDS
Table 16. Result
address state message success
"localhost:7687" "CaughtUp" "caught up" true
Rows: 1
The success column provides an aggregate status of whether or not the command is considered successful
and thus every row will have the same value. The intention of this column is to make it easy to determine,
for example in a script, whether or not the command completed successfully without timing out.
A command with a WAIT clause may be interrupted whilst it is waiting to complete. In this event the
command will continue to execute in the background and will not be aborted.

Result

Thus Databases Neo4j were created and successfully generated

Downloaded by Suganya C (suganyac@srmist.edu.in)

You might also like