cp4152 Database Practices Lab
cp4152 Database Practices Lab
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
CREATE COMMAND
Syntax
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:
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:
Result
Thus the SQL Statements using Data Definition Language (DDL) to Create Table with Constraints
is successfully Implemented.
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 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:
Note :
Use the following command to print Your Register Number in 11 Digit Format
SQL >COLUMN registerno FORMAT 99999999999
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.
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.
A HAVING statement in SQL specifies that a SQL SELECT statement should only
return rows where aggregate values meet the specified conditions.
Example:
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:
• 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.
Syntax:
INSERT INTO table (column1, [column2, ... ]) 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')
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:
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!
The DELETE statement does not return any rows; that is, it will not generate a result set.
Example :
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
8 MBA
9 MCA
9 rows selected.
14 rows selected.
7 rows selected.
9. Display the detail of grade for the mark between 81 and 90.
GRADE LOWMARK HIGHMARK
7 rows selected.78 8
99 9
90 17
75 17
100 17
90 35
7 rows selected.
14. Display the Maximum mark of branch where Maximum Mark greater than 90.
Maximum Marks BRANCHNO
------------- ----------
99 2
100 5
15. Display the Name, Register Number, E-Mail ID and Join Date of Students who have joined later
Commit;
14 rows selected.
Note : Display the Details from Student Table. Check for Updation, Undo the Update Operation and make the changes Permanent.
Rollback;
Commit;
Note : Display the Details from Student Table. Check for Updation and make the changes Permanent.
Commit;
Permanent.
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
Ex. No: 3
Date :
Nested Queries and & Join Queries
Aim
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:
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
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.
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.
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
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.
Ex. No: 4
Date :
Views
Aim
Theory
Syntax
Simple views, which contain a subquery that retrieves from one base table
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
To create a view use the create view command as seen in this example
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 (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
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
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;
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
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;
RAMMANOHAR 11308103030 65 C
14 rows selected.
Result
Ex. No: 5
Date :
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.
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.
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.
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
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.
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.
2. Write a function to Display Mark of a Student with the given Student Register Number.
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.
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;
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
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
Result
Thus to write Procedures, Functions to retrieve or manipulate data from the table and to use Control
Ex. No: 6
Date :
Triggers
Aim
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.
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
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.
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.
Audit_date Date
Audit_user Varchar2(25)
Audit_desc VARCHAR2(50)
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.
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
Ex. No: 7
Date :
Reports.
Aim
Theory
Formatting Columns
Through the SQL*Plus COLUMN command, We can change the column headings and reformat the
column data in our query results.
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;
To display “Average Mark with 2 Decimal Places , enter the following command:
SQL> COLUMN "Average Mark"FORMAT 999.99
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
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
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.
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
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
Institution Confidential
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
PERFECT REPORTS
Institution Confidential
Institution Confidential
Next, enter the following commands into the file, using Notepad
Output File :
Branch Wise Average Mark PAGE: 1
PERFECT REPORTS
Institution Confidential
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
Ex. No: 8
Date :
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')
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
Output:
[1] TRUE
Database table content:
Output:
<MySQLResult:745348760, 3, 5>
Database content:
Output:
<MySQLResult:745348760, 3, 6>
Database content:
# Update query
dbSendQuery(mysqlconn, "UPDATE articles SET sno = 10 \
where type = 'R language'")
Output:
<MySQLResult:-1, 3, 7>
Database content:
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.
Ex. No: 9
Date :
Theory
(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());
// 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);
?>
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.
Ex. No: 10
Date :
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.
import MySQLdb
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
which in turn is used to execute SQL queries. Finally, before coming out, it ensures that database
connection is closed and resources are released.
import MySQLdb
cursor.execute(sql)
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
import MySQLdb
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
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
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
except:
# Rollback in case there is any error
db.rollback()
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
An XML Document
Let's have a look at this XML document called "shiporder.xml":
<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.
Ex. No: 11
Date :
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.
<contact2>
<name>Manisha Patil</name>
<company>TutorialsPoint</company>
<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
Date :
XML Querying
Aim
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.
In the XMLQUERY function, a default namespace is first specified. This namespace matches
the namespace of the documents previously inserted. The for clause specifies iteration through
the <customerinfo> elements in each document from the Info column. The INFO column is
specified by using the passing clause, which binds the INFO column to the variable
named doc that is referenced in the for clause. The return clause then constructs an <out>
element, which contains the <name> element from each iteration of the for clause.
The WHERE clause uses the XMLEXISTS predicate to consider only a subset of the
documents in the Info column. This filtering yields only those documents that have a <city>
element (along the path specified) with a value of Toronto.
To pass a value to the SQL fullselect in the db2-fn:sqlquery function, run the following query:
VALUES XMLQUERY (
'declare default element namespace "http://posample.org";
for $d in db2-fn:sqlquery(
''SELECT INFO FROM CUSTOMER WHERE Cid = parameter(1)'',
$testval)/customerinfo
return <out>{$d/name}</out>'
passing 1000 as "testval" )~
The XMLQUERY function passes the value 1000 to the XQuery expression by using the
identifier testval. The XQuery expression then passes the value to the db2-fn:sqlquery function
by using the PARAMETER scalar function.
<out xmlns="http://posample.org">
<name>Kathy Smith</name>
</out>
Querying in an XQuery context
DB2® XQuery offers two built-in functions specifically for use with DB2 databases: db2-
fn:sqlquery and db2-fn:xmlcolumn. db2-fn:sqlquery retrieves a sequence that is the result table of an
SQL fullselect. db2-fn:xmlcolumn retrieves a sequence from an XML column.
If your query invokes an XQuery expression directly, you must prefix it with the case-insensitive
keyword XQUERY.
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')~
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.
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:
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.
<out xmlns="http://posample.org">
<name>Kathy Smith</name>
</out>
Result
Ex. No: 13
Date :
Aim
Theory
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.
The database is now available to you. You can manually enter new documents, or connect to the
database using any of the MongoDB drivers.
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.
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
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
MongoDB only creates the database when you first store data in that database. This data could be
a collection or a document.
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
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
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.
Find out more at MongoDB Compass: The Easiest Way to Manage and Explore Your Data
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.
In MongoDB Compass, you create a database and add its first collection at the same time:
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
Ex. No: 14
Date :
Aim
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
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.
Cypher
Query
Copy to ClipboardRun in Neo4j Browser
SHOW DATABASES YIELD *
RETURN count(*) AS count
Table 5. Result
count
3
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
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.
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.
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.)
9. CREATE DATABASE
Cypher
Query
Copy to ClipboardRun in Neo4j Browser
CREATE COMPOSITE DATABASE customers IF NOT EXISTS
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.
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.
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:
15.SHOW DATABASE
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.
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.
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).
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.
Result