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

DBMS Practicle File Ex8

Uploaded by

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

DBMS Practicle File Ex8

Uploaded by

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

Experiment-1

Installing MYSQL:-
Installation steps for MySql:

• Download MySql from https://dev.mysql.com/downloads/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.
Experiment-2

ER model
o ER model stands for an Entity-Relationship model. It is a high-level data model. This
model is used to define the data elements and relationship for a specified system.
o It develops a conceptual design for the database. It also develops a very simple and easy
to design view of data.
o In ER modeling, the database structure is portrayed as a diagram called an entity-
relationship diagram.
o An Entity Relationship Diagram (ERD) is a visual representation of different entities
within a system and how they relate to each other.

For example, Suppose we design a school database. In this database, the student will be an
entity with attributes like address, name, id, age, etc. The address can be another entity with
attributes like city, street name, pin code, etc and there will be a relationship between them.

Component of ER Diagram
1. Entity:

An entity may be any object, class, person or place. In the ER diagram, an entity can be
represented as rectangles.

Consider an organization as an example- manager, product, employee, department etc. can be


taken as an entity.

a. Weak Entity

An entity that depends on another entity called a weak entity. The weak entity doesn't contain
any key attribute of its own. The weak entity is represented by a double rectangle.

2. Attribute

The attribute is used to describe the property of an entity. Eclipse is used to represent an
attribute.

For example, id, age, contact number, name, etc. can be attributes of a student.
a. Key Attribute

The key attribute is used to represent the main characteristics of an entity. It represents a primary
key. The key attribute is represented by an ellipse with the text underlined.

b. Composite Attribute

An attribute that composed of many other attributes is known as a composite attribute. The
composite attribute is represented by an ellipse, and those ellipses are connected with an ellipse.
c. Multivalued Attributevolume is gedempt

An attribute can have more than one value. These attributes are known as a multivalued attribute.
The double oval is used to represent multivalued attribute.

For example, a student can have more than one phone number.

For example, a teacher entity can have multiple subject values.

d. Derived Attribute

An attribute that can be derived from other attribute is known as a derived attribute. It can be
represented by a dashed ellipse.

For example, A person's age changes over time and can be derived from another attribute like
Date of birth.
3. Relationship

A relationship is used to describe the relation between entities. Diamond or rhombus is used to
represent the relationship.

Types of relationship are as follows:

Recursive Relationship

If the same entity participates more than once in a relationship it is known as a recursive
relationship. In the below example an employee can be a supervisor and be supervised, so there
is a recursive relationship.

a. One-to-One Relationship

When only one instance of an entity is associated with the relationship, then it is known as one to
one relationship.

For example, A female can marry to one male, and a male can marry to one female.
b. One-to-many relationship

When only one instance of the entity on the left, and more than one instance of an entity on the
right associates with the relationship then this is known as a one-to-many relationship.

For example, Scientist can invent many inventions, but the invention is done by the only
specific scientist.

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

For example, Student enrolls for only one course, but a course can have many students.

d. Many-to-many relationship

When more than one instance of the entity on the left, and more than one instance of an entity on
the right associates with the relationship then it is known as a many-to-many relationship.

For example, Employee can assign by many projects and project can have many employees.
Experiment-3

1. Writing SQL statements Using MYSQL:

CREATE DATABASE ORG;

USE ORG;

CREATE TABLE Worker (

WORKER_ID INT NOT NULL PRIMARY KEY

AUTO_INCREMENT,

FIRST_NAME CHAR(25),

LAST_NAME CHAR(25),

SALARY INT(15),

JOINING_DATE DATETIME,

DEPARTMENT CHAR(25)

);

INSERTION Query-

INSERT INTO Worker

(WORKER_ID, FIRST_NAME, LAST_NAME, SALARY, JOINING_DATE, DEPARTMENT)


VALUES

(001, 'Monika', 'Arora', 100000,'14-02-20 09.00.00', 'HR'),

(002, 'Niharika', 'Verma', 80000,'14-06-11 09.00.00', 'Admin'),

(003, 'Vishal', 'Singhal', 300000,'14-02-20 09.00.00', 'HR'),

(004, 'Amitabh', 'Singh', 500000,'14-02-20 09.00.00', 'Admin'),

(005, 'Vivek', 'Bhati', 500000,'14-06-11 09.00.00', 'Admin'),

(006, 'Vipul', 'Diwan', 200000,'14-06-11 09.00.00', 'Account'),

(007, 'Satish', 'Kumar', 75000,'14-01-20 09.00.00', 'Account');


Select * From Worker ;

UPDATION Query :

UPDATE Worker SET FIRST_NAME = 'Badal' WHERE WORKER_ID = 001;

Select * From Worker ;

ALTER Query :

ALTER TABLE Worker

ADD Email varchar (255);

Select * From Worker ;


ALTER TABLE Worker

DROP COLUMN Email;

Select * From Worker ;

DELETION Query :

DELETE FROM Worker WHERE WORKER_ID= 001;

