Database practices lab Record NEW
Database practices lab Record NEW
ENGINEERING
SEMESTER I
BONAFIDE CERTIFICATE
2. a
2. b
2. c
2. d
2. e
4. a
4. b
10
11
EX NO:1 Data Definition Language
AIM:
PROCEDURE:
Queries:
+ +
| Database |
+ +
| information_schema |
| AMROOD |
| mysql |
| orig |
| test |
| Banking |
+ +
Creating table:
Example:
ALTER TABLE Customers
ADD Email varchar(255);
Syntax (Drop column):
ALTER TABLE table_name
DROP COLUMN column_name;
Example:
ALTER TABLE Customers
DROP COLUMN Email;
Drop Table:
Syntax:
DROP TABLE table_name;
Example:
SQL> DROP TABLE CUSTOMERS;
Query OK, 0 rows affected (0.01 sec)
Drop DB:
Syntax:
DROP DATABASE DatabaseName;
Example:
SQL> DROP DATABASE Banking;
ii) Enforce Primary Key, Foreign Key, Check, Unique and Not Null Constraints
Syntax: (Setting primary key and NOT NULL):
CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);
Foreign key:
Example
Consider the structure of the following two tables.
CUSTOMERS table
CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);
ORDERS table
CREATE TABLE ORDERS (
ID INT NOT NULL,
DATE DATETIME,
CUSTOMER_ID INT references CUSTOMERS(ID),
AMOUNT double,
PRIMARY KEY (ID)
);
If the ORDERS table has already been created and the foreign key has not yet been set, the use the
syntax for specifying a foreign key by altering a table.
ALTER TABLE ORDERS
ADD FOREIGN KEY (Customer_ID) REFERENCES CUSTOMERS (ID);
Unique:
CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL UNIQUE,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);
the AGE column is set to UNIQUE, so that you cannot have two records with the same age.
Check:
CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL CHECK (AGE >= 18),
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);
Added a CHECK with AGE column, so that you cannot have any CUSTOMER who is below 18
years.
iii) Views:
CREATE VIEW:
Syntax:
CREATE VIEW view_name AS
SELECT column1, column2.....
FROM table_name
WHERE [condition];
Example:
CUSTOMERS table having the following records
create a view from the CUSTOMERS table. This view would be used to have customer name and age
from the CUSTOMERS table.
SQL > CREATE VIEW CUSTOMERS_VIEW AS
SELECT name, age
FROM CUSTOMERS;
Result:
EX NO:2 a Data Manipulation Language - Insert, Delete, Update
Aim
Procedure:
Queries:
Insert:
Syntax:
INSERT INTO TABLE_NAME (column1, column2, column3,...columnN)
VALUES (value1, value2, value3,...valueN);
Example:
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (1, 'Ramesh', 32, 'Ahmedabad', 2000.00 );
Delete:
Syntax:
DELETE FROM table_name
WHERE [condition];
Example:
SQL> DELETE FROM CUSTOMERS
WHERE ID = 6;
Update:
Syntax:
UPDATE table_name
SET column1 = value1, column2 = value2. .. , columnN = valueN
WHERE [condition];
Example:
SQL> UPDATE CUSTOMERS
SET ADDRESS = 'Pune'
WHERE ID = 6;
Aim
Procedure:
CARTESIAN JOIN or CROSS JOIN:
Syntax:
Example:
LEFT JOIN
Syntax:
SELECT table1.column1, table2.column2...
FROM table1
LEFT JOIN table2
ON table1.common_field = table2.common_field;
Example
SQL> SELECT ID, NAME, AMOUNT, DATE
FROM CUSTOMERS
LEFT JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;
Right Join:
Syntax:
SELECT table1.column1, table2.column2...
FROM table1
RIGHT JOIN table2
ON table1.common_field = table2.common_field;
Example:
SQL> SELECT ID, NAME, AMOUNT, DATE
FROM CUSTOMERS
RIGHT JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;
Full join:
Syntax:
SELECT table1.column1, table2.column2...
FROM table1
FULL JOIN table2
ON table1.common_field = table2.common_field;
Example
SQL> SELECT ID, NAME, AMOUNT, DATE
FROM CUSTOMERS
FULL JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;
EX NO:2 c Data Manipulation Language – Aggregate functions
Aim
Procedure:
Procedure:
Syntax:
SELECT <FUNCTION NAME> (<PARAMETER>) FROM <TABLE NAME>
Example: table : Employee
AVG Function:
Select AVG(salary) from Employee
AVG(salary)= 16800
COUNT Function:
Select COUNT(*) from Employee where Salary > 20000;
Count(salary)=1
MAX Function:
Select MAX(salary) from Employee;
Max(salary)=30000
SUM Function:
Select SUM(salary) from Employee
SUM (salary)= 84000
EX NO:2 d Data Manipulation Language – Set Operation
Aim
Procedure:
SET Operators in SQL
1. UNION
2. UNION ALL
3. INTERSECT
4. MINUS
Table 1: t_employees
Table 2: t2_employees
Table 4: t2_students
Union:
Syntax:
mysql> SELECT *FROM t_employees UNION SELECT *FROM t2_employees;
ID Name Department Salary Year_of_Experience
Union All:
Syntax:
mysql> SELECT *FROM t_employees UNION ALL SELECT *FROM t2_employees;
Intersect:
Syntax:
mysql> SELECT *FROM t_employees INTERSECT SELECT *FROM t2_employees;
Minus:
Syntax:
mysql> SELECT *FROM t_employees MINUS SELECT *FROM t2_employees;
Aim
Procedure:
Example
Find the names of employee who have regno=103
Student table
The student table is created as follows −
Output
You will get the following output −
1 Pinky 3 2.4
2 Bob 3 1.44
3 Jam 1 3.24
4 Lucky 2 2.67
5 Ram 2 4.56
Teacher table
The teacher table is created as follows −
Example
Create table teacher(id number(10), name varchar(20), subject varchar2(10), classID number(10),
salary number(30));
Insert into teacher values(1,’bhanu’,’computer’,3,5000);
Insert into teacher values(2,'rekha','science',1,5000);
Insert into teacher values(3,'siri','social',NULL,4500);
Insert into teacher values(4,'kittu','mathsr',2,5500);
select * from teacher;
Output
You will get the following output −
Class table
The class table is created as follows −
Example
Output
You will get the following output −
1 8 2 20
2 9 3 40
3 10 1 38
Output
You will get the following output −
20.0
EX NO:3 Transaction Control Language
Aim
Procedure:
Procedure:
Commit, Rollback and Save Points
Commit:
Syntax:
COMMIT;
Example:
ROLLBACK:
Syntax:
Rollback;
AIM:
PROCEDURE:
Syntax:
Output:
2 rows updated
update Employee
set ename=‟Rahul‟
where emp_id=5;
In above example emp_id=5 is not present in the Employee table. But trigger will be fired once and
output will be,
0 rows updated
Result:
EX NO:4 b Triggers – Row Level
AIM:
PROCEDURE:
Syntax:
( emp_id number,
ename varchar2(100)
);
on Employee
begin
end;
The output
The 1=2 is always false condition so this will not execute the trigger.
The output
0 rows updated
EX NO:5 Accessing a Relational Database using Python
AIM:
PROCEDURE:
Connecting with MySQL database "TESTDB"
#!/usr/bin/python
import MySQLdb
#!/usr/bin/python
import MySQLdb
cursor.execute(sql)
Inserting values:
#!/usr/bin/python
import MySQLdb
Queries:
#!/usr/bin/python
import MySQLdb
Output:
fname=Mac, lname=Mohan, age=20, sex=M, income=2000
EX NO: 6 Creating XML Documents, DTD, XML Schema
AIM:
PROCEDURE:
Syntax:
Simple document creation:
Creating DTDs:
Syntax
<!DOCTYPE element DTD identifier
[
declaration1
declaration2
........
]>
Example
<?xml version = "1.0" encoding = "UTF-8" standalone = "yes" ?>
<!DOCTYPE address [
<!ELEMENT address (name,company,phone)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT company (#PCDATA)>
<!ELEMENT phone (#PCDATA)>
]>
<address>
<name>Tanmay Patil</name>
<company>TutorialsPoint</company>
<phone>(011) 123-4567</phone>
</address>
XML Schema:
Example:
<?xml version = "1.0" encoding = "UTF-8"?>
<xs:schema xmlns:xs = "http://www.w3.org/2001/XMLSchema">
<xs:element name = "contact">
<xs:complexType>
<xs:sequence>
<xs:element name = "name" type = "xs:string" />
<xs:element name = "company" type = "xs:string" />
<xs:element name = "phone" type = "xs:int" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
Global type:
Example:
AIM:
PROCEDURE:
Query:
<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
<book category="COOKING">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="CHILDREN">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="WEB">
<title lang="en">XQuery Kick Start</title>
<author>James McGovern</author>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
<author>James Linn</author>
<author>Vaidyanathan Nagarajan</author>
<year>2003</year>
<price>49.99</price>
</book>
<book category="WEB">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
OUTPUT
<bookstore>
<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="children">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="web">
<title lang="en">XQuery Kick Start</title>
<author>James McGovern</author>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
<author>James Linn</author>
<author>Vaidyanathan Nagarajan</author>
<year>2003</year>
<price>49.99</price>
</book>
<book category="web" cover="paperback">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
EX NO: 8 Creating DB using MangoDB
AIM:
PROCEDURE:
Syntax:
use DATABASE_NAME;
>use mydb
switched to db mydb
If you want to check your databases list, use the command show dbs.
>show dbs
local 0.78125GB
test 0.23012GB
Inserting data:
>db.movie.insert({"xxx":"Newone"})
>show dbs
local 0.78125GB
mydb 0.23012GB
test 0.23012GB
EX NO: 9 Code to access MangoDB
AIM:
PROCEDURE:
Code using Java:
MongoDatabase db = mongoClient.getDatabase("sample_guides");
MongoCollection<Document> coll = db.getCollection("planets");
try {
while (cursor.hasNext()) {
System.out.println(cursor.next().toJson());
}
} finally {
cursor.close();
}
Complete Code:
import com.mongodb.client.*;
import com.mongodb.client.model.Filters.*;
import org.bson.Document;
import org.bson.conversions.Bson;
public class CrudRead {
public static void main(String[] args) {
String uri = "mongodb+srv://<user>:<password>@<cluster-
url>?retryWrites=true&writeConcern=majority";
try (MongoClient mongoClient = MongoClients.create(uri)) {
// database and collection code goes here
MongoDatabase db = mongoClient.getDatabase("sample_guides");
MongoCollection<Document> coll = db.getCollection("planets");
// find code goes here
Bson filter = eq("hasRings", true);
MongoCursor<Document> cursor = coll.find(filter).iterator();
// iterate code goes here
try {
while (cursor.hasNext()) {
System.out.println(cursor.next().toJson());
}
} finally {
cursor.close();
}
}
}
}
Output:
AIM:
PROCEDURE:
Code:
To Show DB:
Output:
+
+
| name | type | aliases | access | address | role | writer | requestedStatus | currentStatus
| statusMessage | default | home | constituents |
+
+
| "neo4j" | "standard" | [] | "read-write" | "localhost:7687" | "primary" | TRUE | "online" |
"online" | "" | TRUE | TRUE | [] |
+
+
CREATE DATABASE:
neo4j@system> CREATE DATABASE sales;
output:
0 rows available after 108 ms, consumed after another 0 ms
USE DATABASE:
use <database-name>
DROP DATABASE
Example:
# accept non-local connections
server.default_listen_address=0.0.0.0
AIM:
PROCEDURE:
Queries:
Syntax:
GRANT privileges
[ON relation]
TO users
[WITH GRANT OPTION]
Example:
To one:
To public-
user_or_role: {
user (see Section 6.2.4, ―Specifying Account Names‖)
| role (see Section 6.2.5, ―Specifying Role Names‖
}
Output:
Revoked.