0% found this document useful (0 votes)
13 views

DBMS Lab File - 4thsem

Uploaded by

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

DBMS Lab File - 4thsem

Uploaded by

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

Index

Sr. No. List of Experiments Page No. Signature


1. Design a Database and create required table. For e.g. Bank, College
Database. 1-3

2. Write a SQL statement for implementing ALTER, UPDATE and DELETE.


3-5

3. Perform the following operations for demonstrating the insertion,


updation and deletion. 5-9

4. Write the query to implement the concept of Integrity constrains. 9-12


5. Apply the constrains like Primary key, Foreign key, NOT NULL to the
tables. 12-14

6. Using the referential integrity constraints. 14-17


7. Write query for implementing the following functions: MAX( ), MIN( ),
AVG( ) and COUNT( ). 18-19

8. Perform the queries for triggers. 20-22


9. Write the queries to implement the joins. 22-25
10. Write the query to create the views. 25-27
11. Write the query for creating the users and their roles. 27-29
Data Base Designing Project:

For better understanding students (group of 3-4 students) should


design data base for any database project, understand the requirement
and design methodology of project by its own.

Some example of data base design project like:

College management system, Inventory management system and


Hospital management system
Que.1. To Design a Database and create required table. 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.

Verify MySQL installation:

 Step- 1 : Open from start

 Step-2 : enter the password you have set during installation .

 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 :

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)));

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;


Que.2. SQL statement for implementing ALTER, UPDATE and DELETE.
Database Language : Database languages are used to read, update and store data in a
database. Read, Update, Manipulate, and Store data in a database using Database
Languages.there are four types of DBMS language :

1. DDL (Data Definition Language)


2. DML (Data Manipulation Language)
3. DCL (Data Control Language)
4. TCL (Transaction Control Language)

DDL (Data Definition language) - DDL is used when we need to create database and tables,
alter them , drop them and rename the table .

 CREATE: Create new database, table.

CREATE DATABASE goeduhub;


CREATE TABLE bank (id INT(16) PRIMARY KEY AUTO_INCREMENT,name
VARCHAR(255) NOT NULL );

 ALTER: Alter existing database, table.

ALTER TABLE bank ADD COLUMN lastname VARCHAR(255) NOT NULL;

 DROP: Drop the database

DROP DATABASE goeduhub;


DROP TABLE bank;

 RENAME: Set a new name for the table.


RENAME TABLE bank TO student;

 TRUNCATE : To delete tables in a database instance

TRUNCATE student;
DML (Data Manipulation Language) - DML language used to manipulate the database like
inserting data, updating table, retrieving record from a table .

 SELECT: Retrieve data from the database

SELECT * FROM student;

 INSERT: Insert data

INSERT INTO student (name, lastname) VALUES ('nams', 'Shivi');

 UPDATE: Update data

UPDATE student SET name = 'Dia' WHERE lastname = 'Shivi';

 DELETE: Delete all records

DELETE FROM student WHERE name = 'Dia';

 MERGE: It performs UPSERT (update and insert ) operation

DCL (Data Control Language) : Grant privilege to a user using the GRANT
statement.revoke the privilege using the REVOKE statement.

 GRANT: Give privilege to access the database.

CREATE USER 'dia'@'localhost' IDENTIFIED BY '123';


GRANT ALL PRIVILEGES ON student TO 'dia'@'localhost';
FLUSH PRIVILEGES;

 REVOKE: Take back the privilege to access the database.

REVOKE ALL PRIVILEGES ON student* FROM 'dia'@'localhost';


FLUSH PRIVILEGES;
TCL (Transaction Control Language):Manage transactions in the Database using the
Transaction Control Language:

 COMMIT: Save the work.

START TRANSACTION;
INSERT INTO student (name, lastname) VALUES ('Dia', 'Shivi');
COMMIT;
 SAVEPOINT: Set a point in transaction to rollback later
 ROLLBACK: Restores since last commit

START TRANSACTION;
INSERT INTO student (name, lastname) VALUES ('Dia', 'Shivi');
ROLLBACK;

Que.3. Perform the following operations for demonstrating the insertion,


updation and deletion.
INSERTION Query