Select * From Worker ;


2.Write the query to implement the concept of Integrity constrains.
• SQL constraints are used to specify rules for the data in a table.
• Constraints 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 table. If there is any violation between the
constraint and the data action, the action is aborted.
• Constraints can be column level or table level. Column level constraints apply to a
column, and table level constraints apply to the whole table.

The following constraints are commonly used in SQL:

1. NOT NULL - Ensures that a column cannot have a NULL value


2. UNIQUE - Ensures that all values in a column are different
3. PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely
identifies each row in a table
4. FOREIGN KEY - Prevents actions that would destroy links between tables
5. CHECK - Ensures that the values in a column satisfies a specific condition
6. DEFAULT - Sets a default value for a column if no value is specified
7. CREATE INDEX - Used to create and retrieve data from the database very

quickly

NOT NULL:-

The NOT NULL constraint enforces a column to NOT accept NULL values.

CREATE TABLE Worker (


WORKER_ID INT NOT NULL PRIMARY KEY
AUTO_INCREMENT,
FIRST_NAME CHAR(25) NOT NULL,
LAST_NAME CHAR(25) NOT NULL,
SALARY INT(15),
JOINING_DATE DATETIME,
DEPARTMENT CHAR(25)
);
INSERT INTO Worker
(WORKER_ID, FIRST_NAME, LAST_NAME,SALARY, JOINING_DATE, DEPARTMENT)
VALUES
(001, NULL, 'Arora', 100000,'14-02-20 09.00.00', 'HR');

UNIQUE:-

• The UNIQUE constraint ensures that all values in a column are different.
• Both the UNIQUE and PRIMARY KEY constraints provide a guarantee for uniqueness
for a column or set of columns.
• A PRIMARY KEY constraint automatically has a UNIQUE constraint.
• However, you can have many UNIQUE constraints per table, but only one PRIMARY
KEY constraint per table.

CREATE TABLE Persons (


ID int NOT NULL,
FIRST_NAME varchar(255) NOT NULL,
LAST_NAME varchar(255) ,
Age int,
UNIQUE (ID)
);

INSERT INTO Persons


(ID, FIRST_NAME, LAST_NAME, Age) VALUES
(001, "Amit", 'Arora', 65),
(002, "Divya", 'Singh', 23),
(002, 'Niharika', 'Verma', 54);

PRIMARY KEY:-

• The PRIMARY KEY constraint uniquely identifies each record in a table.


• Primary keys must contain UNIQUE values, and cannot contain NULL values.
• A table can have only ONE primary key; and in the table, this primary key can consist of
single or multiple columns (fields).
CREATE TABLE Persons (
ID int NOT NULL,
FIRST_NAME varchar(255) NOT NULL,
LAST_NAME varchar(255) ,
Age int,
PRIMARY KEY (ID)
);

INSERT INTO Persons


(ID, FIRST_NAME, LAST_NAME, Age) VALUES
(1, "Sohan", 'Sen', 42),
(1, "Divya", 'Singh', 23),
(2, 'Niharika', 'Verma', 54);

FOREIGN KEY:-

• The FOREIGN KEY constraint is used to prevent actions that would destroy links
between tables.
• A FOREIGN KEY is a field (or collection of fields) in one table, that refers to the
PRIMARY KEY in another table.
• The table with the foreign key is called the child table, and the table with the primary key
is called the referenced or parent table.

CREATE TABLE Persons (


Person_ID int NOT NULL,
FIRST_NAME varchar(255) NOT NULL,
LAST_NAME varchar(255) ,
Age int,
PRIMARY KEY (Person_ID)
);

INSERT INTO Persons


(Person_ID, FIRST_NAME, LAST_NAME, Age) VALUES
(1, "Sohan", 'Sen', 42),
(2, "Divya", 'Singh', 23),
(3, 'Niharika', 'Verma', 54),
(4, 'Jayant', 'Verma', 25);

Select * From Persons ;


CREATE TABLE Orders (
Order_ID int NOT NULL,
Order_Number int NOT NULL,
Person_ID int,
PRIMARY KEY (Order_ID),
FOREIGN KEY (Person_ID) REFERENCES Persons(Person_ID)
);

INSERT INTO Orders


(Order_ID, Order_Number, Person_ID) VALUES
(1 ,77895 ,3),
(2 ,89500 ,4),
(3 ,80892 ,3),
(4 ,65859 ,2),
(5 ,54385 ,1);

Select * From Orders


CHECK:-

• The CHECK constraint is used to limit the value range that can be placed in a column.

• If you define a CHECK constraint on a column it will allow only certain values for this
column.

• If you define a CHECK constraint on a table it can limit the values in certain columns
based on values in other columns in the row.

CREATE TABLE Persons (


Person_ID int NOT NULL PRIMARY KEY,
FIRST_NAME varchar(255) NOT NULL,
LAST_NAME varchar(255) ,
Age int,
CHECK (Age>=18)
);

INSERT INTO Persons


