SlideShare a Scribd company logo
Rajkiya Engineering College, Kannauj
A Lab File
on
Database Management System Lab (KCS-551)
Session: 2022-23
Semester: Vth
-: Submitted by :-
Name: Suhani Sinha
Roll No.: 2008390100059
Submitted to:
Mr. Deepak Singh
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
RAJKIYA ENGINEERING COLLEGE, KANNAUJ
209732
INDEX
S.No. Experiment Date Signature
1. Installing MYSQL
2. Represent all entities relationships
3. Writing SQL statements Using ORACLE/MYSQL:
• Insertion, Alter, Update, Delete
• Write the query to implement the concept of Integrity
constraints
• Aggregate functions
• Implementation of joins
4. Practice queries using Logical operators
5. Write the query for creating the users and their role
6. Creating order by, group by functions
7. Creating triggers
8. Applying table creation with select, insert data using select,
renaming on database tables
9. Using the referential integrity constraints
10. Applying Insert, Select, Distinct clause, Where clause on database
tables
11. Practice queries using Group functions
3
EXPERIMENT NO. 1
To Design a Database and create required tables. For e.g. Bank, College Database.
Database : 'Data' is originated from the word 'datum' that means 'single piece of information.' It
is plural of the word datum.A database is an organized collection of inter-related data, generally
stored and accessed electronically from a computer system.
DBMS : DBMS or Database Management System is a software application used to access,
create, and manage databases by modifying them.
Functions of DBMS :
• Data abstraction and independence.
• Data security.
• A locking mechanism for concurrent access.
• Robust data integrity capabilities.
• Logging and auditing of activity.
• Simple access using a standard API.
• Uniform administration procedures for data.
Types of DBMS :
• Hierarchical DBMS : In a Hierarchical database, model data is organized in a tree-
like structure. Data is represented using a parent-child relationship. In Hierarchical
DBMS parent may have many children, but children have only one parent.
• Network Model : The network database model allows each child to have multiple
parents. It helps you to address the need to model more complex relationships like as
the orders/parts many-to-many relationship. In this model, entities are organized in a
graph which can be accessed through several paths.
• Relational model : Relational DBMS is the most widely used DBMS model . This
model is based on normalizing data in the rows and columns of the tables. Relational
model stored in fixed structures and manipulated using SQL.
• Object-Oriented Model : In Object-oriented Model data stored in the form of
objects. The structure which is called classes which display data within it. It defines a
database as a collection of objects which stores both data members values and
operations.
Installation steps for MySql:
• Download MySql from https://dev.mysql.com/downloads/mysql/
Installing MySQL on Windows: Your downloaded MySQL is neatly packaged with an installer.
Download the installer package, unzip it anywhere and run setup.exe. By default, this process
will install everything under C:mysql.
4
Verify MySQL installation:
• Step- 1 : Open from start
• Step-2 : enter the password you have set during installation .
5
• Step-3 : if you already have created data bases then use them else create new
database.
Creation of Database :
Syntax : CREATE DATABASE databasename;
How to use the data base you have created
Syntax: USE databasename;
How to create a table :
CREATE TABLE table_name (column1 datatype, column2 datatype, column3 datatype,.... );
Creating table college:
create table college(stu_id int(10),stu_name varchar(30), stu_dept varchar(20),phonenumber
int(10),DOB date,address varchar(50),fathers_name varchar(25),mothers_name varchar(25));
Creating table bank :
create table college(stu_id int(10),stu_name varchar(30), stu_dept varchar(20),phonenumber
int(10),DOB date,address varchar(50)));
6
DESC Command : desc or describe command shows the structure of table which include name
of the column, data-type of column and the nullability which means, that column can contain
null values or not.
syntax :
DESCRIBE tablename; OR DESC tablename;
7
EXPERIMENT NO. 2
Represent all entities relationships
Relationship : A Relationship describes relation between entities. Relationship is represented
using diamonds or rhombus.
There are four types of relationships :
• One to one
• One to many
• Many to many
• Many to one
One to one Relationship :A one-to-one relationship is mostly used to split an entity in two to
provide information concisely and make it more understandable. The figure below shows an
example of a one-to-one relationship.
Example :
One to many Relationship :A one-to-many relationship refers to the relationship between two
entities X and Y in which an instance of X may be linked to many instances of Y, but an instance
of Y is linked to only one instance of X. The figure below shows an example of a one-to-many
relationship.
Example : Student can enroll for only one course .
8
Many-to-Many cardinality :A many-to-many relationship refers to the relationship between
two entities X and Y in which X may be linked to many instances of Y and vice versa. The figure
below shows an example of a many-to-many relationship. Note that a many-to-many relationship
is split into a pair of one-to-many relationships in a physical Entity Relationship Diagram.
Example : Employee can assign by many projects and project can have many employees.
Many-to-one relationship:When more than one instance of the entity on the left, and only one
instance of an entity on the right associates with the relationship then it is known as a many-to-
one relationship.
Example :Student enrolls for only one course, but a course can have many students.
9
EXPERIMENT NO. 3
Writing SQL statements Using ORACLE /MYSQL:
1. Perform the following operation for demonstrating the insertion, updation ,deletion
andalter .
INSERTION Query
Syntax : INSERT INTO table(column1, column2, …) VALUES (value1, value2, …);
• Inserting only values
Example :
Output :
ROLL_NO NAME DEPT SEC PHONE
101 Alia CSE B 9876540010
102 Alisha ME A 9876541110
• Inserting values in only specified columns
Example :
Select * from college;
INSERT INTO college(ROLL_NO, NAME, SEC)VALUES(‘104,’Aditya','A');
INSERT INTO college(ROLL_NO, NAME, SEC)VALUES(‘105,’NITYA','B');
INSERT INTO college(ROLL_NO, NAME, SEC)VALUES(‘106,’Anaya','C');
Insert into college values(101,"Alia","CSE","B",9876540010)
Insert into college values(102,"Alisha","ME","A",9876541110)
10
Output :
ROLL_NO NAME DEPT SEC PHONE
101 Alia CSE B 9876540010
102 Alisha ME A 9876541110
104 Aditya NULL A NULL
105 Nitya NULL B NULL
106 Anaya NULL C NULL
UPDATION Query :
syntax : UPDATE table_name SET column1 = value1, column2 = value2, ...WHERE condition;
• Updating single column :
Output :
ROLL_NO NAME DEPT SEC PHONE
101 Alia CSE B 9876540010
102 Alisha ME A 9876541110
Select*from college;
UPDATE college SET NAME = 'Amit ' WHERE ROLL_NO = 104;
11
Select*from college;
UPDATE college SET NAME = 'Atulya', DEPT = 'ECE' WHERE ROLL_NO = 105;
ROLL_NO NAME DEPT SEC PHONE
104 Amit NULL A NULL
105 Nitya NULL B NULL
106 Anaya NULL C NULL
• Updating multiple columns:
Example :
Output :
ROLL_NO NAME DEPT SEC PHONE
101 Alia CSE B 9876540010
102 Alisha ME A 9876541110
104 Amit NULL A NULL
105 Atulya ECE B NULL
106 Anaya NULL C NULL
DELETION Query :
12
Select*from college;
DELETE FROM college WHERE NAME = 'Ananya';
syntax : DELETE FROM table_name WHERE condition;
• Deleting single record:
Example :
Output :
ROLL_NO NAME DEPT SEC PHONE
101 Alia CSE B 9876540010
102 Alisha ME A 9876541110
104 Amit NULL A NULL
105 Atulya ECE B NULL
• Deleting multiple records:
Output :
Select*from college;
DELETE FROM college WHERE SEC = 'A';
13
ROLL_NO NAME DEPT SEC PHONE
101 Alia CSE B 9876540010
105 Atulya ECE B NULL
• Delete all of the records:
2. INTEGRITY CONSTRAINTS
INTEGRITY CONSTRAINT : Integrity constraints are a set of rules. It is used to maintain the
quality of information.integrity constraint is used to guard against accidental damage to the
database.Constraints can be defined in two ways :-
1) The constraints can be specified immediately after the column definition. This is called
column-level definition.
2) The constraints can be specified after all the columns are defined. This is called table-level
definition.
DATABASE CONSTRAINTS
• Primary Key
• Foreign Key
• CHECK Constraint
• UNIQUE Constraint
• NOT NULL Constraint
PRIMARY KEY : A primary key is a column or a group of columns used to identify a row
uniquely in a table. A primary key constraint is the combination of a not-null
constraint and a UNIQUE constraint.
Example :
Delete from college;
OR
Delete * from college;
syntax : CREATE TABLE TABLE ( column_1 data_type PRIMARY KEY, column_2 data_type, …
);
14
CREATE TABLE products (product_no INTEGER,description TEXT,
product_cost NUMERIC);
syntax : ALTER TABLE table_name ADD PRIMARY KEY (column_1, column_2);
In case you want to specify the name of the primary key constraint, you
use CONSTRAINT clause as follows:
Define primary key when changing the existing table structure
Example :
When we want to add primary key constraint in the table :
How to add an auto-incremented primary key to an existing table
Remove primary key
syntax : ALTER TABLE table_name DROP CONSTRAINT primary_key_constraint;
FOREIGN KEY : Also called referential integrity . This constraint identifies any column
referencing the PRIMARY KEY in another table. For a column to be defined as a Foreign Key, it
should be a defined as a Primary Key in the table which it is referring. One or more columns can
be defined as Foreign key.
Define a group of columns as a foreign key :
CREATE TABLE po_items ( po_no INTEGER, item_no INTEGER, product_no
INTEGER, qty INTEGER, net_price NUMERIC, PRIMARY KEY (po_no,
item_no));
syntax : CONSTRAINT constraint_name PRIMARY KEY(column_1, column_2,...);
ALTER TABLE products ADD PRIMARY KEY (product_no);
ALTER TABLE vendors ADD COLUMN ID SERIAL PRIMARY KEY;
CREATE TABLE Orders (OrderID int NOT NULL, OrderNumber
int NOT NULL,PersonID int, PRIMARY KEY (OrderID)
,FOREIGN KEY (PersonID) REFERENCES Persons(PersonID));
15
Add a foreign key constraint to an existing table :
Drop existing foreign key constraint :
CHECK Constraint : This constraint defines a business rule on a column. All the rows must
satisfy this rule. The constraint can be applied for a single column or a group of columns.
syntax:column_name data_type CONSTRAINT constraint_name CHECK(...)
CHECK on ALTER TABLE :
DROP a CHECK Constraint :
UNIQUE Constraint : This constraint ensures that a column or a group of columns in each row
have a distinct value. A column(s) can have a null value but the values cannot be duplicated.
syntax : [CONSTRAINT constraint_name] UNIQUE(column_name)
Creating a UNIQUE constraint on multiple columns :
syntax : CREATE TABLE table (c1 data_type,c2 data_type,c3 data_type,UNIQUE (c2, c3));
UNIQUE Constraint on ALTER TABLE :
DROP a Unique Constraint :
CREATE TABLE child_table(c1 INTEGER PRIMARY KEY,
c2 INTEGER,c3 INTEGER,FOREIGN KEY (c2, c3)
REFERENCES parent_table (p1, p2));
ALTER TABLE child_table ADD CONSTRAINT
constraint_name FOREIGN KEY (c1) REFERENCES parent_table (p1);
ALTER TABLE child_table
DROP CONSTRAINT constraint_fkey;
ALTER TABLE Persons ADD CHECK (Age>=18);
ALTER TABLE Persons DROP CHECK CHK_PersonAge;
ALTER TABLE Persons
ADD CONSTRAINT UC_Person UNIQUE (ID,LastName);
16
NOT NULL Constraint : This constraint ensures all rows in the table contain a definite value
for the column which is specified as not null. Which means a null value is not allowed.
syntax : [CONSTRAINT constraint name] NOT NULL
Example :
not-null constraint to columns of an existing table :
Example :
3. Aggregate Functions
Aggregate Functions: Aggregate functions perform a calculation on a set of rows and return a
single row. You can use aggregate functions as expressions only in the following clauses i.e.,
SELECT clause, HAVING clause. There are five aggregate functions:
• AVG() – returns the average value
• COUNT() – returns the number of values.
• MAX() – returns the maximum value.
• MIN() – returns the minimum value.
• SUM() – returns the sum of all or distinct value
ALTER TABLE Persons
DROP INDEX UC_Person;
CREATE TABLE invoice(id serial PRIMARY KEY,product_id int NOT
NULL,qty numeric NOT
NULL CHECK(qty > 0),net_price numeric CHECK(net_price > 0) );
syntax :
ALTER TABLE table_name
ALTER COLUMN column_name_1 SET NOT NULL,
ALTER COLUMN column_name_2 SET NOT NULL;
ALTER TABLE production_orders
ALTER COLUMN material_id SET NOT NULL,
ALTER COLUMN start_date SET NOT NULL,
ALTER COLUMN finish_date SET NOT NULL;
17
AVG(): The AVG() function allows you to calculate the average value of a numeric column.
Output :
COUNT(): The COUNT function returns the total number of values in the specified field.
Output :
MAX() : It returns the maximum value from the specified table field.
Output :
SELECTAVG(SALARY) "AVERAGE SAL" FROM empl;
SELECT COUNT(*) FROM empl;
30000
MAX(Salary)
syntax : AVG(column)
22000.0000
AVERAGE
SAL
syntax : COUNT(expression)
6
count(*)
syntax : MAX(expression)
18
MIN(): The MIN function returns the minimum value in the specified table field.
Output :
SUM(): SUM function which returns the sum of all the values in the specified column. SUM
works on numeric fields only. Null values are excluded from the result returned.
Output :
These functions are called aggregate functions because they operate on the aggregate of tuples.
The result of an aggregate function is a single value.
4. SQL JOINS
JOINS : join is used to combine columns from one (self-join) or more tables based on the values
of the common columns between the tables. A JOIN is a means for combining fields fromtwo
tables by using values common to each.There are four types of joins :-
• INNER JOIN
• LEFT JOIN
• RIGHT JOIN
• FULL JOIN
SELECT MIN(Salary)FROM empl;
SELECT SUM(Salary) "Total Salary" from empl;
syntax : MIN(expression)
12000
MIN(Salar
y)
syntax : SUM(expression)
132000
Total Salary
19
sample tables :Suppose we have two tables called basket_a and basket_b that stores fruits:
INNER JOIN : This type of join returns those records which have matching values in both
tables.
Output :
id_a fruit_a id_b fruit_b
1 apple 2 apple
2 orange 1 orange
CREATE TABLE basket_b (id INT PRIMARY KEY,fruit VARCHAR (100) NOT
NUL);
INSERT INTO basket_b (id, fruit)VALUES(1, 'Orange'),
INSERT INTO basket_b (id, fruit)VALUES(2, 'Apple'),
INSERT INTO basket_b (id, fruit)VALUES(3, 'Watermelon'),
INSERT INTO basket_b (id, fruit)VALUES(4, 'Pear');
CREATE TABLE basket_a (id INT PRIMARY KEY, fruit VARCHAR (100) NOT
NUL);
INSERT INTO basket_a (id, fruit)VALUES(1, 'Apple'),
INSERT INTO basket_a (id, fruit)VALUES (2, 'Orange'),
INSERT INTO basket_a (id, fruit)VALUES(3, 'Banana'),
INSERT INTO basket_a (id, fruit)VALUES (4, 'Cucumber');
SELECT a.id id_a, a.fruit fruit_a, b.id id_b, b.fruit fruit_b FROM basket_a a INNER
JOIN basket_b b ON a.fruit = b.fruit;
20
LEFT JOIN : returns all rows from the left table, even if there are no matches in the right table.
Output :
id_a fruit_a id_b fruit_b
1 apple 2 apple
2 orange 1 orange
3 banana null null
4 cucumber null null
RIGHT JOIN : returns all rows from the right table, even if there are no matches in the left
table.
Output :
SELECT a.id id_a, a.fruit fruit_a, b.id id_b, b.fruit fruit_b FROM basket_a a LEFT
JOIN basket_b b ON a.fruit = b.fruit;
SELECT a.id id_a, a.fruit fruit_a, b.id id_b, b.fruit fruit_b FROM basket_a a RIGH
T JOIN basket_b b ON a.fruit = b.fruit;
21
id_a fruit_a id_b fruit_b
2 orange 1 orange
1 apple 2 apple
null null 3 watermelon
null null 4 pear
FULL JOIN: returns rows when there is a match in one of the tables.
Output :
id_a fruit_a id_b fruit_b
3 banana null null
4 cucumber null null
null null 3 watermelon
null null 4 pear
SELECT a.id id_a, a.fruit fruit_a, b.id id_b, b.fruit fruit_b FROM basket_a a FULL
JOIN basket_b b ON a.fruit = b.fruit WHERE a.id IS NULL OR b.id IS NULL;
22
EXPERIMENT NO. 4
Queries using Logical Operator
There are three Logical Operators namely, AND, OR, and NOT. These operators compare two
conditions at a time to determine whether a row can be selected for the output. When retrieving
data using a SELECT statement, you can use logical operators in the WHERE clause, which
allows you to combine more than one condition.
LOGICAL
OPERATORS
DESCRIPTION
OR For the row to be selected at least one of the conditions must
be true
AND
For a row to be selected all the specified conditions must be
true
NOT
For a row to be selected the specified condition must be false
Examples : This is our given Database table named as abc.
select *from abc where marks=70 OR marks=80;
Output :
23
Output :
Output :
select *from abc where dept="EE" AND marks>=75;
select *from abc where NOT dept="EE";
24
mysql > DROP USER ‘username’@‘localhost’;
mysql>SHOW GRANTS username;
EXPERIMENT NO. 5
How To Create a New User and their roles
Create a New User :
At this point new user has no permissions to do anything with the databases. In fact, even if new
user tries to login (with the password, password), they will not be able to reach the MySQL shell.
provide the user with access to the information :
asterisks in this command refer to the database and table that they can access .Once you have
finalized the permissions that you want to set up for your new users, always be sure to reload all
the privileges.Your changes will now be in effect.
How To Grant Different User Permissions
• ALL PRIVILEGES - as we saw previously, this would allow a MySQL user full
access to a designated database (or if no database is selected, global access across the
system)
• CREATE - allows them to create new tables or databases
• DROP - allows them to them to delete tables or databases
• DELETE - allows them to delete rows from tables
• INSERT - allows them to insert rows into tables
• SELECT - allows them to use the SELECT command to read through databases
• UPDATE - allow them to update table rows
• GRANT OPTION - allows them to grant or remove other users’ privileges
To provide a specific user with a permission, you can use this framework:
If you need to revoke a permission, the structure is almost identical to granting it:
You can review a user’s current permissions by running the following:
Just as you can delete databases with DROP, you can use DROP to delete a user altogether:
To test out your new user, log out by typing:
mysql > CREATE USER 'newuser'@'localhost' IDENTIFIED BY 'password';
mysql > GRANT ALL PRIVILEGES ON * . * TO 'newuser'@'localhost';
mysql > FLUSH PRIVILEGES;
mysql > GRANT type_of_permission ON database_name.table_name TO
‘username’@'localhost’;
mysql > REVOKE type_of_permission ON database_name.table_name FROM
‘username’@‘localhost’;
25
log back in with this command in terminal:
mysql>quit
mysql >mysql -u [username] -p
26
EXPERIMENT NO. 6
Practice Queries using Group By, Having, Order By Functions
GROUP BY : The GROUP BY clause divides the rows returned from the SELECT statement
into groups. For each group, you can apply an aggregate function .The GROUP BY clause must
appear right after the FROM or WHERE clause.
Example-1 :
SELECT customer_id FROM payment GROUP BY customer_id;
Output :
.
.
.
.
customer_id
1 455
2 233
3 234
4 45
5 455
6 451
7 123
8 234
9 567
27
Example-2 :
SELECT customer_id, SUM (amount) FROM payment GROUP BY customer_id;
Output:
customer_id sum
455 12
233 12
234 56
45 564
455 45
451 34
123 34
234 22
567 34
23 5
66
HAVING : We often use the HAVING clause in conjunction with the GROUP BY clause to filter
group rows that do not satisfy a specified condition.
Example-1 :
Output :
Syntax : SELECT column_1, aggregate_function (column_2) FROM tbl_name GROUP
BY column_1 HAVING condition;
SELECT customer_id, SUM (amount) FROM payment GROUP BY customer_id
HAVING SUM (amount) > 200;
28
customer_id sum
526 234
148 232
Example-2:
Output:
store_id sum
1 326
ORDER BY :The ORDER BY clause allows you to sort rows returned from
a SELECT statement in ascending or descending order based on the specified criteria.
Example-1 :
SELECT first_name, last_name FROM customer ORDER BY first_name ASC;
Output :
... first_name last_name
1 Aaron Selby
2 Adam Gooch
3 Aram Clary
4 Agnes Bishop
5 Alan Kahn
Syntax : SELECT column_1, column_2 FROM table_name ORDER BY column_1 [ASC |
DESC], column_2 [ASC | DESC];
SELECT store_id COUNT(customer_id) FROM customer GROUP BY store_id
HAVING COUNT (customer_id) > 300;
29
Example-2 :
SELECT first_name, last_name FROM customer ORDER BY last_name DESC;
Output :
first_name last_name
1 Aaron Selby
2 Alan Kahn
3 Adam Gooch
4 Aram Clary
5 Agnes Bishop
30
EXPERIMENT NO. 7
TRIGGERS
TRIGGERS : A SQL trigger is a database object just like a stored procedure, or we can say it is
a special kind of stored procedure which fires when an event occurs in a database. We can
execute a SQL query that will "do something" in a database when an event is fired.
Types of Triggers
1. DDLTrigger
2. DML Trigger
TRIGGERS PROCEDURES
They are automatically executed on
occurrence ofspecified event.
They can be executed whenever
required.
Triggers can’t be called inside a procedure. But, you can call a procedure inside a
trigger.
We cannot pass parameters to triggers. We can pass parameters to procedures.
Triggers never return values on execution. Procedure may return value/s on
execution.
31
Creating a trigger function :
SQL CREATE TRIGGER statement :
Example :
CREATE TABLE employees(
id SERIAL PRIMARY KEY,
first_name VARCHAR(40) NOT NULL,
last_name VARCHAR(40) NOT NULL
);
INSERT INTO employees (first_name, last_name)
VALUES ('John', 'Doe');
INSERT INTO employees (first_name, last_name)
VALUES ('Lily', 'Bush');
SELECT * FROM employees;
CREATE TRIGGER trigger_name
{BEFORE | AFTER | INSTEAD OF} {event [OR ...]}
ON table_name
[FOR [EACH] {ROW | STATEMENT}]
EXECUTE PROCEDURE trigger_function
CREATE FUNCTION trigger_function()
RETURNS trigger AS
32
Output :
id first_name last_name
1 john doe
2 lily blush
UPDATE QUERY :
SELECT * FROM employees;
Output :
id first_name last_name
1 john doe
2 lily brown
UPDATE employees
SET last_name = 'Brown'
WHERE ID = 2;
33
Advantages of Triggers :
• Trigger generates some derived column values automatically
• Enforces referential integrity
• Event logging and storing information on table access
• Auditing
• Synchronous replication of tables
• Imposing security authorizations
• Preventing invalid transactions
34
EXPERIMENT NO. 8
Applying table creation with select, Insert data using select, Renaming on database Tables
CREATE TABLE with SELECT :You can create one table from another by adding
a SELECT statement at the end of the CREATE TABLE statement:
Syntax : CREATE TABLE new_tbl [AS] SELECT * FROM orig_tbl;
Example : we already have a table named as dept , now with the help of dept table we will
create new table named bar.
INSERT DATA using SELECT : Insert data into a table using the SELECT statement.
Example :
CREATE TABLE bar (m INT) SELECT * FROM dept;
Syntax : INSERT INTO table_name(column_name) SELECT tbl_name.col_name FROM
some_table tbl_name WHERE condition;
INSERT INTO bar (m, dept_id) SELECT '101', ea.dept_id FROM dept ea WHERE
ea.dept_name = 'CSE';
INSERT INTO bar (m, dept_id) SELECT '101', ea.dept_id FROM dept ea WHERE
ea.dept_name = 'IT';
INSERT INTO bar (m, dept_id) SELECT '104', ea.dept_id FROM dept ea WHERE
ea.dept_name = 'ME';
35
Output :
RENAME TABLE : To rename the existing table .
Syntax : RENAME TABLE tbl_name TO new_tbl_name ;
Example :
Output :
RENAME TABLE bar TO clg;
36
EXPERIMENT NO. 9
Referential Integrity Constraint
Referential Integrity Constraint : Referential Integrity is set of constraints applied to foreign
key which prevents entering a row in child table (where you have foreign key) for which you
don't have any corresponding row in parent table .Referential Integrity prevents your table from
having incorrect or incomplete relationship .
Referential Integrity example :
• Create Table command:
CREATE TABLE Emp (emp_id INT NOT NULL,
emp_name VARCHAR(256), dept_id INT,
FOREIGN KEY (dept_id) REFERENCES Dept(dept_id)
) ENGINE=INNODB;
CREATE TABLE Dept (dept_id INT NOT NULL,
dept_name VARCHAR(256),
PRIMARY KEY (dept_id)) ENGINE=INNODB;
37
• Insert Query :
insert into dept (dept_id,dept_name) values(101,"CSE");
insert into dept (dept_id,dept_name) values(102,"EE");
insert into dept (dept_id,dept_name) values(103,"ECE");
insert into dept (dept_id,dept_name) values(104,"ME");
insert into dept (dept_id,dept_name) values(105,"IT");
insert into emp (emp_id,dept_id,emp_name) values(1,105,"amita");
insert into emp (emp_id,dept_id,emp_name) values(2,104,"anita");
insert into emp (emp_id,dept_id,emp_name) values(3,103,"anitya");
insert into emp (emp_id,dept_id,emp_name) values(4,102,"ananya");
insert into emp (emp_id,dept_id,emp_name) values(5,101,"amaaya");
38
• Delete command:
Advantages of referential Integrity :
1. Prevents the entry of duplicate data
2. Prevents one table from pointing to a nonexistent field in another table
3. Guarantees consistency between "partnered" tables
4. Prevents the deletion of a record that contains a value referred to by a foreign key in
another table
5. Prevents the addition of a record to a table that contains a foreign key unless there is a
primary key in the linked table
mysql> DELETE FROM Dept;
Query OK, 1 row affected (0.05 sec)
mysql> SELECT * FROM Emp;
Empty SET (0.00 sec)
39
EXPERIMENT NO. 10
Applying Insert, Select, Distinct Clause, Where Clause on database Tables
Insert : The INSERT INTO statement is used to insert new records in a table.
Syntax : INSERT INTO table(column1, column2, …) VALUES (value1, value2, …);
• Inserting only values
Example :
Output :
ROLL_NO NAME DEPT SEC PHONE
101 Alia CSE B 9876540010
102 Alisha ME A 9876541110
• Inserting values in only specified columns
Example :
Select Statement :The SELECT statement is used to select data from a database.The data
returned is stored in a result table, called the result-set.
Syntax : SELECT column1, column2, ...FROM table_name;
Example :
INSERT INTO college (ROLL_NO, NAME, SEC) VALUES (‘104,’Aditya,A);
INSERT INTO college (ROLL_NO, NAME, SEC) VALUES (‘105,’NITYA,B);
INSERT INTO college (ROLL_NO, NAME, SEC) VALUES (‘106,’Anaya,C);
Insert into college values(101,Alia,CSE,B,9876540010);
Insert into college values(102,Alisha,ME,A,9876541110);
40
Output :
ROLL_NO NAME DEPT SEC PHONE
101 Alia CSE B 9876540010
102 Alisha ME A 9876541110
104 Aditya NULL A NULL
105 Nitya NULL B NULL
106 Anaya NULL C NULL
Distinct Statement :The SELECT DISTINCT statement is used to return only distinct
(different) values.Inside a table, a column often contains many duplicate values; and sometimes
you only want to list the different (distinct) values.
Syntax : SELECT DISTINCT column1, column2, ...FROM table_name;
Example :
Output :
SEC
A
B
C
Select * from college;
SELECT DISTINCT SEC FROM college;
41
Where statement : The WHERE clause is used to filter records.The WHERE clause is used to
extract only those records that fulfill a specified condition.
Syntax : SELECT column1, column2, ...FROM table_nameWHERE condition;
Example :
Output :
ROLL_NO NAME DEPT SEC PHONE
106 Anaya NULL C NULL
SELECT * FROM college WHERE SEC='C';
42
EXPERIMENT NO. 11
GROUP Functions
GROUP Functions: Group functions are built-in SQL functions that operate on groups of rows
and return one value for the entire group. These functions are:
• COUNT
• MAX
• MIN
• AVG
• SUM
• DISTINCT
COUNT (): This function returns the number of rows in the table that satisfies the condition
specified in the WHERE condition. If the WHERE condition is not specified, then the query
returns the total number of rows in the table.
Example :
DISTINCT(): This function is used to select the distinct rows.
MAX(): This function is used to get the maximum value from a column.
Example :
MIN(): This function is used to get the minimum value from a column.
Example :
AVG(): This function is used to get the average value of a numeric column.
Example :
SUM(): This function is used to get the sum of a numeric column
Example :
select count(id) from b;
select distinct name from a;
select max(id) from a;
select min(id) from a;
select avg(id) from a;
select sum(id) from a;
Ad

More Related Content

What's hot (20)

Presentation LIBRARY MANAGEMENT SYSTEM
Presentation LIBRARY MANAGEMENT SYSTEM Presentation LIBRARY MANAGEMENT SYSTEM
Presentation LIBRARY MANAGEMENT SYSTEM
binrehmat
 
EXCEL: Importancia y Ventajas
EXCEL: Importancia y VentajasEXCEL: Importancia y Ventajas
EXCEL: Importancia y Ventajas
Horacio González
 
Ms sql-server
Ms sql-serverMs sql-server
Ms sql-server
Md.Mojibul Hoque
 
database
databasedatabase
database
Shwetanshu Gupta
 
Online student management system
Online student management systemOnline student management system
Online student management system
Mumbai Academisc
 
Database Testing
Database TestingDatabase Testing
Database Testing
Siva Kotilingam Pallikonda
 
Oracle sql material
Oracle sql materialOracle sql material
Oracle sql material
prathap kumar
 
ORACLE PL SQL FOR BEGINNERS
ORACLE PL SQL FOR BEGINNERSORACLE PL SQL FOR BEGINNERS
ORACLE PL SQL FOR BEGINNERS
mohdoracle
 
Database fundamentals(database)
Database fundamentals(database)Database fundamentals(database)
Database fundamentals(database)
welcometofacebook
 
SQL subquery
SQL subquerySQL subquery
SQL subquery
Vikas Gupta
 
Sequences and indexes
Sequences and indexesSequences and indexes
Sequences and indexes
Balqees Al.Mubarak
 
Chapter23
Chapter23Chapter23
Chapter23
gourab87
 
Database architecture
Database architectureDatabase architecture
Database architecture
VENNILAV6
 
Incremental load
Incremental loadIncremental load
Incremental load
Venkat Mandalapu
 
Advanced Database Management Systems Project Report
Advanced Database Management Systems Project ReportAdvanced Database Management Systems Project Report
Advanced Database Management Systems Project Report
IshanMalpotra
 
Introduction to database
Introduction to databaseIntroduction to database
Introduction to database
Arpee Callejo
 
Pharmacy Management System1
Pharmacy Management System1Pharmacy Management System1
Pharmacy Management System1
Nuwan Lansakara
 
Oracle: Procedures
Oracle: ProceduresOracle: Procedures
Oracle: Procedures
DataminingTools Inc
 
Complete project on hospital maangement system
Complete project on hospital maangement systemComplete project on hospital maangement system
Complete project on hospital maangement system
Rahul Kumar
 
09 Managing Dependencies
09 Managing Dependencies09 Managing Dependencies
09 Managing Dependencies
rehaniltifat
 
Presentation LIBRARY MANAGEMENT SYSTEM
Presentation LIBRARY MANAGEMENT SYSTEM Presentation LIBRARY MANAGEMENT SYSTEM
Presentation LIBRARY MANAGEMENT SYSTEM
binrehmat
 
EXCEL: Importancia y Ventajas
EXCEL: Importancia y VentajasEXCEL: Importancia y Ventajas
EXCEL: Importancia y Ventajas
Horacio González
 
Online student management system
Online student management systemOnline student management system
Online student management system
Mumbai Academisc
 
ORACLE PL SQL FOR BEGINNERS
ORACLE PL SQL FOR BEGINNERSORACLE PL SQL FOR BEGINNERS
ORACLE PL SQL FOR BEGINNERS
mohdoracle
 
Database fundamentals(database)
Database fundamentals(database)Database fundamentals(database)
Database fundamentals(database)
welcometofacebook
 
Database architecture
Database architectureDatabase architecture
Database architecture
VENNILAV6
 
Advanced Database Management Systems Project Report
Advanced Database Management Systems Project ReportAdvanced Database Management Systems Project Report
Advanced Database Management Systems Project Report
IshanMalpotra
 
Introduction to database
Introduction to databaseIntroduction to database
Introduction to database
Arpee Callejo
 
Pharmacy Management System1
Pharmacy Management System1Pharmacy Management System1
Pharmacy Management System1
Nuwan Lansakara
 
Complete project on hospital maangement system
Complete project on hospital maangement systemComplete project on hospital maangement system
Complete project on hospital maangement system
Rahul Kumar
 
09 Managing Dependencies
09 Managing Dependencies09 Managing Dependencies
09 Managing Dependencies
rehaniltifat
 

Similar to DBMS LAB M.docx (20)

Module 3
Module 3Module 3
Module 3
cs19club
 
Sql wksht-2
Sql wksht-2Sql wksht-2
Sql wksht-2
Mukesh Tekwani
 
database in my squel assignment for students.pdf
database in my squel assignment for students.pdfdatabase in my squel assignment for students.pdf
database in my squel assignment for students.pdf
mashorialli500
 
Sql commands
Sql commandsSql commands
Sql commands
Pooja Dixit
 
CS3481_Database Management Laboratory .pdf
CS3481_Database Management Laboratory .pdfCS3481_Database Management Laboratory .pdf
CS3481_Database Management Laboratory .pdf
Kirubaburi R
 
SQL: Introduction and its Basic Commands
SQL: Introduction and its Basic CommandsSQL: Introduction and its Basic Commands
SQL: Introduction and its Basic Commands
niyantadesai7
 
Data Manipulation(DML) and Transaction Control (TCL)
Data Manipulation(DML) and Transaction Control (TCL)  Data Manipulation(DML) and Transaction Control (TCL)
Data Manipulation(DML) and Transaction Control (TCL)
MuhammadWaheed44
 
SQL.pptx for the begineers and good know
SQL.pptx for the begineers and good knowSQL.pptx for the begineers and good know
SQL.pptx for the begineers and good know
PavithSingh
 
MySQL Essential Training
MySQL Essential TrainingMySQL Essential Training
MySQL Essential Training
HudaRaghibKadhim
 
DBMS week 2 hjghg hvgfhgf,3 BSCS 6th.pptx
DBMS week 2 hjghg hvgfhgf,3 BSCS 6th.pptxDBMS week 2 hjghg hvgfhgf,3 BSCS 6th.pptx
DBMS week 2 hjghg hvgfhgf,3 BSCS 6th.pptx
universalcomputer1
 
SQL -Beginner To Intermediate Level.pdf
SQL -Beginner To Intermediate Level.pdfSQL -Beginner To Intermediate Level.pdf
SQL -Beginner To Intermediate Level.pdf
DraguClaudiu
 
2. DBMS Experiment - Lab 2 Made in SQL Used
2. DBMS Experiment - Lab 2 Made in SQL Used2. DBMS Experiment - Lab 2 Made in SQL Used
2. DBMS Experiment - Lab 2 Made in SQL Used
TheVerse1
 
SQl data base management and design
SQl     data base management  and designSQl     data base management  and design
SQl data base management and design
franckelsania20
 
Data base.ppt
Data base.pptData base.ppt
Data base.ppt
TeklayBirhane
 
Adbms 21 sql 99 schema definition constraints and queries
Adbms 21 sql 99 schema definition constraints and queriesAdbms 21 sql 99 schema definition constraints and queries
Adbms 21 sql 99 schema definition constraints and queries
Vaibhav Khanna
 
Database COMPLETE
Database COMPLETEDatabase COMPLETE
Database COMPLETE
Abrar ali
 
Its about a sql topic for basic structured query language
Its about a sql topic for basic structured query languageIts about a sql topic for basic structured query language
Its about a sql topic for basic structured query language
IMsKanchanaI
 
Lab
LabLab
Lab
neelam_rawat
 
Oracle: Commands
Oracle: CommandsOracle: Commands
Oracle: Commands
oracle content
 
Oracle: DDL
Oracle: DDLOracle: DDL
Oracle: DDL
DataminingTools Inc
 
database in my squel assignment for students.pdf
database in my squel assignment for students.pdfdatabase in my squel assignment for students.pdf
database in my squel assignment for students.pdf
mashorialli500
 
CS3481_Database Management Laboratory .pdf
CS3481_Database Management Laboratory .pdfCS3481_Database Management Laboratory .pdf
CS3481_Database Management Laboratory .pdf
Kirubaburi R
 
SQL: Introduction and its Basic Commands
SQL: Introduction and its Basic CommandsSQL: Introduction and its Basic Commands
SQL: Introduction and its Basic Commands
niyantadesai7
 
Data Manipulation(DML) and Transaction Control (TCL)
Data Manipulation(DML) and Transaction Control (TCL)  Data Manipulation(DML) and Transaction Control (TCL)
Data Manipulation(DML) and Transaction Control (TCL)
MuhammadWaheed44
 
SQL.pptx for the begineers and good know
SQL.pptx for the begineers and good knowSQL.pptx for the begineers and good know
SQL.pptx for the begineers and good know
PavithSingh
 
DBMS week 2 hjghg hvgfhgf,3 BSCS 6th.pptx
DBMS week 2 hjghg hvgfhgf,3 BSCS 6th.pptxDBMS week 2 hjghg hvgfhgf,3 BSCS 6th.pptx
DBMS week 2 hjghg hvgfhgf,3 BSCS 6th.pptx
universalcomputer1
 
SQL -Beginner To Intermediate Level.pdf
SQL -Beginner To Intermediate Level.pdfSQL -Beginner To Intermediate Level.pdf
SQL -Beginner To Intermediate Level.pdf
DraguClaudiu
 
2. DBMS Experiment - Lab 2 Made in SQL Used
2. DBMS Experiment - Lab 2 Made in SQL Used2. DBMS Experiment - Lab 2 Made in SQL Used
2. DBMS Experiment - Lab 2 Made in SQL Used
TheVerse1
 
SQl data base management and design
SQl     data base management  and designSQl     data base management  and design
SQl data base management and design
franckelsania20
 
Adbms 21 sql 99 schema definition constraints and queries
Adbms 21 sql 99 schema definition constraints and queriesAdbms 21 sql 99 schema definition constraints and queries
Adbms 21 sql 99 schema definition constraints and queries
Vaibhav Khanna
 
Database COMPLETE
Database COMPLETEDatabase COMPLETE
Database COMPLETE
Abrar ali
 
Its about a sql topic for basic structured query language
Its about a sql topic for basic structured query languageIts about a sql topic for basic structured query language
Its about a sql topic for basic structured query language
IMsKanchanaI
 
Ad

Recently uploaded (20)

Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...
Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...
Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...
Journal of Soft Computing in Civil Engineering
 
Machine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptxMachine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptx
rajeswari89780
 
International Journal of Distributed and Parallel systems (IJDPS)
International Journal of Distributed and Parallel systems (IJDPS)International Journal of Distributed and Parallel systems (IJDPS)
International Journal of Distributed and Parallel systems (IJDPS)
samueljackson3773
 
Raish Khanji GTU 8th sem Internship Report.pdf
Raish Khanji GTU 8th sem Internship Report.pdfRaish Khanji GTU 8th sem Internship Report.pdf
Raish Khanji GTU 8th sem Internship Report.pdf
RaishKhanji
 
MAQUINARIA MINAS CEMA 6th Edition (1).pdf
MAQUINARIA MINAS CEMA 6th Edition (1).pdfMAQUINARIA MINAS CEMA 6th Edition (1).pdf
MAQUINARIA MINAS CEMA 6th Edition (1).pdf
ssuser562df4
 
Oil-gas_Unconventional oil and gass_reseviours.pdf
Oil-gas_Unconventional oil and gass_reseviours.pdfOil-gas_Unconventional oil and gass_reseviours.pdf
Oil-gas_Unconventional oil and gass_reseviours.pdf
M7md3li2
 
AI-assisted Software Testing (3-hours tutorial)
AI-assisted Software Testing (3-hours tutorial)AI-assisted Software Testing (3-hours tutorial)
AI-assisted Software Testing (3-hours tutorial)
Vəhid Gəruslu
 
π0.5: a Vision-Language-Action Model with Open-World Generalization
π0.5: a Vision-Language-Action Model with Open-World Generalizationπ0.5: a Vision-Language-Action Model with Open-World Generalization
π0.5: a Vision-Language-Action Model with Open-World Generalization
NABLAS株式会社
 
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdffive-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
AdityaSharma944496
 
Compiler Design Unit1 PPT Phases of Compiler.pptx
Compiler Design Unit1 PPT Phases of Compiler.pptxCompiler Design Unit1 PPT Phases of Compiler.pptx
Compiler Design Unit1 PPT Phases of Compiler.pptx
RushaliDeshmukh2
 
Artificial Intelligence (AI) basics.pptx
Artificial Intelligence (AI) basics.pptxArtificial Intelligence (AI) basics.pptx
Artificial Intelligence (AI) basics.pptx
aditichinar
 
QA/QC Manager (Quality management Expert)
QA/QC Manager (Quality management Expert)QA/QC Manager (Quality management Expert)
QA/QC Manager (Quality management Expert)
rccbatchplant
 
15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...
IJCSES Journal
 
introduction to machine learining for beginers
introduction to machine learining for beginersintroduction to machine learining for beginers
introduction to machine learining for beginers
JoydebSheet
 
Reagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptxReagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptx
AlejandroOdio
 
Value Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous SecurityValue Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous Security
Marc Hornbeek
 
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITYADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ijscai
 
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E..."Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
Infopitaara
 
Compiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptxCompiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptx
RushaliDeshmukh2
 
railway wheels, descaling after reheating and before forging
railway wheels, descaling after reheating and before forgingrailway wheels, descaling after reheating and before forging
railway wheels, descaling after reheating and before forging
Javad Kadkhodapour
 
Machine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptxMachine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptx
rajeswari89780
 
International Journal of Distributed and Parallel systems (IJDPS)
International Journal of Distributed and Parallel systems (IJDPS)International Journal of Distributed and Parallel systems (IJDPS)
International Journal of Distributed and Parallel systems (IJDPS)
samueljackson3773
 
Raish Khanji GTU 8th sem Internship Report.pdf
Raish Khanji GTU 8th sem Internship Report.pdfRaish Khanji GTU 8th sem Internship Report.pdf
Raish Khanji GTU 8th sem Internship Report.pdf
RaishKhanji
 
MAQUINARIA MINAS CEMA 6th Edition (1).pdf
MAQUINARIA MINAS CEMA 6th Edition (1).pdfMAQUINARIA MINAS CEMA 6th Edition (1).pdf
MAQUINARIA MINAS CEMA 6th Edition (1).pdf
ssuser562df4
 
Oil-gas_Unconventional oil and gass_reseviours.pdf
Oil-gas_Unconventional oil and gass_reseviours.pdfOil-gas_Unconventional oil and gass_reseviours.pdf
Oil-gas_Unconventional oil and gass_reseviours.pdf
M7md3li2
 
AI-assisted Software Testing (3-hours tutorial)
AI-assisted Software Testing (3-hours tutorial)AI-assisted Software Testing (3-hours tutorial)
AI-assisted Software Testing (3-hours tutorial)
Vəhid Gəruslu
 
π0.5: a Vision-Language-Action Model with Open-World Generalization
π0.5: a Vision-Language-Action Model with Open-World Generalizationπ0.5: a Vision-Language-Action Model with Open-World Generalization
π0.5: a Vision-Language-Action Model with Open-World Generalization
NABLAS株式会社
 
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdffive-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
AdityaSharma944496
 
Compiler Design Unit1 PPT Phases of Compiler.pptx
Compiler Design Unit1 PPT Phases of Compiler.pptxCompiler Design Unit1 PPT Phases of Compiler.pptx
Compiler Design Unit1 PPT Phases of Compiler.pptx
RushaliDeshmukh2
 
Artificial Intelligence (AI) basics.pptx
Artificial Intelligence (AI) basics.pptxArtificial Intelligence (AI) basics.pptx
Artificial Intelligence (AI) basics.pptx
aditichinar
 
QA/QC Manager (Quality management Expert)
QA/QC Manager (Quality management Expert)QA/QC Manager (Quality management Expert)
QA/QC Manager (Quality management Expert)
rccbatchplant
 
15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...
IJCSES Journal
 
introduction to machine learining for beginers
introduction to machine learining for beginersintroduction to machine learining for beginers
introduction to machine learining for beginers
JoydebSheet
 
Reagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptxReagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptx
AlejandroOdio
 
Value Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous SecurityValue Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous Security
Marc Hornbeek
 
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITYADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ijscai
 
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E..."Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
Infopitaara
 
Compiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptxCompiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptx
RushaliDeshmukh2
 
railway wheels, descaling after reheating and before forging
railway wheels, descaling after reheating and before forgingrailway wheels, descaling after reheating and before forging
railway wheels, descaling after reheating and before forging
Javad Kadkhodapour
 
Ad

DBMS LAB M.docx

  • 1. Rajkiya Engineering College, Kannauj A Lab File on Database Management System Lab (KCS-551) Session: 2022-23 Semester: Vth -: Submitted by :- Name: Suhani Sinha Roll No.: 2008390100059 Submitted to: Mr. Deepak Singh DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING RAJKIYA ENGINEERING COLLEGE, KANNAUJ 209732
  • 2. INDEX S.No. Experiment Date Signature 1. Installing MYSQL 2. Represent all entities relationships 3. Writing SQL statements Using ORACLE/MYSQL: • Insertion, Alter, Update, Delete • Write the query to implement the concept of Integrity constraints • Aggregate functions • Implementation of joins 4. Practice queries using Logical operators 5. Write the query for creating the users and their role 6. Creating order by, group by functions 7. Creating triggers 8. Applying table creation with select, insert data using select, renaming on database tables 9. Using the referential integrity constraints 10. Applying Insert, Select, Distinct clause, Where clause on database tables 11. Practice queries using Group functions
  • 3. 3 EXPERIMENT NO. 1 To Design a Database and create required tables. For e.g. Bank, College Database. Database : 'Data' is originated from the word 'datum' that means 'single piece of information.' It is plural of the word datum.A database is an organized collection of inter-related data, generally stored and accessed electronically from a computer system. DBMS : DBMS or Database Management System is a software application used to access, create, and manage databases by modifying them. Functions of DBMS : • Data abstraction and independence. • Data security. • A locking mechanism for concurrent access. • Robust data integrity capabilities. • Logging and auditing of activity. • Simple access using a standard API. • Uniform administration procedures for data. Types of DBMS : • Hierarchical DBMS : In a Hierarchical database, model data is organized in a tree- like structure. Data is represented using a parent-child relationship. In Hierarchical DBMS parent may have many children, but children have only one parent. • Network Model : The network database model allows each child to have multiple parents. It helps you to address the need to model more complex relationships like as the orders/parts many-to-many relationship. In this model, entities are organized in a graph which can be accessed through several paths. • Relational model : Relational DBMS is the most widely used DBMS model . This model is based on normalizing data in the rows and columns of the tables. Relational model stored in fixed structures and manipulated using SQL. • Object-Oriented Model : In Object-oriented Model data stored in the form of objects. The structure which is called classes which display data within it. It defines a database as a collection of objects which stores both data members values and operations. Installation steps for MySql: • Download MySql from https://dev.mysql.com/downloads/mysql/ Installing MySQL on Windows: Your downloaded MySQL is neatly packaged with an installer. Download the installer package, unzip it anywhere and run setup.exe. By default, this process will install everything under C:mysql.
  • 4. 4 Verify MySQL installation: • Step- 1 : Open from start • Step-2 : enter the password you have set during installation .
  • 5. 5 • Step-3 : if you already have created data bases then use them else create new database. Creation of Database : Syntax : CREATE DATABASE databasename; How to use the data base you have created Syntax: USE databasename; How to create a table : CREATE TABLE table_name (column1 datatype, column2 datatype, column3 datatype,.... ); Creating table college: create table college(stu_id int(10),stu_name varchar(30), stu_dept varchar(20),phonenumber int(10),DOB date,address varchar(50),fathers_name varchar(25),mothers_name varchar(25)); Creating table bank : create table college(stu_id int(10),stu_name varchar(30), stu_dept varchar(20),phonenumber int(10),DOB date,address varchar(50)));
  • 6. 6 DESC Command : desc or describe command shows the structure of table which include name of the column, data-type of column and the nullability which means, that column can contain null values or not. syntax : DESCRIBE tablename; OR DESC tablename;
  • 7. 7 EXPERIMENT NO. 2 Represent all entities relationships Relationship : A Relationship describes relation between entities. Relationship is represented using diamonds or rhombus. There are four types of relationships : • One to one • One to many • Many to many • Many to one One to one Relationship :A one-to-one relationship is mostly used to split an entity in two to provide information concisely and make it more understandable. The figure below shows an example of a one-to-one relationship. Example : One to many Relationship :A one-to-many relationship refers to the relationship between two entities X and Y in which an instance of X may be linked to many instances of Y, but an instance of Y is linked to only one instance of X. The figure below shows an example of a one-to-many relationship. Example : Student can enroll for only one course .
  • 8. 8 Many-to-Many cardinality :A many-to-many relationship refers to the relationship between two entities X and Y in which X may be linked to many instances of Y and vice versa. The figure below shows an example of a many-to-many relationship. Note that a many-to-many relationship is split into a pair of one-to-many relationships in a physical Entity Relationship Diagram. Example : Employee can assign by many projects and project can have many employees. Many-to-one relationship:When more than one instance of the entity on the left, and only one instance of an entity on the right associates with the relationship then it is known as a many-to- one relationship. Example :Student enrolls for only one course, but a course can have many students.
  • 9. 9 EXPERIMENT NO. 3 Writing SQL statements Using ORACLE /MYSQL: 1. Perform the following operation for demonstrating the insertion, updation ,deletion andalter . INSERTION Query Syntax : INSERT INTO table(column1, column2, …) VALUES (value1, value2, …); • Inserting only values Example : Output : ROLL_NO NAME DEPT SEC PHONE 101 Alia CSE B 9876540010 102 Alisha ME A 9876541110 • Inserting values in only specified columns Example : Select * from college; INSERT INTO college(ROLL_NO, NAME, SEC)VALUES(‘104,’Aditya','A'); INSERT INTO college(ROLL_NO, NAME, SEC)VALUES(‘105,’NITYA','B'); INSERT INTO college(ROLL_NO, NAME, SEC)VALUES(‘106,’Anaya','C'); Insert into college values(101,"Alia","CSE","B",9876540010) Insert into college values(102,"Alisha","ME","A",9876541110)
  • 10. 10 Output : ROLL_NO NAME DEPT SEC PHONE 101 Alia CSE B 9876540010 102 Alisha ME A 9876541110 104 Aditya NULL A NULL 105 Nitya NULL B NULL 106 Anaya NULL C NULL UPDATION Query : syntax : UPDATE table_name SET column1 = value1, column2 = value2, ...WHERE condition; • Updating single column : Output : ROLL_NO NAME DEPT SEC PHONE 101 Alia CSE B 9876540010 102 Alisha ME A 9876541110 Select*from college; UPDATE college SET NAME = 'Amit ' WHERE ROLL_NO = 104;
  • 11. 11 Select*from college; UPDATE college SET NAME = 'Atulya', DEPT = 'ECE' WHERE ROLL_NO = 105; ROLL_NO NAME DEPT SEC PHONE 104 Amit NULL A NULL 105 Nitya NULL B NULL 106 Anaya NULL C NULL • Updating multiple columns: Example : Output : ROLL_NO NAME DEPT SEC PHONE 101 Alia CSE B 9876540010 102 Alisha ME A 9876541110 104 Amit NULL A NULL 105 Atulya ECE B NULL 106 Anaya NULL C NULL DELETION Query :
  • 12. 12 Select*from college; DELETE FROM college WHERE NAME = 'Ananya'; syntax : DELETE FROM table_name WHERE condition; • Deleting single record: Example : Output : ROLL_NO NAME DEPT SEC PHONE 101 Alia CSE B 9876540010 102 Alisha ME A 9876541110 104 Amit NULL A NULL 105 Atulya ECE B NULL • Deleting multiple records: Output : Select*from college; DELETE FROM college WHERE SEC = 'A';
  • 13. 13 ROLL_NO NAME DEPT SEC PHONE 101 Alia CSE B 9876540010 105 Atulya ECE B NULL • Delete all of the records: 2. INTEGRITY CONSTRAINTS INTEGRITY CONSTRAINT : Integrity constraints are a set of rules. It is used to maintain the quality of information.integrity constraint is used to guard against accidental damage to the database.Constraints can be defined in two ways :- 1) The constraints can be specified immediately after the column definition. This is called column-level definition. 2) The constraints can be specified after all the columns are defined. This is called table-level definition. DATABASE CONSTRAINTS • Primary Key • Foreign Key • CHECK Constraint • UNIQUE Constraint • NOT NULL Constraint PRIMARY KEY : A primary key is a column or a group of columns used to identify a row uniquely in a table. A primary key constraint is the combination of a not-null constraint and a UNIQUE constraint. Example : Delete from college; OR Delete * from college; syntax : CREATE TABLE TABLE ( column_1 data_type PRIMARY KEY, column_2 data_type, … );
  • 14. 14 CREATE TABLE products (product_no INTEGER,description TEXT, product_cost NUMERIC); syntax : ALTER TABLE table_name ADD PRIMARY KEY (column_1, column_2); In case you want to specify the name of the primary key constraint, you use CONSTRAINT clause as follows: Define primary key when changing the existing table structure Example : When we want to add primary key constraint in the table : How to add an auto-incremented primary key to an existing table Remove primary key syntax : ALTER TABLE table_name DROP CONSTRAINT primary_key_constraint; FOREIGN KEY : Also called referential integrity . This constraint identifies any column referencing the PRIMARY KEY in another table. For a column to be defined as a Foreign Key, it should be a defined as a Primary Key in the table which it is referring. One or more columns can be defined as Foreign key. Define a group of columns as a foreign key : CREATE TABLE po_items ( po_no INTEGER, item_no INTEGER, product_no INTEGER, qty INTEGER, net_price NUMERIC, PRIMARY KEY (po_no, item_no)); syntax : CONSTRAINT constraint_name PRIMARY KEY(column_1, column_2,...); ALTER TABLE products ADD PRIMARY KEY (product_no); ALTER TABLE vendors ADD COLUMN ID SERIAL PRIMARY KEY; CREATE TABLE Orders (OrderID int NOT NULL, OrderNumber int NOT NULL,PersonID int, PRIMARY KEY (OrderID) ,FOREIGN KEY (PersonID) REFERENCES Persons(PersonID));
  • 15. 15 Add a foreign key constraint to an existing table : Drop existing foreign key constraint : CHECK Constraint : This constraint defines a business rule on a column. All the rows must satisfy this rule. The constraint can be applied for a single column or a group of columns. syntax:column_name data_type CONSTRAINT constraint_name CHECK(...) CHECK on ALTER TABLE : DROP a CHECK Constraint : UNIQUE Constraint : This constraint ensures that a column or a group of columns in each row have a distinct value. A column(s) can have a null value but the values cannot be duplicated. syntax : [CONSTRAINT constraint_name] UNIQUE(column_name) Creating a UNIQUE constraint on multiple columns : syntax : CREATE TABLE table (c1 data_type,c2 data_type,c3 data_type,UNIQUE (c2, c3)); UNIQUE Constraint on ALTER TABLE : DROP a Unique Constraint : CREATE TABLE child_table(c1 INTEGER PRIMARY KEY, c2 INTEGER,c3 INTEGER,FOREIGN KEY (c2, c3) REFERENCES parent_table (p1, p2)); ALTER TABLE child_table ADD CONSTRAINT constraint_name FOREIGN KEY (c1) REFERENCES parent_table (p1); ALTER TABLE child_table DROP CONSTRAINT constraint_fkey; ALTER TABLE Persons ADD CHECK (Age>=18); ALTER TABLE Persons DROP CHECK CHK_PersonAge; ALTER TABLE Persons ADD CONSTRAINT UC_Person UNIQUE (ID,LastName);
  • 16. 16 NOT NULL Constraint : This constraint ensures all rows in the table contain a definite value for the column which is specified as not null. Which means a null value is not allowed. syntax : [CONSTRAINT constraint name] NOT NULL Example : not-null constraint to columns of an existing table : Example : 3. Aggregate Functions Aggregate Functions: Aggregate functions perform a calculation on a set of rows and return a single row. You can use aggregate functions as expressions only in the following clauses i.e., SELECT clause, HAVING clause. There are five aggregate functions: • AVG() – returns the average value • COUNT() – returns the number of values. • MAX() – returns the maximum value. • MIN() – returns the minimum value. • SUM() – returns the sum of all or distinct value ALTER TABLE Persons DROP INDEX UC_Person; CREATE TABLE invoice(id serial PRIMARY KEY,product_id int NOT NULL,qty numeric NOT NULL CHECK(qty > 0),net_price numeric CHECK(net_price > 0) ); syntax : ALTER TABLE table_name ALTER COLUMN column_name_1 SET NOT NULL, ALTER COLUMN column_name_2 SET NOT NULL; ALTER TABLE production_orders ALTER COLUMN material_id SET NOT NULL, ALTER COLUMN start_date SET NOT NULL, ALTER COLUMN finish_date SET NOT NULL;
  • 17. 17 AVG(): The AVG() function allows you to calculate the average value of a numeric column. Output : COUNT(): The COUNT function returns the total number of values in the specified field. Output : MAX() : It returns the maximum value from the specified table field. Output : SELECTAVG(SALARY) "AVERAGE SAL" FROM empl; SELECT COUNT(*) FROM empl; 30000 MAX(Salary) syntax : AVG(column) 22000.0000 AVERAGE SAL syntax : COUNT(expression) 6 count(*) syntax : MAX(expression)
  • 18. 18 MIN(): The MIN function returns the minimum value in the specified table field. Output : SUM(): SUM function which returns the sum of all the values in the specified column. SUM works on numeric fields only. Null values are excluded from the result returned. Output : These functions are called aggregate functions because they operate on the aggregate of tuples. The result of an aggregate function is a single value. 4. SQL JOINS JOINS : join is used to combine columns from one (self-join) or more tables based on the values of the common columns between the tables. A JOIN is a means for combining fields fromtwo tables by using values common to each.There are four types of joins :- • INNER JOIN • LEFT JOIN • RIGHT JOIN • FULL JOIN SELECT MIN(Salary)FROM empl; SELECT SUM(Salary) "Total Salary" from empl; syntax : MIN(expression) 12000 MIN(Salar y) syntax : SUM(expression) 132000 Total Salary
  • 19. 19 sample tables :Suppose we have two tables called basket_a and basket_b that stores fruits: INNER JOIN : This type of join returns those records which have matching values in both tables. Output : id_a fruit_a id_b fruit_b 1 apple 2 apple 2 orange 1 orange CREATE TABLE basket_b (id INT PRIMARY KEY,fruit VARCHAR (100) NOT NUL); INSERT INTO basket_b (id, fruit)VALUES(1, 'Orange'), INSERT INTO basket_b (id, fruit)VALUES(2, 'Apple'), INSERT INTO basket_b (id, fruit)VALUES(3, 'Watermelon'), INSERT INTO basket_b (id, fruit)VALUES(4, 'Pear'); CREATE TABLE basket_a (id INT PRIMARY KEY, fruit VARCHAR (100) NOT NUL); INSERT INTO basket_a (id, fruit)VALUES(1, 'Apple'), INSERT INTO basket_a (id, fruit)VALUES (2, 'Orange'), INSERT INTO basket_a (id, fruit)VALUES(3, 'Banana'), INSERT INTO basket_a (id, fruit)VALUES (4, 'Cucumber'); SELECT a.id id_a, a.fruit fruit_a, b.id id_b, b.fruit fruit_b FROM basket_a a INNER JOIN basket_b b ON a.fruit = b.fruit;
  • 20. 20 LEFT JOIN : returns all rows from the left table, even if there are no matches in the right table. Output : id_a fruit_a id_b fruit_b 1 apple 2 apple 2 orange 1 orange 3 banana null null 4 cucumber null null RIGHT JOIN : returns all rows from the right table, even if there are no matches in the left table. Output : SELECT a.id id_a, a.fruit fruit_a, b.id id_b, b.fruit fruit_b FROM basket_a a LEFT JOIN basket_b b ON a.fruit = b.fruit; SELECT a.id id_a, a.fruit fruit_a, b.id id_b, b.fruit fruit_b FROM basket_a a RIGH T JOIN basket_b b ON a.fruit = b.fruit;
  • 21. 21 id_a fruit_a id_b fruit_b 2 orange 1 orange 1 apple 2 apple null null 3 watermelon null null 4 pear FULL JOIN: returns rows when there is a match in one of the tables. Output : id_a fruit_a id_b fruit_b 3 banana null null 4 cucumber null null null null 3 watermelon null null 4 pear SELECT a.id id_a, a.fruit fruit_a, b.id id_b, b.fruit fruit_b FROM basket_a a FULL JOIN basket_b b ON a.fruit = b.fruit WHERE a.id IS NULL OR b.id IS NULL;
  • 22. 22 EXPERIMENT NO. 4 Queries using Logical Operator There are three Logical Operators namely, AND, OR, and NOT. These operators compare two conditions at a time to determine whether a row can be selected for the output. When retrieving data using a SELECT statement, you can use logical operators in the WHERE clause, which allows you to combine more than one condition. LOGICAL OPERATORS DESCRIPTION OR For the row to be selected at least one of the conditions must be true AND For a row to be selected all the specified conditions must be true NOT For a row to be selected the specified condition must be false Examples : This is our given Database table named as abc. select *from abc where marks=70 OR marks=80; Output :
  • 23. 23 Output : Output : select *from abc where dept="EE" AND marks>=75; select *from abc where NOT dept="EE";
  • 24. 24 mysql > DROP USER ‘username’@‘localhost’; mysql>SHOW GRANTS username; EXPERIMENT NO. 5 How To Create a New User and their roles Create a New User : At this point new user has no permissions to do anything with the databases. In fact, even if new user tries to login (with the password, password), they will not be able to reach the MySQL shell. provide the user with access to the information : asterisks in this command refer to the database and table that they can access .Once you have finalized the permissions that you want to set up for your new users, always be sure to reload all the privileges.Your changes will now be in effect. How To Grant Different User Permissions • ALL PRIVILEGES - as we saw previously, this would allow a MySQL user full access to a designated database (or if no database is selected, global access across the system) • CREATE - allows them to create new tables or databases • DROP - allows them to them to delete tables or databases • DELETE - allows them to delete rows from tables • INSERT - allows them to insert rows into tables • SELECT - allows them to use the SELECT command to read through databases • UPDATE - allow them to update table rows • GRANT OPTION - allows them to grant or remove other users’ privileges To provide a specific user with a permission, you can use this framework: If you need to revoke a permission, the structure is almost identical to granting it: You can review a user’s current permissions by running the following: Just as you can delete databases with DROP, you can use DROP to delete a user altogether: To test out your new user, log out by typing: mysql > CREATE USER 'newuser'@'localhost' IDENTIFIED BY 'password'; mysql > GRANT ALL PRIVILEGES ON * . * TO 'newuser'@'localhost'; mysql > FLUSH PRIVILEGES; mysql > GRANT type_of_permission ON database_name.table_name TO ‘username’@'localhost’; mysql > REVOKE type_of_permission ON database_name.table_name FROM ‘username’@‘localhost’;
  • 25. 25 log back in with this command in terminal: mysql>quit mysql >mysql -u [username] -p
  • 26. 26 EXPERIMENT NO. 6 Practice Queries using Group By, Having, Order By Functions GROUP BY : The GROUP BY clause divides the rows returned from the SELECT statement into groups. For each group, you can apply an aggregate function .The GROUP BY clause must appear right after the FROM or WHERE clause. Example-1 : SELECT customer_id FROM payment GROUP BY customer_id; Output : . . . . customer_id 1 455 2 233 3 234 4 45 5 455 6 451 7 123 8 234 9 567
  • 27. 27 Example-2 : SELECT customer_id, SUM (amount) FROM payment GROUP BY customer_id; Output: customer_id sum 455 12 233 12 234 56 45 564 455 45 451 34 123 34 234 22 567 34 23 5 66 HAVING : We often use the HAVING clause in conjunction with the GROUP BY clause to filter group rows that do not satisfy a specified condition. Example-1 : Output : Syntax : SELECT column_1, aggregate_function (column_2) FROM tbl_name GROUP BY column_1 HAVING condition; SELECT customer_id, SUM (amount) FROM payment GROUP BY customer_id HAVING SUM (amount) > 200;
  • 28. 28 customer_id sum 526 234 148 232 Example-2: Output: store_id sum 1 326 ORDER BY :The ORDER BY clause allows you to sort rows returned from a SELECT statement in ascending or descending order based on the specified criteria. Example-1 : SELECT first_name, last_name FROM customer ORDER BY first_name ASC; Output : ... first_name last_name 1 Aaron Selby 2 Adam Gooch 3 Aram Clary 4 Agnes Bishop 5 Alan Kahn Syntax : SELECT column_1, column_2 FROM table_name ORDER BY column_1 [ASC | DESC], column_2 [ASC | DESC]; SELECT store_id COUNT(customer_id) FROM customer GROUP BY store_id HAVING COUNT (customer_id) > 300;
  • 29. 29 Example-2 : SELECT first_name, last_name FROM customer ORDER BY last_name DESC; Output : first_name last_name 1 Aaron Selby 2 Alan Kahn 3 Adam Gooch 4 Aram Clary 5 Agnes Bishop
  • 30. 30 EXPERIMENT NO. 7 TRIGGERS TRIGGERS : A SQL trigger is a database object just like a stored procedure, or we can say it is a special kind of stored procedure which fires when an event occurs in a database. We can execute a SQL query that will "do something" in a database when an event is fired. Types of Triggers 1. DDLTrigger 2. DML Trigger TRIGGERS PROCEDURES They are automatically executed on occurrence ofspecified event. They can be executed whenever required. Triggers can’t be called inside a procedure. But, you can call a procedure inside a trigger. We cannot pass parameters to triggers. We can pass parameters to procedures. Triggers never return values on execution. Procedure may return value/s on execution.
  • 31. 31 Creating a trigger function : SQL CREATE TRIGGER statement : Example : CREATE TABLE employees( id SERIAL PRIMARY KEY, first_name VARCHAR(40) NOT NULL, last_name VARCHAR(40) NOT NULL ); INSERT INTO employees (first_name, last_name) VALUES ('John', 'Doe'); INSERT INTO employees (first_name, last_name) VALUES ('Lily', 'Bush'); SELECT * FROM employees; CREATE TRIGGER trigger_name {BEFORE | AFTER | INSTEAD OF} {event [OR ...]} ON table_name [FOR [EACH] {ROW | STATEMENT}] EXECUTE PROCEDURE trigger_function CREATE FUNCTION trigger_function() RETURNS trigger AS
  • 32. 32 Output : id first_name last_name 1 john doe 2 lily blush UPDATE QUERY : SELECT * FROM employees; Output : id first_name last_name 1 john doe 2 lily brown UPDATE employees SET last_name = 'Brown' WHERE ID = 2;
  • 33. 33 Advantages of Triggers : • Trigger generates some derived column values automatically • Enforces referential integrity • Event logging and storing information on table access • Auditing • Synchronous replication of tables • Imposing security authorizations • Preventing invalid transactions
  • 34. 34 EXPERIMENT NO. 8 Applying table creation with select, Insert data using select, Renaming on database Tables CREATE TABLE with SELECT :You can create one table from another by adding a SELECT statement at the end of the CREATE TABLE statement: Syntax : CREATE TABLE new_tbl [AS] SELECT * FROM orig_tbl; Example : we already have a table named as dept , now with the help of dept table we will create new table named bar. INSERT DATA using SELECT : Insert data into a table using the SELECT statement. Example : CREATE TABLE bar (m INT) SELECT * FROM dept; Syntax : INSERT INTO table_name(column_name) SELECT tbl_name.col_name FROM some_table tbl_name WHERE condition; INSERT INTO bar (m, dept_id) SELECT '101', ea.dept_id FROM dept ea WHERE ea.dept_name = 'CSE'; INSERT INTO bar (m, dept_id) SELECT '101', ea.dept_id FROM dept ea WHERE ea.dept_name = 'IT'; INSERT INTO bar (m, dept_id) SELECT '104', ea.dept_id FROM dept ea WHERE ea.dept_name = 'ME';
  • 35. 35 Output : RENAME TABLE : To rename the existing table . Syntax : RENAME TABLE tbl_name TO new_tbl_name ; Example : Output : RENAME TABLE bar TO clg;
  • 36. 36 EXPERIMENT NO. 9 Referential Integrity Constraint Referential Integrity Constraint : Referential Integrity is set of constraints applied to foreign key which prevents entering a row in child table (where you have foreign key) for which you don't have any corresponding row in parent table .Referential Integrity prevents your table from having incorrect or incomplete relationship . Referential Integrity example : • Create Table command: CREATE TABLE Emp (emp_id INT NOT NULL, emp_name VARCHAR(256), dept_id INT, FOREIGN KEY (dept_id) REFERENCES Dept(dept_id) ) ENGINE=INNODB; CREATE TABLE Dept (dept_id INT NOT NULL, dept_name VARCHAR(256), PRIMARY KEY (dept_id)) ENGINE=INNODB;
  • 37. 37 • Insert Query : insert into dept (dept_id,dept_name) values(101,"CSE"); insert into dept (dept_id,dept_name) values(102,"EE"); insert into dept (dept_id,dept_name) values(103,"ECE"); insert into dept (dept_id,dept_name) values(104,"ME"); insert into dept (dept_id,dept_name) values(105,"IT"); insert into emp (emp_id,dept_id,emp_name) values(1,105,"amita"); insert into emp (emp_id,dept_id,emp_name) values(2,104,"anita"); insert into emp (emp_id,dept_id,emp_name) values(3,103,"anitya"); insert into emp (emp_id,dept_id,emp_name) values(4,102,"ananya"); insert into emp (emp_id,dept_id,emp_name) values(5,101,"amaaya");
  • 38. 38 • Delete command: Advantages of referential Integrity : 1. Prevents the entry of duplicate data 2. Prevents one table from pointing to a nonexistent field in another table 3. Guarantees consistency between "partnered" tables 4. Prevents the deletion of a record that contains a value referred to by a foreign key in another table 5. Prevents the addition of a record to a table that contains a foreign key unless there is a primary key in the linked table mysql> DELETE FROM Dept; Query OK, 1 row affected (0.05 sec) mysql> SELECT * FROM Emp; Empty SET (0.00 sec)
  • 39. 39 EXPERIMENT NO. 10 Applying Insert, Select, Distinct Clause, Where Clause on database Tables Insert : The INSERT INTO statement is used to insert new records in a table. Syntax : INSERT INTO table(column1, column2, …) VALUES (value1, value2, …); • Inserting only values Example : Output : ROLL_NO NAME DEPT SEC PHONE 101 Alia CSE B 9876540010 102 Alisha ME A 9876541110 • Inserting values in only specified columns Example : Select Statement :The SELECT statement is used to select data from a database.The data returned is stored in a result table, called the result-set. Syntax : SELECT column1, column2, ...FROM table_name; Example : INSERT INTO college (ROLL_NO, NAME, SEC) VALUES (‘104,’Aditya,A); INSERT INTO college (ROLL_NO, NAME, SEC) VALUES (‘105,’NITYA,B); INSERT INTO college (ROLL_NO, NAME, SEC) VALUES (‘106,’Anaya,C); Insert into college values(101,Alia,CSE,B,9876540010); Insert into college values(102,Alisha,ME,A,9876541110);
  • 40. 40 Output : ROLL_NO NAME DEPT SEC PHONE 101 Alia CSE B 9876540010 102 Alisha ME A 9876541110 104 Aditya NULL A NULL 105 Nitya NULL B NULL 106 Anaya NULL C NULL Distinct Statement :The SELECT DISTINCT statement is used to return only distinct (different) values.Inside a table, a column often contains many duplicate values; and sometimes you only want to list the different (distinct) values. Syntax : SELECT DISTINCT column1, column2, ...FROM table_name; Example : Output : SEC A B C Select * from college; SELECT DISTINCT SEC FROM college;
  • 41. 41 Where statement : The WHERE clause is used to filter records.The WHERE clause is used to extract only those records that fulfill a specified condition. Syntax : SELECT column1, column2, ...FROM table_nameWHERE condition; Example : Output : ROLL_NO NAME DEPT SEC PHONE 106 Anaya NULL C NULL SELECT * FROM college WHERE SEC='C';
  • 42. 42 EXPERIMENT NO. 11 GROUP Functions GROUP Functions: Group functions are built-in SQL functions that operate on groups of rows and return one value for the entire group. These functions are: • COUNT • MAX • MIN • AVG • SUM • DISTINCT COUNT (): This function returns the number of rows in the table that satisfies the condition specified in the WHERE condition. If the WHERE condition is not specified, then the query returns the total number of rows in the table. Example : DISTINCT(): This function is used to select the distinct rows. MAX(): This function is used to get the maximum value from a column. Example : MIN(): This function is used to get the minimum value from a column. Example : AVG(): This function is used to get the average value of a numeric column. Example : SUM(): This function is used to get the sum of a numeric column Example : select count(id) from b; select distinct name from a; select max(id) from a; select min(id) from a; select avg(id) from a; select sum(id) from a;