Syntax : INSERT INTO table(column1, column2, …)


VALUES (value1, value2, …);

 Inserting only values

Example :

Insert into college values(101,"Alia","CSE","B",9876540010)

Insert into college values(102,"Alisha","ME","A",9876541110)

Output :

ROLL_NO NAME DEPT SEC PHONE

101 Alia CSE B 9876540010

102 Alisha ME A 9876541110

 Inserting values in only specified columns

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');
Select * from college;

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 :

UPDATE college SET NAME = 'Amit ' WHERE ROLL_NO = 104;

Select*from college;

Output :

ROLL_NO NAME DEPT SEC PHONE

101 Alia CSE B 9876540010

102 Alisha ME A 9876541110


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 :

UPDATE college SET NAME = 'Atulya', DEPT = 'ECE' WHERE ROLL_NO = 105;

Select*from college;

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 :

syntax : DELETE FROM table_name WHERE condition;

 Deleting single record:


Example :

DELETE FROM college WHERE NAME = 'Ananya';

Select*from college;

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:

DELETE FROM college WHERE SEC = 'A';

Select*from college;

Output :

ROLL_NO NAME DEPT SEC PHONE

101 Alia CSE B 9876540010

105 Atulya ECE B NULL

 Delete all of the records:


Delete from college;
OR
Delete * from college;

Que.4. Write the query to implement the concept of Integrity constrains.


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.

syntax
: CREATE TABLE TABLE ( column_1 data_type PRIMARY KEY, column_
2 data_type, …);
Example :

CREATE TABLE po_items ( po_no INTEGER, item_no INTEGER, product_no


INTEGER, qty INTEGER, net_price NUMERIC, PRIMARY KEY (po_no,
item_no));

In case you want to specify the name of the primary key constraint, you
use CONSTRAINT clause as follows:

syntax
: CONSTRAINT constraint_name PRIMARY KEY(column_1, column_2,..
.);
Define primary key when changing the existing table structure

syntax : ALTER TABLE table_name ADD PRIMARY KEY (column_1,


column_2);
Example :

CREATE TABLE products (product_no INTEGER,description TEXT,


product_cost NUMERIC);

When we want to add primary key constraint in the table :

ALTER TABLE products ADD PRIMARY KEY (product_no);

How to add an auto-incremented primary key to an existing table

ALTER TABLE vendors ADD COLUMN ID SERIAL PRIMARY KEY;

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.

CREATE TABLE Orders (OrderID int NOT NULL, OrderNumber


int NOT NULL,PersonID int, PRIMARY KEY (OrderID)
,FOREIGN KEY (PersonID) REFERENCES Persons(PersonID));

Define a group of columns as a foreign key :

CREATE TABLE child_table(c1 INTEGER PRIMARY KEY,


c2 INTEGER,c3 INTEGER,FOREIGN KEY (c2, c3)
REFERENCES parent_table (p1, p2));

Add a foreign key constraint to an existing table :

ALTER TABLE child_table


ADD CONSTRAINT constraint_name FOREIGN KEY (c1) REFERENCES parent_table (p1);

Drop existing foreign key constraint :


ALTER TABLE child_table

DROP CONSTRAINT constraint_fkey;

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 :

ALTER TABLE Persons ADD CHECK (Age>=18);

DROP a CHECK Constraint :

ALTER TABLE Persons DROP CHECK CHK_PersonAge;

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 :

ALTER TABLE Persons


ADD CONSTRAINT UC_Person UNIQUE (ID,LastName);

DROP a Unique Constraint :

ALTER TABLE Persons


DROP INDEX UC_Person;

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 :

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) );

not-null constraint to columns of an existing table :

syntax :
ALTER TABLE table_name
ALTER COLUMN column_name_1 SET NOT NULL,
ALTER COLUMN column_name_2 SET NOT NULL;
Example :

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;

Que.5. Apply the constrains like Primary key, Foreign key, NOT NULL to
the tables.
Constraints : SQL constraints are used to specify rules for data in a table.These are used to
limit the type of data that can go into a table. This ensures the accuracy and reliability of the
data in the database.Constraints could be either on a column level or a table level. The
column level constraints are applied only to one column, whereas the table level constraints
are applied to the whole table.Constraints can be divided into the following two types :