(Person_ID, FIRST_NAME, LAST_NAME, Age) VALUES
(1, "Sohan", 'Sen', 42),
(2, "Divya", 'Singh', 23),
(3, 'Niharika', 'Verma', 18);

Select * From Persons ;

INSERT INTO Persons


(Person_ID, FIRST_NAME, LAST_NAME, Age) VALUES
(4, 'Jayant', 'Verma', 15);
DEFAULT:-

• The DEFAULT constraint is used to set a default value for a column.

• The default value will be added to all new records, if no other value is specified.

CREATE TABLE Persons (


Person_ID int NOT NULL ,
FIRST_NAME varchar(255) NOT NULL,
LAST_NAME varchar(255) ,
Age int,
City varchar(255) DEFAULT 'Delhi'
);

INSERT INTO Persons


(Person_ID, FIRST_NAME, LAST_NAME, Age,City) VALUES
(1, "Sohan", 'Sen', 42, "Lucknow"),
(2, "Divya", 'Singh', 23,"Noida"),
(3, 'Niharika', 'Verma', 18, "Basti");

Select * From Persons ;

INSERT INTO Persons


(Person_ID, FIRST_NAME, LAST_NAME, Age) VALUES
(4, 'Jayant', 'Sani', 35);

Select * From Persons ;


CREATE INDEX:-

• An index is a data structure that allows us to add indexes in the existing table.
• It enables you to improve the faster retrieval of records on a database table.
• We use it to quickly find the record without searching each row in a database table
whenever the table is accessed. We can create an index by using one or
more columns of the table for efficient access to the records.
• When a table is created with a primary key or unique key, it automatically creates a
special index named PRIMARY. We called this index as a clustered index. All indexes
other than PRIMARY indexes are known as a non-clustered index or secondary index.

CREATE TABLE Persons (


Person_ID int NOT NULL ,
FIRST_NAME varchar(255) NOT NULL,
LAST_NAME varchar(255) ,
Age int,
City varchar(255),
INDEX (Person_ID,FIRST_NAME)
);

INSERT INTO Persons


(Person_ID, FIRST_NAME, LAST_NAME, Age,City) VALUES
(1, "Sohan", 'Sen', 42, "Lucknow"),
(2, "Divya", 'Singh', 23,"Noida"),
(3, 'Niharika', 'Verma', 18, "Basti"),
(4, 'Jayant', 'Sani', 35,"Delhi");

Select * From Persons ;

SHOW INDEXES FROM Persons;


3.Write the queries to implement the Aggregate Functions:-

• SQL aggregation function is used to perform the calculations on multiple rows of a single
column of a table. It returns a single value.
• It is also used to summarize the data.

Types of SQL Aggregation Function

CREATE TABLE Worker (

WORKER_ID INT NOT NULL PRIMARY KEY

AUTO_INCREMENT,

FIRST_NAME CHAR(25) NOT NULL,

LAST_NAME CHAR(25) NOT NULL,

SALARY INT(15),

JOINING_DATE DATETIME,

DEPARTMENT CHAR(25)

);
INSERT INTO Worker

(WORKER_ID, FIRST_NAME, LAST_NAME,SALARY, JOINING_DATE, DEPARTMENT)


VALUES

(001, "Diksha", 'Arora', 100000,'14-02-20 09.00.00', 'HR'),

(002, 'Niharika', 'Verma', 80000,'14-06-11 09.00.00', 'Admin'),

(003, 'Vishal', 'Singhal', 300000,'14-02-20 09.00.00', 'HR'),

(004, 'Amitabh', 'Singh', 500000,'14-02-20 09.00.00', 'Admin'),

(005, 'Vivek', 'Bhati', 500000,'14-06-11 09.00.00', 'Admin'),

(006, 'Vipul', 'Diwan', 200000,'14-06-11 09.00.00', 'Account'),

(007, 'Satish', 'Kumar', 75000,'14-01-20 09.00.00', 'Account');

Select * From Worker ;

COUNT
• This aggregate function returns the total number of values in the specified column.
• This function can work on any type of data, i.e., numeric as well as non-numeric.
• This function does not count the NULL and DUPLICATE values. If we want to count all
the rows with NULL values, then we have to use the Count(*) function.

Select Count(WORKER_ID) from Worker ;


SUM
• This aggregate function sums all the non-NULL values of the given column.
• Like the AVG function, this function also works only on the numeric data.

AVG
• This function takes the values from the given column and then returns the average of the
values.
• This function works only on the datatypes, which are specified as numeric in the table.

MAX
• MAX function is used to find the maximum value of a certain column. This function
determines the largest value of all selected values of a column.

MIN
• MIN function is used to find the minimum value of a certain column. This function
determines the smallest value of all selected values of a column.

4.Write the queries to implement the joins.


A JOIN clause is used to combine rows from two or more tables, based on a related column
between them.
There are four types of joins :-

