DBMS
DBMS
NO:1 Create a database table, add constraints, insert rows, update and delete
rows using SQL DDL and DML commands.
AIM:
To create a Database table, add constraints (primary key, unique, check, Not null),
insert rows, update and delete rows using SQL DDL and DML commands.
DDL(DATADEFINITIONLANGUAGE)
❖ CREATE
❖ ALTER
❖ DROP
❖ TRUNCATE
❖ COMMENT
❖ RENAME
PROCEDURE
STEP1: Start
table.
STEP4: Stop
SQLCOMMANDS
1. COMMAND NAME: CREATE
COMMAND DESCRIPTION: CREATE command is used to create
objects in the database.
2. COMMAND NAME: DROP
COMMAND DESCRIPTION: DROP command is used to delete the object from
the database.
3. COMMAND NAME: TRUNCATE
COMMAND DESCRIPTION: TRUNCATE command is used to remove all the
records from the table
QUERY:01
Q1. Write a query to create a table employee with empno, ename, designation, and
salary.
SQL:
CREATE<OBJ.TYPE><OBJ.NAME>(COLUMNNAME.1<DATATYPE>(SIZE),
COLUMNNAME.1<DATATYPE>(SIZE) ...........................................);
QUERY:01
SQL>CREATETABLEEMP(EMPNO NUMBER(4),
ENAME VARCHAR2(10),
DESIGNATIN VARCHAR2(10),
SALARY NUMBER(8,2));
Table created.
QUERY:02
Q2. Write a query to display the column name and datatype of the table employee.
SQL:
DESC<TABLENAME>;
SQL>DESC EMP;
QUERY:03
Q3 .Write a query for create a from an existing table with all the fields
SQL>CREATETABLEEMP1ASSELECT*FROM EMP;
Table created.
SQL>DESC EMP1;
QUERY:04
Q4. Write a query for create a from an existing table with selected fields
SQL>CREATETABLE<TRAGETTABLENAME>SELECTEMPNO,ENAME
FROM<SOURCE TABLE NAME>;
QUERY:04
SQL>DESC EMP2;
QUERY:05
Q5 .Write a query for create a new table from an existing table without any record:
Syntax for create a new table from an existing table without any record:
SQL>CREATETABLE<TRAGETTABLENAME> ASSELECT*FROM
<SOURCETABLENAME>WHERE<FALSECONDITION>;
QUERY:05
SQL> CREATE TABLE EMP3 AS SELECT * FROM EMP
WHERE1>2;
Table created.
SQL>DESC
EMP3;
QUERY:06
Q6. Write a Query to Alter the column EMPNO NUMBER (4) TO EMPNO
NUMBER(6).
QUERY:06
SQL>ALTER TABLE EMP MODIFY EMPNO NUMBER(6);
Table altered.
SQL>DESC EMP;
QUERY:07
Q7. Write a Query to Alter the table employee with multiple columns
(EMPNO,ENAME.)
SQL>DESC EMP;
QUERY:08
Q8. Write a query to add a new column into employee
Syntax for add a new column:
SQL> ALTER TABLE <TABLE NAME> ADD (<COLUMN
NAME><DATATYPE><SIZE>);
QUERY:08
SQL>ALTERTABLEEMPADDQUALIFICATIONVARCHAR2(6);
Table altered.
SQL>DESC
EMP;
QUERY:09
Q9. Write a query to add multiple columns into employee
Syntax for add a new column:
SQL> ALTER TABLE <TABLE NAME> ADD (<COLUMN
NAME1><DATATYPE><SIZE>,(<COLUMN NAME2><DATA
TYPE><SIZE>,
………………………………………………………………);
QUERY:09
REMOVE/DROP
QUERY:10
Q10.Writeaquerytodropacolumnfromanexistingtable employee
Syntax for add a new column:
SQL>ALTERTABLE<TABLENAME>DROPCOLUMN<COLUMNNAME>;
QUERY:10
Table altered.
SQL>DESC
EMP;
QUERY:11
Q10.Write a query to drop multiple columns from employee
Syntax for add a new column:
SQL>ALTERTABLE<TABLENAME>DROP<COLUMN
NAME1>,<COLUMNNAME2>,… ........................................... ;
QUERY:11
SQL>DESC EMP;
REMOVE
QUERY:12
Q10. Write a query to rename table emp to employee.
Syntax for add a new column:
SQL>ALTERTABLERENAME<OLDNAME> TO<NEWNAME>
QUERY:12
RESULT:
Thus the program to implement DDL and DML commands was executed and
verified successfully.
1.B.
Aim:
To write a program to add the constraints to the table.
CONSTRAINTS
Constraints are part of the table definition that limits and restriction on the
value entered into its columns.
TYPES OF CONSTRAINTS:
1) Primary key
2) Check
3) Unique
4) Not null
CONSTRAINTS CAN BE CREATED IN THREE WAYS:
OPERATION ON CONSTRAINT:
i) ENABLE
ii) DISABLE
iii) DROP
QUERY:13
QUERY:14
SQL>CREATE TABLE EMPLOYEE ( EMPNO NUMBER(5),ENAME
VARCHAR2(6),JOB VARCHAR2(6),SAL NUMBER(6),DEPTNO NUMBER(6));
SQL>ALTER TABLE EMP3 ADD CONSTRAINT EMP3_EMPNO_PK
PRIMARYKEY(EMPNO);
Check constraint
QUERY:15
Unique Constraint
Column Level Constraint
Q16: Write a query to create unique constraints with column level
QUERY:17
SQL>CREATE TABLE EMP13( EMPNO NUMBER(4), ENAME VARCHAR2(20)
CONSTRAINT EMP13_ENAME_NN NOT NULL, DESIGN VARCHAR2(20), SAL
NUMBER(3));
RESULT:
Thus the program to implement constraints was executed and verified
successfully.
1.C :
Aim:
To write a program to implement the DML commands.
PROCEDURE
STEP1: Start
STEP2: Create the table with its essential
attributes.
INSERT
QUERY:01
SQL:>INSERTINTO <TABLENAME>VALUES<VAL1,‘VAL2’,…..);
QUERY:01
INSERT A RECORD FROM AN EXISTING TABLE:
SQL>INSERT INTO EMP VALUES(101,'NAGESWARI ','LECTURER',15000);
1rowcreated.
SELECT
QUERY:02
SQL>SELECT*FROM<TABLENAME>;
QUERY:02
DISPLAY THE EMPTABLE:
SQL>SELECT * FROM EMP;
INSERTARECORDUSINGSUBSITUTIONMETHOD
QUERY:03
Q3. Write a query to insert the records into employee using substitution method.
Syntax for Insert Records into the table:
QUERY:03
SQL> INSERT INTO EMP VALUES
(&EMPNO,'&ENAME','&DESIGNATIN','&SALARY');
Enter value forempno:102
Enter value for ename:
SARAVANAN
SQL>/
Enter value for empno: 104
QUERY:04
SQL>UPDATE<<TABLENAME>SET<COLUMNANE>=<VALUE>WHERE
<COLUMNNAME=<VALUE>;
QUERY:04
SQL>UPDATE<<TABLENAME>SET<COLUMNANE>=<VALUE>WHERE
<COLUMNNAME=<VALUE>;
QUERY:05
SQL>UPDATE EMP SET SALARY=16000, DESIGNATIN='ASST.PROF 'WHERE
EMPNO=102;
1rowupdated.
SQL>SELECT * FROM EMP;
DELETE
QUERY:06
SQL>DELETE<TABLENAME>WHERE<COLUMNNAME>=<VALUE>;
QUERY:06
TCL(TRNSACTIONCONTROLLANGUAGE)
SAVEPOINT:
QUERY:07
SQL>SAVEPOINT<SAVEPOINTNAME>;
QUERY:07
SQL>SAVEPOINT S1;
Savepointcreated.
QUERY:08
SQL>ROLLBACK<SAVEPOINTNAME>;
QUERY:08
SQL>ROLLBACK S1;
Rollbackcomplete.
COMMIT
QUERY:09
Q5. Write a query to implement the Rollback.
Syntax for commit:
SQL>COMMIT;
QUERY:09
SQL>COMMIT;
Commitcomplete
RESULT:
Thus the program to implement the DML commands was executed and verified
successfully.
EX.2. Create a set of tables, add foreign key constraints and incorporate referential
integrity
AIM:
To create a set of tables, add foreign key constraints and incorporate referential integrity.
A referential integrity constraint is also known as foreign key constraint. A foreign key is a key
whose values are derived from the Primary key of another table.The table from which the values
are derived is known as Master or Referenced Table and the Table in which values are inserted
accordingly is known as Child or Referencing Table, In other words, we can say that the table
containing the foreign key is called the child table, and the table containing the Primary
key/candidate key is called the referenced or parent table. When we talk about the database
relational model, the candidate key can be defined as a set of attribute which can have zero or
more attributes.
1. CREATE TABLE Student (Roll int PRIMARY KEY, Name varchar(25) , Course varc
har(10) );
Here column Roll is acting as Primary Key, which will help in deriving the value of foreign key
in the child table
2. CREATE TABLE Subject (Roll int references Student, SubCode int, SubName varcha
r(10) );
In the above table, column Roll is acting as Foreign Key, whose values are derived using the
Roll value of Primary key from Master table.
SQL FOREIGN KEY Constraint
The FOREIGN KEY constraint is used to prevent actions that would destroy links between
tables.
A FOREIGN KEY is a field (or collection of fields) in one table, that refers to the PRIMARY
KEY in another table.
The table with the foreign key is called the child table, and the table with the primary key is
called the referenced or parent table.
CREATE TABLE Orders(
OrderIDint NOT NULL,
OrderNumberint NOT NULL,
PersonIDint,
PRIMARY KEY (OrderID),
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)
);
To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY constraint
on multiple columns, use the following SQL syntax:
Result:
Thus set of tables to add foreign key constraints and incorporate referential integrity is dine
successfully.
EX3. Query the database tables using different ‘where’ clause conditions and also
implement aggregate functions
AIM:
To write a query the database tables using different ‘where’ clause conditions and also implement
aggregate functions
WHERE conditions;
Parameters or Arguments
conditions
The conditions that must be met for records to be selected.
SELECT *
FROM contacts
WHERE last_name = 'Johnson';
In this MySQL WHERE clause example, we've used the WHERE clause to filter our results from
the contacts table. The SELECT statement above would return all rows from the contacts table
where the last_name is Johnson. Because the * is used in the SELECT, all fields from
the contacts table would appear in the result set.
SELECT *
FROM suppliersWHERE state = 'Florida'
AND supplier_id> 1000;
This MySQL WHERE clause example uses the WHERE clause to define multiple conditions. In
this case, this SELECT statement uses the AND Condition to return all suppliers that are located
in the state of Florida and whose supplier_id is greater than 1000.
SELECT supplier_id
FROM suppliers
WHERE supplier_name = 'Apple'
OR supplier_name = 'Microsoft';
This MySQL WHERE clause example uses the WHERE clause to define multiple conditions,
but instead of using the AND Condition, it uses the OR Condition. In this case, this SELECT
statement would return all supplier_id values where the supplier_name is Apple or Microsoft.
SELECT *
FROM suppliers
WHERE (state = 'Florida' AND supplier_name = 'IBM')
OR (supplier_id> 5000);
This MySQL WHERE clause example uses the WHERE clause to define multiple conditions,
but it combines the AND Condition and the OR Condition. This example would return
all suppliers that reside in the state of Florida and whose supplier_name is IBM as well as all
suppliers whose supplier_id is greater than 5000.
MySQL Aggregate Functions
MySQL's aggregate function is used to perform calculations on multiple values and return
the result in a single value like the average of all values, the sum of all values, and maximum
& minimum value among certain groups of values. We mostly use the aggregate functions
with SELECT statements in the data query languages.
Execute the below statement to insert the records into the employee table:
Count() Function
MySQL count() function returns the total number of values in the expression. This function
produces all rows or only some rows of the table based on a specified condition, and its return
type is BIGINT. It returns zero if it does not find any matching rows. It can work with both
numeric and non-numeric data types.
Sum() Function
The MySQL sum() function returns the total summed (non-NULL) value of an expression. It
returns NULL if the result set does not have any rows. It works with numeric data type only.
mysql> SELECT SUM(working_hours) AS "Total working hours" FROM employee;
AVG() Function
MySQL AVG() function calculates the average of the values specified in the column. Similar
to the SUM() function, it also works with numeric data type only.
MIN() Function
MySQL MIN() function returns the minimum (lowest) value of the specified column. It also
works with numeric data type only.
MAX() Function
MySQL MAX() function returns the maximum (highest) value of the specified column. It also
works with numeric data type only.
FIRST() Function
This function returns the first value of the specified column. To get the first value of the
column, we must have to use the LIMIT clause. It is because FIRST() function only supports in
MS Access.
LAST() Function
This function returns the last value of the specified column. To get the last value of the column,
we must have to use the ORDER BY and LIMIT clause. It is because the LAST() function only
supports in MS Access.
AIM:
To write a query the database tables and explore sub queries and simple join operations.
Syntax
Or
Example:
1. IN
2. ANY
3. ALL orEXISTS
Example
JOIN IN MYSQL
SQL JOIN
A JOIN clause is used to combine rows from two or more tables, based on a related column
between them.Let's look at a selection from the "Orders" table. Then, look at a selection from the
"Customers" table:
OrderID CustomerID OrderDate
10308 2 1996-09-18
10309 37 1996-09-19
10310 77 1996-09-20
Notice that the "CustomerID" column in the "Orders" table refers to the "CustomerID" in the
"Customers" table. The relationship between the two tables above is the "CustomerID" column.
Then, we can create the following SQL statement (that contains an INNER JOIN), that selects
records that have matching values in both tables:
QUERY
SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate
FROM Orders
INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID;
Result:
Thus the queries for the database tables and explore sub queries and simple join
operations is executed successfully.
EX 5: Query the database tables and explore natural, equi and outer joins
AIM:
To write a query the database tables and explore natural, equi and outer joins.
Result:
Thus the queries to perform join operation was executed successfully
Ex 6: Write user defined functions and stored procedures in SQL
Aim:
To write user defined functions and stored procedures in SQL.
Stored procedure basics
A stored procedure is a segment of declarative SQL statements stored inside the MySQL Server
• Changing the default delimiter – learn how to change the default delimiter in MySQL.
• Creating new stored procedures – show you how to create use the CREATE
PROCEDURE statement to create a new stored procedure in the database.
• Removing stored procedures – show you how to use the DROP PROCEDURE statement to drop
an existing stored procedure.
• Variables – guide on you how to use variables to hold immediate results inside stored
procedures.
• Parameters –various types of parameters used in stored procedures including IN, OUT,
and INOUT parameter.
FUNCTION
The CREATE FUNCTION statement is also used in MySQL to support loadable functions. A
loadable function can be regarded as an external stored function. Stored functions share their
namespace with loadable functions
Procedure Example
User Variable
mysql> DELIMITER $$
CREATE PROCEDURE User_Variables()
-> BEGIN
-> SET @x=15;
-> SET @y=10;
-> SELECT @x,@y,@x-@y;
-> END$$
mysql> CALL User_Variables();
-> $$
Local Variable
mysql> DELIMITER $$
mysql>CALL Local_Variables();
-> $$
Simple Procedure
Procedure Parameter IN
mysql> DELIMITER $$
mysql> CREATE PROCEDURE my_IN (IN var1 INT)
-> BEGIN
-> SELECT * FROM table1 LIMIT var1;
-> END$$
mysql> DELIMITER $$
mysql> CREATE PROCEDURE my_proc_OUT (OUT coursecount INT)
-> BEGIN
-> SELECT COUNT(class) INTO coursecount FROM table1;
-> END$$
mysql> DELIMITER $$
mysql> CREATE PROCEDURE course_counts1 (IN var1 VARCHAR(10), OUT count INT)
-> BEGIN
-> SELECT COUNT(*) INTO count FROM table1 WHERE class=var1;
-> END$$
Function Example
Example 2:
mysql>create table customer (id int, name varchar(20), age int);
\mysql>insert into customer values (101,’pater’,32), (102,’Joseph’,30), (103,’John’,28),
(105,’stephen’,45), (105,’suzi’,26), (106,’Bob’,25);
mysql> select * from customer;
mysql> DELIMITER $$
mysql> CREATE FUNCTION customer_occupation(age int)
-> RETURNS VARCHAR(20)
-> DETERMINISTIC
-> BEGIN
-> DECLARE occupation VARCHAR(20);
-> IF age>35 THEN
-> SET occupation='Scientist';
-> ELSEIF (age<=35 AND age>=30) THEN
-> SET occupation='Engineer';
-> ELSEIF age<30 THEN
-> SET occupation='Actor';
-> END IF;
-> RETURN(occupation);
-> END$$
Result:
AIM:
To execute complex transactions and realize DCL and TCL commands.
TCL Commands in SQL
o There are certain commands present in SQL known as TCL commands that help the user
manage the transactions that take place in a database.
o COMMIT. ROLLBACK and SAVEPOINT are the most commonly used TCL
commands in SQL.
Now let us take a deeper dive into the TCL commands of SQL with the help of examples. All the
queries in the examples will be written using the MySQL database.
1. COMMIT
COMMIT command in SQL is used to save all the transaction-related changes permanently to the
disk. Whenever DDL commands such as INSERT, UPDATE and DELETE are used, the changes
made by these commands are permanent only after closing the current session
mysql> COMMIT;
2. SAVEPOINT
We can divide the database operations into parts. For example, we can consider all the insert related
queries that we will execute consecutively as one part of the transaction and the delete command
as the other part of the transaction. Using the SAVEPOINT command in SQL, we can save these
different parts of the same transaction using different names
SAVEPOINT savepoint_name;
3. ROLLBACK
While carrying a transaction, we must create savepoints to save different parts of the transaction.
According to the user's changing requirements, he/she can roll back the transaction to different
savepoints. Consider a scenario: We have initiated a transaction followed by the table creation
and record insertion into the table. After inserting records, we have created a savepoint INS. Then
we executed a delete query, but later we thought that mistakenly we had removed the useful record.
Therefore in such situations, we have an option of rolling back our transaction. In this case, we
have to roll back our transaction using the ROLLBACK command to the savepoint INS, which we
have created before executing the DELETE query.
Note : Use the table T_school and insert some rows then follow the given procedure:
DCL
o Every user will have some pre-defined privileges; accordingly, the data can be accessed by
that particular user. Using the DCL commands in SQL, we can give privileges to the user
on the SQL database and tables, or we can also revoke the given privileges from the user.
1. GRANT
Access privileges can be assigned to a user for the databases and tables using the GRANT
command.
2. REVOKE
All the access privileges which are already assigned to the user can be revoked by using the
REVOKE command.
GRANT SELECT, UPDATE ON t_school TO USER 1 , USER2;
Permission granted
REVOKE SELECT, UPDATE ON t_school FROM USER1, USER2;
Result:
Thus the Execution of complex transactions and realize DCL
and TCL commandsdone successfully.
EX 8: Write SQL Triggers for insert, delete, and update operations
in a database table.AIM:
To write SQL Triggers for insert, delete, and update operations in a database table.
Description:
The SQL standard defines two types of triggers: row-level triggers and statement-level
triggers.
• A row-level trigger is activated for each row that is inserted, updated, or deleted.
• A statement-level trigger is executed once for each transaction
regardless of how manyrows are inserted, updated, or deleted.
mysql> DELIMITER $$
mysql> Create Trigger after_insert_details2
-> AFTER INSERT ON employee FOR EACH ROW
-> BEGIN
-> INSERT INTO emp_details1
VALUES(NEW.id,NEW.name,NEW.occupation,NEW.working_hours,C
URTIME());
-> END$$
-> $$
mysql> select * from delemp1;
-> $$
-> $$
mysql> drop trigger after_delete;
-> $$
mysql> show triggers;
-> $$
Result:
Thus the database triggers has been implemented and executed successfully.
EX 9: Create View and index for database tables with a large number of records
AIM:
To create View and index for database tables with a large number of records.
Creating Views
Database views are created using the CREATE VIEW statement. Views can be
created from a single table, multiple tables or anotherview.
To create a view, a user must have the appropriate system privilege
according to the specific implementation.
Updating a View
This would ultimately update the base table CUSTOMERS and the same would reflect inthe
view itself.
Dropping Views
Obviously, where you have a view, you need a way to drop the view if it is no longer needed.
The syntax is very simple and is given below−
The SQL statement below creates an index named "idx_lastname" on the "LastName" column in
the "Persons" table:
If you want to create an index on a combination of columns, you can list the column names
within the parentheses, separated by commas:
Drop index:
Thus the commands to create View and index for database tables with a large number of records
executed successfully.
EX 10: Create an XML database and validate it using XML schema
Aim:
To create an XML database and validate it using XML schema.
XML Schema
An XML Schema describes the structure of an XML document, just like a DTD.
An XML document with correct syntax is called "Well Formed".
An XML document validated against an XML Schema is both "Well Formed" and "Valid".
XML Schema is an XML-based alternative to DTD:
A Simple XML Document
Look at this simple XML document called "note.xml":
<?xml version="1.0"?>
<note>
<to>To</to>
<from>JanANI</from>
<heading>Reminder</heading>
<body>Don't forget APPOINTMENT this weekend!</body>
</note>
An XML Schema
The following example is an XML Schema file called "note.xsd" that defines the elements of the
XML document above ("note.xml"):
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="https://www.w3schools.com"
xmlns="https://www.w3schools.com"
elementFormDefault="qualified">
<xs:element name="note">
<xs:complexType>
<xs:sequence>
<xs:element name="to" type="xs:string"/>
<xs:element name="from" type="xs:string"/>
<xs:element name="heading" type="xs:string"/>
<xs:element name="body" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
The Schema above is interpreted like this:
{
"accounts": [
{
"balance": "1000",
"id": "81def5e2-84f4-4885-a920-1c14d2be3c20",
"type": "Checking"
}
],
"email": "[email protected]",
"id": "0d2b2319-9c0b-4ecb-8953-98687f6a99ce",
"name": "Bob"
}
Expected output
{
"documentId": "137d8609-87f6-4cb7-9506-e52f338e79e9"
}
Expected output
{
"documentId": "137d8609-87f6-4cb7-9506-e52f338e79e9",
"data": {
"accounts": [
{
"balance": "1000",
"id": "81def5e2-84f4-4885-a920-1c14d2be3c20",
"type": "Checking"
}
],
"email": "[email protected]",
"id": "0d2b2319-9c0b-4ecb-8953-98687f6a99ce",
"name": "Bob"
}
}
Graph data:
Graph databases store their data using a graph metaphor to exploit the relationships between
data. Nodes in the graph represent data items, and edges represent the relationships between
the data items. Graph databases are designed for highly complex and connected data, which
outpaces the relationship and JOIN capabilities of an RDBMS. Graph databases are often
exceptionally good at finding commonalities and anomalies among large data sets. Examples of
Graph databases include DataStax Graph, Neo4J, JanusGraph, and Amazon Neptune
Result:
Thus the program to create Document, column and graph based data using
NOSQL database tools