1. Column level constraints: Limits only column data.


2. Table level constraints: Limits whole table data.

Following are the most used constraints that can be applied to a table.

 NOT NULL
 UNIQUE
 PRIMARY KEY
 FOREIGN KEY
 CHECK
 DEFAULT
NOT NULL : NOT NULL constraint restricts a column from having a NULL value.
Once NOT NULL constraint is applied to a column, you cannot pass a null value to that
column. It enforces a column to contain a proper value.

CREATE TABLE Student(stu_id int NOT NULL, Name varchar(60),


Age int);

UNIQUE : UNIQUE constraint ensures that a field or column will only have unique values.
A UNIQUE constraint field will not have duplicate data. This constraint can be applied at
column level or table level.

CREATE TABLE Student(stu_id int NOT NULL UNIQUE, Name


varchar(60), Age int);
Applying Unique constraint Column wise :

ALTER TABLE Student ADD UNIQUE(stu_id);

PRIMARY KEY : Uniquely identifies each row/record in a database table. A combination


of a NOT NULL and UNIQUE. this constraint is used to specify a field in a table as primary
key.

CREATE TABLE Student(ID int(6) NOT NULL UNIQUE,NAME


varchar(10),ADDRESS varchar(20),PRIMARY KEY(ID));
Applying Primary key constraint Column wise :

ALTER table Student ADD PRIMARY KEY (s_id);

FOREIGN KEY : FOREIGN KEY is used to relate two tables. FOREIGN KEY constraint
is also used to restrict actions that would destroy links between tables. Foreign Key is a field
in a table which uniquely identifies each row of a another table

CREATE table bank(bank_id int PRIMARY KEY, emp_name


varchar(60) NOT NULL,stud_id int FOREIGN KEY REFERENCES
college(coll_id));
Applying Foreign key constraint column wise :

ALTER table bank ADD FOREIGN KEY (coll_id) REFERENCES


college(coll_id);
CHECK : CHECK constraint is used to restrict the value of a column between a range. It
performs check on the values, before storing them into the database. Its like condition
checking before saving data into a column.

CREATE table Student(stu_id int NOT NULL CHECK(stu_id >


0),Name varchar(60) NOT NULL,Age int);
Applying Check constraint column wise :

ALTER table Student ADD CHECK(stu_id > 0);


DEFAULT : Sets a default value for a column when no value is specified. This constraint is
used to provide a default value for the fields.

CREATE TABLE Student(ID int(6) NOT NULL,NAME varchar(10) NOT


NULL,AGE int DEFAULT 18);

Que.6. Using the referential integrity constraints.


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 Dept (dept_id INT NOT NULL,


dept_name
VARCHAR(256), PRIMARY KEY (dept_id)) ENGINE=INNODB;

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;
 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");


 Delete command:

mysql> DELETE FROM Dept;


Query OK, 1 row affected (0.05 sec)

mysql> SELECT * FROM Emp;


Empty SET (0.00 sec)

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
Que.7. Write query for implementing the following functions: MAX( ),
MIN( ), AVG( ) and COUNT( ).
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 values.

AVG(): The AVG() function allows you to calculate the average value of a numeric column.

syntax : AVG(column)

SELECT AVG(SALARY) "AVERAGE SAL" FROM empl;

Output :

AVERAGE
SAL

22000.0000

COUNT(): The COUNT function returns the total number of values in the specified field.

syntax : COUNT(expression)

SELECT COUNT(*) FROM empl;

Output :

count(*)

6
MAX() : It returns the maximum value from the specified table field.

syntax : MAX(expression)

SELECT MAX(Salary) FROM empl;

Output :

MAX(Salary)

30000

MIN(): The MIN function returns the minimum value in the specified table field.

syntax : MIN(expression)

SELECT MIN(Salary)FROM empl;

Output :

MIN(Salary)

12000

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.

syntax : SUM(expression)

SELECT SUM(Salary) "Total Salary" from empl;

Output :

Total Salary

132000

These functions are called aggregate functions because they operate on the aggregate of tuples.
The result of an aggregate function is a single value.
Que.8. Perform the queries for triggers.
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. DDL Trigger
2. DML Trigger