• INNER JOIN
• LEFT JOIN
• RIGHT JOIN
• FULL JOIN
CREATE TABLE Employee (

EmpID INT NOT NULL PRIMARY KEY,

EmpFname VARCHAR(25) NOT NULL,


EmpLname VARCHAR(25) NOT NULL,
Age int,
EmailID varchar(100),
PhoneNo VARCHAR(25),
Address VARCHAR(255)
);

INSERT INTO Employee


(EmpID, EmpFname, EmpLname, Age,EmailID,PhoneNo,Address) VALUES
(1,"Vardhan","Kumar",22 ,"[email protected]","9876543210","Delhi"),
(2,"Himani" ,"Sharma",32,"[email protected]","9977554422","Mumbai"),
(3,"Aayushi","Shreshth",24,"[email protected]","9977555121","Kolkata"),
(4,"Hemanth","Sharma",25,"[email protected]","9876545666","Bengaluru"),
(5,"Swatee" ,"Kapoor",26,"[email protected]","9544567777","Hyderabad");
Select * From Employee ;
CREATE TABLE Project (
ProjectID INT NOT NULL PRIMARY KEY,
EmpID int,
ClientID INT NOT NULL ,
ProjectName VARCHAR(25) NOT NULL
);

INSERT INTO Project


(ProjectID,EmpID,ClientID,ProjectName) VALUES
(111,1,3,"Project1"),
(222,2,1,"Project2"),
(333,3,5,"Project3"),
(444,3,2,"Project4"),
(555,5,4,"Project5"),
(666,9,1,"Project6"),
(777,7,2,"Project7"),
(888,8,3,"Project8");
Select * From Project ;
INNER JOIN:
Returns records that have matching values in both tables.

SELECT Employee.EmpID, Employee.EmpFname, Employee.EmpLname, Project.ProjectID,


Project.ProjectName
FROM Employee INNER JOIN Project ON Employee.EmpID=Project.EmpID;

LEFT JOIN:
Returns all records from the left table, and the matched records from the right table.
SELECT Employee.EmpFname, Employee.EmpLname, Project.ProjectID, Project.ProjectName
FROM Employee LEFT JOIN Project ON Employee.EmpID = Project.EmpID ;

RIGHT JOIN:
Returns all records from the right table, and the matched records from the left table.

SELECT Employee.EmpID ,Employee.EmpFname, Employee.EmpLname, Project.ProjectID,


Project.ProjectName
FROM Employee RIGHT JOIN Project ON Employee.EmpID = Project.EmpID;
FULL JOIN: Returns all records when there is a match in either left or right table.
5.Write the query to create table.
CREATE DATABASE Practice;
USE Practice;
CREATE TABLE Table1 (
ID INT NOT NULL PRIMARY KEY
AUTO_INCREMENT,
FIRST_NAME VARCHAR(25) NOT NULL,
LAST_NAME VARCHAR(25) NOT NULL,
SALARY INT,
DEPARTMENT VARCHAR(25)
);
Select * From Table1;
Experiment-4

SQL Logical Operators

S.No. Operator Description

1. ALL TRUE if all of the subquery values meet the condition

2. AND TRUE if all the conditions separated by AND is TRUE

3. ANY TRUE if any of the subquery values meet the condition

4. BETWEEN TRUE if the operand is within the range of comparisons

5. EXISTS TRUE if the subquery returns one or more records

6. IN TRUE if the operand is equal to one of a list of expressions

7. LIKE TRUE if the operand matches a pattern

8. NOT Displays a record if the condition(s) is NOT TRUE

9. OR TRUE if any of the conditions separated by OR is TRUE

10. SOME TRUE if any of the subquery values meet the condition

CREATE DATABASE ORG;


USE ORG;
CREATE TABLE Employee (
WORKER_ID INT NOT NULL PRIMARY KEY
AUTO_INCREMENT,
FIRST_NAME VARCHAR(25) NOT NULL,
LAST_NAME VARCHAR(25) NOT NULL,
SALARY INT,
DEPARTMENT VARCHAR(25),
PHONE_No VARCHAR(25)
);
INSERT INTO Employee
(WORKER_ID, FIRST_NAME, LAST_NAME,SALARY, DEPARTMENT,PHONE_No)
VALUES
(001, "Diksha", 'Arora', 100000, 'HR',NULL),
(002, 'Divya', 'Gaur', 80000, 'Admin',NULL),
(003, 'Vishal', 'Singhal', 300000, 'HR',"2345637810"),
(004, 'Amitabh', 'Singh', 500000, 'Admin',"8764539201"),
(005, 'Vivek', 'Bhati', 500000,'Admin',NULL),
(006, 'Vipul', 'Diwan', 200000,'Account',"4352678913"),
(007, 'Satish', 'Kumar', 75000,'Account',"5412327908");

AND
The AND operator allows you to construct multiple conditions in the WHERE clause of an SQL
statement such as SELECT, UPDATE, and DELETE.

SELECT FIRST_NAME, LAST_NAME, SALARY


FROM Worker WHERE SALARY >= 7000 AND DEPARTMENT = "HR"
ORDER BY salary;

