DBMS Practicle File Ex8
DBMS Practicle File Ex8
Installing MYSQL:-
Installation steps for MySql:
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.
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.
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.
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
USE ORG;
AUTO_INCREMENT,
FIRST_NAME CHAR(25),
LAST_NAME CHAR(25),
SALARY INT(15),
JOINING_DATE DATETIME,
DEPARTMENT CHAR(25)
);
INSERTION Query-
UPDATION Query :
ALTER Query :
DELETION Query :
quickly
NOT NULL:-
The NOT NULL constraint enforces a column to NOT accept NULL values.
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.
PRIMARY KEY:-
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.
• 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.
• The default value will be added to all new records, if no other value is specified.
• 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.
• 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.
AUTO_INCREMENT,
SALARY INT(15),
JOINING_DATE DATETIME,
DEPARTMENT CHAR(25)
);
INSERT INTO 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.
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.
• INNER JOIN
• LEFT JOIN
• RIGHT JOIN
• FULL JOIN
CREATE TABLE Employee (
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.
10. SOME TRUE if any of the subquery values meet the condition
AND
The AND operator allows you to construct multiple conditions in the WHERE clause of an SQL
statement such as SELECT, UPDATE, and DELETE.
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:
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
Customer_id int,
First_name varchar(100),
Last_name varchar(100),
Age int,
Country varchar(100)
);
(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");
FROM Customers
GROUP BY country;
Experiment-6
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.
WORKER_REF_ID INT,
BONUS_AMOUNT INT(10),
BONUS_DATE DATETIME,
REFERENCES Worker(WORKER_ID)
ON DELETE CASCADE
);
WORKER_REF_ID INT,
WORKER_TITLE CHAR(25),
AFFECTED_FROM DATETIME,
REFERENCES Worker(WORKER_ID)
ON DELETE CASCADE
);
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-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-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);