TRIGGERS PROCEDURES

They are automatically executed on occurrence of They can be executed whenever


specified event. required.

But, you can call a procedure inside a


Triggers can't be called inside a procedure.
trigger.

We can pass parameters to


We can not pass parameters to triggers.
procedures.

Procedure may return value/s on


Trigger never return value on execution.
execution.

Creating a trigger function :

CREATE FUNCTION trigger_function()

RETURNS trigger AS
SQL CREATE TRIGGER statement :

CREATE TRIGGER trigger_name

{BEFORE | AFTER | INSTEAD OF} {event [OR ...]}

ON table_name

[FOR [EACH] {ROW | STATEMENT}]

EXECUTE PROCEDURE trigger_function

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;

Output :

id first_name last_name

1 john doe

2 lily blush
UPDATE QUERY :

UPDATE employees

SET last_name = 'Brown'

WHERE ID = 2;

SELECT * FROM employees;

Output :

id first_name last_name

1 john doe

2 lily brown

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

Que.9. Write the queries to implement the joins.

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
from two tables by using values common to each. There are four types of joins :-

 INNER JOIN
 LEFT JOIN
 RIGHT JOIN
 FULL JOIN
sample tables :Suppose we have two tables called basket a and basket b that stores fruits:

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');

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');

INNER JOIN : This type of join returns those records which have matching values in both
tables.

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;

Output :

id_a fruit_a id_b fruit_b

1 apple 2 apple

2 orange 1 orange

LEFT JOIN : returns all rows from the left table, even if there are no matches in the right
table.

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;
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.

SELECT a.id id_a, a.fruit fruit_a, b.id id_b, b.fruit fruit_b FROM basket_a a RIGHT
JOIN basket_b b ON a.fruit = b.fruit;

Output :

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.

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;
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

Que.10. Write the query to create the views.


VIEWS
VIEW : Views are small part of sql . In SQL views are kind of virtual tables. A view also
has rows and columns as they are in a real table in the database. We can create a view by
selecting fields from one or more tables present in the database.

syntax : CREATE VIEW view_name AS SELECT column1, column2, ...


FROM table_name WHERE condition;
Example :

CREATE VIEW stu_View AS SELECT NAME, ADDRESS FROM college WHERE S_ID
< 5;

to see the result :

SELECT * FROM stu_view;

Output :
name address

ani goa

nia chennai

kia delhi

ishi bhutan

Creating view from multiple table :

CREATE VIEW stu_View AS


SELECT college.NAME, college.ADDRESS, bank.MARKS
FROM college, bank WHERE college.NAME = bank.NAME;

to see result :

SELECT * From stu_view;

Output :

name address marks

ani goa 99

nia chennai 98

kia delhi 89

ishi bhutan 70

DELETING VIEWS:

syntax : DROP VIEW view_name;


Example :
Drop VIEW stu_view;

UPDATING VIEWS :

 Insertion :

syntax :
INSERT INTO view_name(column1, column2 , column3,..)
VALUES(value1, value2, value3..);

 Deleting a row from a View:

syntax : DELETE FROM view_name WHERE condition;

Que.11. Write the query for creating the users and their roles.

How To Create a New User and their roles-


Create a New User :

mysql > CREATE USER 'newuser'@'localhost' IDENTIFIED BY


'password';
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 :

mysql > GRANT ALL PRIVILEGES ON * . * TO


'newuser'@'localhost';

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.

mysql > FLUSH PRIVILEGES;

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:

mysql > GRANT type_of_permission ON database_name.table_name


TO ‘username’@'localhost’;

If you need to revoke a permission, the structure is almost identical to granting


it:

mysql > REVOKE type_of_permission ON database_name.table_name


FROM ‘username’@‘localhost’;

You can review a user’s current permissions by running the following:

mysql>SHOW GRANTS username;

Just as you can delete databases with DROP, you can use DROP to delete a
user altogether:

mysql > DROP USER ‘username’@‘localhost’;

To test out your new user, log out by typing:

mysql>quit

log back in with this command in terminal:

mysql >mysql -u [username] -p

You might also like