OR
The OR operator returns true if a least one expression evaluates to true.
SELECT FIRST_NAME,LAST_NAME, SALARY
FROM Worker WHERE DEPARTMENT = "HR" OR DEPARTMENT = 'Admin'
ORDER BY SALARY;

IS NULL
The IS NULL operator compares a value with a null value and returns true if the compared value
is null; otherwise, it returns false.
SELECT FIRST_NAME,LAST_NAME,PHONE_No
FROM Employee WHERE PHONE_No IS NULL ORDER BY WORKER_ID;

BETWEEN
The BETWEEN operator searches for values that are within a set of values, given the minimum
value and maximum value. Note that the minimum and maximum values are included as part of
the conditional set.
SELECT WORKER_ID,FIRST_NAME,LAST_NAME,SALARY
FROM Employee WHERE SALARY BETWEEN 74000 AND 300000
ORDER BY SALARY;
IN
The IN operator compares a value to a list of specified values. The IN operator returns true if the
compared value matches at least one value in the list; otherwise, it returns false.
SELECT WORKER_ID,FIRST_NAME,LAST_NAME,SALARY
FROM Employee WHERE SALARY IN (80000,200000,300000, 500000)
ORDER BY SALARY;

LIKE
The LIKE operator compares a value to similar values using a wildcard operator. SQL provides
two wildcards used in conjunction with the LIKE operator:

• The percent sign ( %) represents zero, one, or multiple characters.


• The underscore sign ( _) represents a single character.
SELECT WORKER_ID,FIRST_NAME,LAST_NAME
FROM Employee WHERE FIRST_NAME LIKE '_i%'
ORDER BY FIRST_NAME;

ALL
The ALL operator compares a value to all values in another value set. The ALL operator must be
preceded by a comparison operator and followed by a subquery.
SELECT WORKER_ID,FIRST_NAME,LAST_NAME,SALARY
FROM Employee WHERE SALARY <=ALL (SELECT SALARY FROM Employee WHERE
PHONE_No IS NULL)
ORDER BY SALARY DESC;

ANY
• The ANY operator compares a value to any value in a set according to the condition as
shown below:
• Similar to the ALL operator, the ANY operator must be preceded by a comparison
operator and followed by a subquery.
SELECT WORKER_ID,FIRST_NAME,LAST_NAME,SALARY
FROM Employee WHERE SALARY >ANY (SELECT AVG(SALARY) FROM Employee )
ORDER BY SALARY DESC;

SOME
SOME is an alias for ANY, therefore, you can use them interchangeably.
Experiment-5

Creating Orderby , Groupby functions


Orderby:-
CREATE TABLE Employee_d(
EmpID INT NOT NULL PRIMARY KEY,
EmpFname VARCHAR(25) NOT NULL,
EmpLname VARCHAR(25) NOT NULL,
Age int,
EmailID varchar(100),
PhoneNo VARCHAR(25),
Address VARCHAR(255)
);
INSERT INTO Employee_d
(EmpID, EmpFname, EmpLname, Age,EmailID,PhoneNo,Address) VALUES
(1,"Vardhan","Kumar",22,"[email protected]","9876543210","Delhi"),
(2,"Himani","Sharma",32,"[email protected]","9977554422","Mumbai"),
(3,"Aayushi","Shreshth",24,"[email protected]","9977555121","Kolkata"),
(4,"Hemanth","Sharma",25,"[email protected]","9876545666","Bengaluru"),
(5,"Swatee","Kapoor",26,"[email protected]","9544567777","Hyderabad");

Select * from Employee_d


ORDER BY Age;
GROUP BY:-

Create Table Customers (

Customer_id int,

First_name varchar(100),

Last_name varchar(100),

Age int,

Country varchar(100)

);

INSERT INTO Customers

(Customer_id, First_name, Last_name, Age,Country ) VALUES

(1,"John","Doe",31,"USA"),

(2,"Robert","Luna",22,"USA"),

(3,"David","Robinson",22,"UK"),

(4,"John","Reinhardt",25,"UK"),

(5,"Betty","Doe",28,"UAE");

Select * from Customers;


SELECT country, COUNT(*) AS number

FROM Customers

GROUP BY country;
Experiment-6

Write query to apply Insert, Select, Distinct Clause, Where Clause on


database Tables.
CREATE DATABASE ORG;
USE ORG;
CREATE TABLE Employee (
WORKER_ID INT NOT NULL PRIMARY KEY
AUTO_INCREMENT,
FIRST_NAME VARCHAR(25) NOT NULL,
LAST_NAME VARCHAR(25) NOT NULL,
SALARY INT,
DEPARTMENT VARCHAR(25),
PHONE_No VARCHAR(25)
);

INSERT:-
INSERT INTO Employee
(WORKER_ID, FIRST_NAME, LAST_NAME,SALARY, DEPARTMENT,PHONE_No)
VALUES
(001, "Diksha", 'Arora', 100000, 'HR',NULL),
(002, 'Divya', 'Gaur', 80000, 'Admin',NULL);
SELECT * FROM Employee;

SELECT:-
SELECT WORKER_ID,FIRST_NAME,LAST_NAME,SALARY FROM Employee;
Where Clause:-
SELECT WORKER_ID,FIRST_NAME,LAST_NAME
FROM Employee WHERE FIRST_NAME LIKE '_i%'
ORDER BY FIRST_NAME;

Distinct Clause :-

• To select a distinct value from column value you can use distinct.

SELECT Distinct SALARY FROM Employee;


Experiment-7
Write query to apply table Creation with select, Insert data using select,
Renaming on database Tables.
Table Creation with select:-
CREATE TABLE Persons_d (
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);
Select * from Persons_d ;

CREATE TABLE Employee_d AS


SELECT PersonID,LastName,FirstName
FROM Persons_d;
Select * from Employee_d;

Insert data using select:-


CREATE TABLE Employee_d(
EmpID INT NOT NULL PRIMARY KEY,
EmpFname VARCHAR(25) NOT NULL,
EmpLname VARCHAR(25) NOT NULL,
Age int,
EmailID varchar(100),
PhoneNo VARCHAR(25),
Address VARCHAR(255)
);
INSERT INTO Employee_d
(EmpID, EmpFname, EmpLname, Age,EmailID,PhoneNo,Address) VALUES
(1,"Vardhan","Kumar",22 ,"[email protected]","9876543210","Delhi"),
(2,"Himani" ,"Sharma",32,"[email protected]","9977554422","Mumbai"),
(3,"Aayushi","Shreshth",24,"[email protected]","9977555121","Kolkata"),
(4,"Hemanth","Sharma",25,"[email protected]","9876545666","Bengaluru"),
(5,"Swatee" ,"Kapoor",26,"[email protected]","9544567777","Hyderabad");
Select * from Employee_d;

CREATE TABLE Persons_d AS


SELECT EmpID,EmpFname,EmpLname,Age
FROM Employee_d;

INSERT INTO Persons_d (EmpID,EmpFname,EmpLname,Age)


SELECT EmpID,EmpFname,EmpLname,Age
FROM Employee_d;
Select * from Persons_d ;
Renaming on database Tables:-
RENAME TABLE Persons_d TO New_Persons_d;
Select * from New_Persons_d;
Experiment-8
CREATE DATABASE ORG;
SHOW DATABASES;
USE ORG;
CREATE TABLE Worker (
WORKER_ID INT NOT NULL PRIMARY KEY
AUTO_INCREMENT,
FIRST_NAME CHAR(25),
LAST_NAME CHAR(25),
SALARY INT,
JOINING_DATE DATETIME,
DEPARTMENT CHAR(25)
);
INSERT INTO Worker
(WORKER_ID, FIRST_NAME, LAST_NAME,
SALARY, JOINING_DATE, DEPARTMENT) VALUES
(001, 'Monika', 'Arora', 100000,'14-02-20 09.00.00', 'HR'),
(002, 'Niharika', 'Verma', 80000,'14-06-11 09.00.00', 'Admin'),
(003, 'Vishal', 'Singhal', 300000,'14-02-20 09.00.00', 'HR'),
(004, 'Amitabh', 'Singh', 500000,'14-02-20 09.00.00', 'Admin'),
(005, 'Vivek', 'Bhati', 500000,'14-06-11 09.00.00', 'Admin'),
(006, 'Vipul', 'Diwan', 200000,'14-06-11 09.00.00', 'Account'),
(007, 'Satish', 'Kumar', 75000,'14-01-20 09.00.00', 'Account'),
(008, 'Geetika', 'Chauhan', 90000,'14-04-11 09.00.00', 'Admin');
SELECT * From Worker;
CREATE TABLE Bonus (

WORKER_REF_ID INT,

BONUS_AMOUNT INT(10),

BONUS_DATE DATETIME,

FOREIGN KEY (WORKER_REF_ID)

REFERENCES Worker(WORKER_ID)

ON DELETE CASCADE

);

CREATE TABLE Title (

WORKER_REF_ID INT,

WORKER_TITLE CHAR(25),

AFFECTED_FROM DATETIME,

FOREIGN KEY (WORKER_REF_ID)

REFERENCES Worker(WORKER_ID)

ON DELETE CASCADE

);

INSERT INTO Title

(WORKER_REF_ID, WORKER_TITLE,AFFECTED_FROM) VALUES

(001, 'Manager', '2016-02-20 00:00:00'),


(002, 'Executive', '2016-06-11 00:00:00'),

(008, 'Executive', '2016-06-11 00:00:00'),

(005, 'Manager', '2016-06-11 00:00:00'),

(004, 'Asst. Manager', '2016-06-11 00:00:00'),

(007, 'Executive', '2016-06-11 00:00:00'),

(006, 'Lead', '2016-06-11 00:00:00'),

(003, 'Lead', '2016-06-11 00:00:00');

SELECT * From Title ;

Q-1. Write an SQL query to fetch “FIRST_NAME” from Worker table using the alias
name as <WORKER_NAME>.
Select FIRST_NAME AS WORKER_NAME from Worker;

Q-2. Write an SQL query to fetch “FIRST_NAME” from Worker table in upper case.
Select upper(FIRST_NAME) from Worker;
Q-3. Write an SQL query to fetch unique values of DEPARTMENT from Worker table.
Select distinct DEPARTMENT from Worker;

Q-4. Write an SQL query to print the first three characters of FIRST_NAME from
Worker table.
Select substring (FIRST_NAME,1,3) from Worker;

Q-5. Write an SQL query to find the position of the alphabet (‘a’) in the first name column
‘Amitabh’ from Worker table.
Select INSTR(FIRST_NAME, BINARY'a') from Worker where FIRST_NAME = 'Amitabh';
Q-6. Write an SQL query to print the FIRST_NAME from Worker table after removing
white spaces from the right side.
Select RTRIM(FIRST_NAME) from Worker;

Q-7. Write an SQL query to print the DEPARTMENT from Worker table after removing
white spaces from the left side.
Select LTRIM(DEPARTMENT) from Worker;

Q-8. Write an SQL query that fetches the unique values of DEPARTMENT from Worker
table and prints its length.
Select distinct length(DEPARTMENT) from Worker;

Q-9. Write an SQL query to print the FIRST_NAME from Worker table after replacing
‘a’ with ‘A’.
Select REPLACE(FIRST_NAME,'a','A') from Worker;
Q-10. Write an SQL query to print the FIRST_NAME and LAST_NAME from Worker
table into a single column COMPLETE_NAME. A space char should separate them.
Select CONCAT(FIRST_NAME, ' ', LAST_NAME) AS 'COMPLETE_NAME' from Worker;

Q-11. Write an SQL query to print all Worker details from the Worker table order by
FIRST_NAME Ascending.
Select * from Worker order by FIRST_NAME asc;

Q-12. Write an SQL query to print all Worker details from the Worker table order by
FIRST_NAME Ascending and DEPARTMENT Descending.
Select * from Worker order by FIRST_NAME asc,DEPARTMENT desc;

Q-13. Write an SQL query to print details for Workers with the first name as “Vipul” and
“Satish” from Worker table.
Select * from Worker where FIRST_NAME in ('Vipul','Satish');

Q-14. Write an SQL query to print details of workers excluding first names, “Vipul” and
“Satish” from Worker table.
Select * from Worker where FIRST_NAME not in ('Vipul','Satish');

Q-15. Write an SQL query to print details of Workers with DEPARTMENT name as
“Admin”.
Select * from Worker where DEPARTMENT like 'Admin%';
Q-16. Write an SQL query to print details of the Workers whose FIRST_NAME contains
‘a’.
Select * from Worker where FIRST_NAME like '%a%';

Q-17. Write an SQL query to print details of the Workers whose FIRST_NAME ends with
‘a’.
Select * from Worker where FIRST_NAME like '%a';

Q-18. Write an SQL query to print details of the Workers whose FIRST_NAME ends with
‘h’ and contains six alphabets.
Select * from Worker where FIRST_NAME like '_____h';

Q-19. Write an SQL query to print details of the Workers whose SALARY lies between
100000 and 500000.
Select * from Worker where SALARY between 100000 and 500000;
Q-20. Write an SQL query to print details of the Workers who have joined in Feb’2014.
Select * from Worker where year(JOINING_DATE) = 2014 and month(JOINING_DATE) = 2;

Q-21. Write an SQL query to fetch the count of employees working in the department
‘Admin’.
SELECT COUNT(*) FROM worker WHERE DEPARTMENT = 'Admin';

Q-22. Write an SQL query to fetch worker names with salaries >= 50000 and <= 100000.
SELECT CONCAT(FIRST_NAME, ' ', LAST_NAME) As
Worker_Name, Salary
FROM worker
WHERE WORKER_ID IN
(SELECT WORKER_ID FROM worker
WHERE Salary BETWEEN 50000 AND 100000);
Q-23. Write an SQL query to fetch the no. of workers for each department in the
descending order.
SELECT DEPARTMENT, count(WORKER_ID)
No_Of_Workers
FROM worker
GROUP BY DEPARTMENT
ORDER BY No_Of_Workers DESC;

Q-24. Write an SQL query to print details of the Workers who are also Managers.
SELECT DISTINCT W.FIRST_NAME, T.WORKER_TITLE
FROM Worker W
INNER JOIN Title T
ON W.WORKER_ID = T.WORKER_REF_ID
AND T.WORKER_TITLE in ('Manager');

Q-25. Write an SQL query to fetch duplicate records having matching data in some fields
of a table.
SELECT WORKER_TITLE, AFFECTED_FROM, COUNT(*)
FROM Title
GROUP BY WORKER_TITLE, AFFECTED_FROM
HAVING COUNT(*) > 1;
Q-26. Write an SQL query to show only odd rows from a table.
SELECT * FROM Worker WHERE MOD (WORKER_ID, 2) <> 0;

Q-27. Write an SQL query to show only even rows from a table.
SELECT * FROM Worker WHERE MOD (WORKER_ID, 2) = 0;

Q-28. Write an SQL query to clone a new table from another table.
CREATE TABLE WorkerClone LIKE Worker;
INSERT INTO WorkerClone
SELECT * FROM Worker;

Q-29. Write an SQL query to fetch intersecting records of two tables.


Q-30. Write an SQL query to show records from one table that another table does not
have.
Q-31. Write an SQL query to show the current date and time.
SELECT NOW();

Q-32. Write an SQL query to show the top n (say 5) records of a table.
SELECT * FROM Worker ORDER BY Salary DESC
LIMIT 5;
Q-33. Write an SQL query to determine the nth (say n=5) highest salary from a table.
SELECT Salary FROM Worker ORDER BY Salary DESC
LIMIT 4,1;

Q-34. Write an SQL query to determine the 5th highest salary without using TOP or limit
method.
SELECT Salary
FROM Worker W1
WHERE 4 = (
SELECT COUNT( DISTINCT ( W2.Salary ) )
FROM Worker W2
WHERE W2.Salary >= W1.Salary
);

Q-35. Write an SQL query to fetch the list of employees with the same salary.
Select distinct W.WORKER_ID, W.FIRST_NAME,
W.Salary
from Worker W, Worker W1
where W.Salary = W1.Salary
and W.WORKER_ID != W1.WORKER_ID;
Q-36. Write an SQL query to show the second highest salary from a table.
Select max(Salary) from Worker
where Salary not in (Select max(Salary) from
Worker);

Q-37. Write an SQL query to show one row twice in results from a table.
select FIRST_NAME, DEPARTMENT from worker W
where W.DEPARTMENT='HR'
union all
select FIRST_NAME, DEPARTMENT from Worker W1
where W1.DEPARTMENT='HR';

Q-38. Write an SQL query to fetch intersecting records of two tables.


Q-39. Write an SQL query to fetch the first 50% records from a table.
SELECT *
FROM WORKER
WHERE WORKER_ID <= (SELECT count(WORKER_ID)/2
from Worker);
Q-40. Write an SQL query to fetch the departments that have less than five people in it.
SELECT DEPARTMENT, COUNT(WORKER_ID) as 'Number of Workers'
FROM Worker GROUP BY DEPARTMENT
HAVING COUNT(WORKER_ID) < 5;

Q-41. Write an SQL query to show all departments along with the number of people in
there.
SELECT DEPARTMENT, COUNT(DEPARTMENT) as
'Number of Workers' FROM Worker GROUP BY
DEPARTMENT;

Q-42. Write an SQL query to show the last record from a table.
Select * from Worker where WORKER_ID = (SELECT
max(WORKER_ID) from Worker);
Q-43. Write an SQL query to fetch the first row of a table.
Select * from Worker where WORKER_ID = (SELECT
min(WORKER_ID) from Worker);

Q-44. Write an SQL query to fetch the last five records from a table.
SELECT * FROM Worker WHERE WORKER_ID <=5
UNION
SELECT * FROM (SELECT * FROM Worker W order by
W.WORKER_ID DESC) AS W1 WHERE W1.WORKER_ID
<=5;

Q-45. Write an SQL query to print the name of employees having the highest salary in each
department.
SELECT t.DEPARTMENT,t.FIRST_NAME,t.Salary
from(SELECT max(Salary) as
TotalSalary,DEPARTMENT from Worker group by
DEPARTMENT) as TempNew
Inner Join Worker t on
TempNew.DEPARTMENT=t.DEPARTMENT
and TempNew.TotalSalary=t.Salary;
Q-46. Write an SQL query to fetch three max salaries from a table.
SELECT distinct Salary from worker a WHERE 3
>= (SELECT count(distinct Salary) from worker
b WHERE a.Salary <= b.Salary) order by
a.Salary desc;

Q-47. Write an SQL query to fetch three min salaries from a table.
SELECT distinct Salary from worker a WHERE 3
>= (SELECT count(distinct Salary) from worker
b WHERE a.Salary >= b.Salary) order by
a.Salary desc;

Q-48. Write an SQL query to fetch nth(say 5) max salaries from a table.
SELECT distinct Salary from worker a WHERE 5
>= (SELECT count(distinct Salary) from worker
b WHERE a.Salary <= b.Salary) order by
a.Salary desc;

Q-49. Write an SQL query to fetch departments along with the total salaries paid for each
of them.
SELECT DEPARTMENT, sum(Salary) from worker
group by DEPARTMENT;

Q-50. Write an SQL query to fetch the names of workers who earn the highest salary.
SELECT FIRST_NAME, SALARY from Worker WHERE
SALARY=(SELECT max(SALARY) from Worker);

You might also like