0% found this document useful (0 votes)
44 views60 pages

SH Ut Os H: Youtube

Uploaded by

Prasanta Agasti
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views60 pages

SH Ut Os H: Youtube

Uploaded by

Prasanta Agasti
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 60

sh

👉
YouTube
https://youtube.com/@codewithashutosh247?si=rXike59WnLhUEUkL

to
hu
👉
Whatsapp Group -
https://chat.whatsapp.com/Iy2Ag6hE35WENehlmNcctV
As
👉
Telegram Group -
ith

https://t.me/+3jqmwqzNp3xlMTZl

👉
Git & GitHub -
W

https://github.com/AshutoshG1?tab=repositories
e
od
C
MySQL

Q. What is a Database ?
● A database is a structured collection of data stored electronically,

sh
often managed by a Database Management System (DBMS).
● It allows for efficient data retrieval, manipulation, and management.

to
Q. What is Data ?

hu
● Data refers to raw facts and figures that are collected and stored,
which can be processed to generate meaningful information.
As
● It can be in various forms, such as numbers, text, or multimedia.
ith

Q. What is DBMS ?
● A Database Management System (DBMS) is software that facilitates
W

the creation, manipulation, and management of databases.


● It provides tools for data storage, retrieval, and security, ensuring
efficient and organized access to data.
e
od

Q. What is RDBMS ?
● A Relational Database Management System (RDBMS) is a type of
DBMS that organizes data into tables with rows and columns,
C

allowing relationships between tables.


● It uses Structured Query Language (SQL) for querying and managing
data.

Q. What are the constraints in mysql ?


● Constraints in MySQL are rules applied to columns in a table to
enforce data integrity and consistency.
● Common constraints include PRIMARY KEY, FOREIGN KEY,
UNIQUE, NOT NULL, and CHECK.

Q. What is Foreign key ?


● A foreign key is a field or collection of fields in one table that refers to
the primary key in another table.

sh
● It can be null or duplicate.

Q. What is the Primary key ?

to
● The primary key constraint uniquely identifies each record in a table.
● It should be unique and not null.

hu
Q. What is the candidate key? As
● A candidate key is a minimal set of columns that can uniquely identify
a record in a table.
● There can be multiple candidate keys, but only one is chosen as the
ith

primary key.

Q. What is a unique key?


W

● A unique key is a constraint that ensures all values in a column or a


set of columns are unique across the table, preventing duplicate
entries.
e
od

Q. What is a composite key ?


● A composite key is a combination of two or more columns in a table
that together uniquely identify a record, used when a single column is
C

insufficient for uniqueness.

Q. What is join and types of join ?


● A join clause is used to combine rows from two or more tables based
on a related column between them.
○ Inner join - The inner join keywords selects records that have
matching values in both tables.
○ Left join - Left join returns all the records from the left table and
the matching records from the right table.
○ Right join - Right join returns all the records from the right table
and the matching record from the left table.
○ Cross join - cross join returns all the records from the both
tables.
○ Self join - A table is joined with itself.

sh
to
👉 https://chat.whatsapp.com/Iy2Ag6hE35WENehlmNcctV

hu
As
Q. SQL vs MySQL vs NoSQL ?
ith

SQL MySQL NoSQL


W

Stands for Structured A popular Refers to


Query Language open-source non-relational
e

used for querying relational database databases designed


relational databases. management system for unstructured or
od

(RDBMS). semi-structured data.


Used with databases Uses SQL for Includes databases
C

like MySQL, querying and like MongoDB,


PostgreSQL, and managing data. Cassandra, and
Oracle. Redis, supporting
flexible schemas and
scalability.
Q. What is Normalization ?
● Normalization is the process of organizing data in a database to
reduce redundancy and improve data integrity.
● Types-
○ First Normal Form (1NF): Ensures each column contains
atomic, indivisible values and each record is unique.

sh
○ Second Normal Form (2NF): Achieved when the table is in
1NF and all non-key attributes are fully functionally dependent
on the entire primary key.

to
○ Third Normal Form (3NF): Achieved when the table is in 2NF
and all attributes are only dependent on the primary key, not on

hu
other non-key attributes.
○ Boyce-Codd Normal Form (BCNF): A stronger version of 3NF
where every determinant is a candidate key.
As
○ Fourth Normal Form (4NF): Eliminates multivalued
dependencies by ensuring that no table contains two or more
independent multi-valued facts about an entity.
ith

Q. Relationship in sql and its types ?


W

Relationships in SQL describe how tables are related to each other in a


database.
e

Types of Relationships:
od

1. One-to-One (1:1): Each record in Table A corresponds to one record


in Table B.
Example: A person has only one passport; each passport is
C

assigned to only one person.

2. One-to-Many (1:M): A department can have many employees, but


each employee belongs to only one department.
Example: A company department like "Marketing" can have many
employees, but each employee works in only one department.

3. Many-to-Many (M:M): Records in Table A can relate to multiple


records in Table B and vice versa.
Example: Students can enroll in multiple courses, and each course
can have multiple students. This typically requires a junction table to
manage the relationships.

sh
to
Q. What is Commit ?
● To permanently save all the changes made during the current

hu
transaction to the database.

Q. What is rollback ?
As
● It is used to undo all changes made during the current transaction .

Q. What is Having clause ?


ith

● The having clause was added to SQL because the where keyword
cannot be used with aggregate functions.
W

Q. What is GroupBy ?
● It is used to group the rows that have the same values in specified
e

column.
od

Q. What is Order By ?
● It is used to sort the result set in ascending or descending order
C

● For ascending we use ASC and for descending we use DESC.

Q. What are ACID properties ?


ACID properties ensure reliable database transactions:
● Atomicity: Transactions are all-or-nothing.
● Consistency: Transactions maintain database integrity.
● Isolation: Transactions do not interfere with each other.
● Durability: Committed transactions are permanent and survive
failures.

Q. What is DDL, DML, DQL, DCL, and TCL ?

sh
● DDL (Data Definition Language): Defines and manages database
structure (e.g., CREATE, ALTER, DROP).

to
● DML (Data Manipulation Language): Handles data manipulation
(e.g., SELECT, INSERT, UPDATE, DELETE).

hu
● DQL (Data Query Language): Queries data from the database (e.g.,
SELECT).
● DCL (Data Control Language): Manages access permissions (e.g.,
As
GRANT, REVOKE).
● TCL (Transaction Control Language): Manages transactions (e.g.,
COMMIT, ROLLBACK, SAVEPOINT).
ith
W

Q. What is Indexing ?
● In mysql , indexing improves the speed of the data retrieval
e

operations on a database table.


od

● Indexing can be applied on attribute or column in a database table


● Internally it uses a B tree to sort the data.
● It works similarly to an index in a book.
C

Q. What is Stored Procedure in MySQL ?


● Stored procedure is a reusable sql code block that is stored on the
database server and can be executed as per the requirement.
● These are precompiled sql statements encapsulated into single unit
that executes faster.
Q. What are the triggers in MySQL ?
● In mysql , triggers are database objects that are automatically
executed in response to specific events on a table.
● Triggers are activated before or after by insert , update or delete
statements.
● Triggers are always associated with a specific table.

sh
to
hu
As
Query Set - 1
ith
W
e
od
C
C
od
e
W
ith
As
hu
to
sh
Q1. Write a query to fetch the EmpFname from the EmployeeInfo table in
upper case and use the ALIAS name as EmpName.

SELECT UPPER(EmpFname) AS EmpName FROM EmployeeInfo;

Q2. Write a query to fetch the number of employees working in the


department ‘HR’.

sh
SELECT COUNT(*) FROM EmployeeInfo WHERE Department = 'HR';

to
Q3. Write a query to get the current date and time .

hu
SELECT NOW();
As
Write a query to get the current date

SELECT CURDATE();
ith

Q4. Write a query to retrieve the first four characters of EmpLname from
W

the EmployeeInfo table.

SELECT SUBSTRING(EmpLname, 1, 4) FROM EmployeeInfo;


e

Q5. Write a query to fetch only the place name(string before brackets) from
od

the Address column of the EmployeeInfo table.


C

SELECT SUBSTRING(Address, 1, LOCATE('(', Address) - 1)


FROM EmployeeInfo;
Q6. Write a query to create a new table which consists of data and
structure copied from the other table.

CREATE TABLE NewTable AS SELECT * FROM EmployeeInfo;

Q7. Write a query to find all the employees whose salary is between 50000
to 100000.

sh
SELECT * FROM EmployeePosition WHERE Salary BETWEEN '50000'
AND '100000';

to
Q8. Write a query to find the names of employees that begin with ‘S’

hu
SELECT * FROM EmployeeInfo WHERE EmpFname LIKE 'S%';
As
Q9. Write a query to fetch top N records.

SELECT *
FROM employeeposition
ith

ORDER BY Salary DESC


LIMIT 3;
W

Q10. Write a query to retrieve the EmpFname and EmpLname in a single


e

column as “FullName”. The first name and the last name must be
separated with space.
od
C

SELECT CONCAT(EmpFname, ' ', EmpLname) AS 'FullName' FROM


EmployeeInfo;

Q11. Write a query find number of employees whose DOB is between


02/05/1970 to 31/12/1975 and are grouped according to gender
SELECT COUNT(*), Gender FROM EmployeeInfo WHERE DOB
BETWEEN '02/05/1970 ' AND '31/12/1975' GROUP BY Gender;

Q12. Write a query to fetch all the records from the EmployeeInfo table
ordered by EmpLname in descending order and Department in the
ascending order.

sh
SELECT * FROM EmployeeInfo ORDER BY EmpFname desc, Department
asc;

to
Q13. Write a query to fetch details of employees whose EmpLname ends

hu
with an alphabet ‘A’ and contains five alphabets.

As
SELECT * FROM EmployeeInfo WHERE EmpLname LIKE '____a';

Q14. Write a query to fetch details of all employees excluding the


employees with first names, “Sanjay” and “Sonia” from the EmployeeInfo
ith

table.
W

SELECT * FROM EmployeeInfo WHERE EmpFname NOT IN


('Sanjay','Sonia');
e

Q15. Write a query to fetch details of employees with the address as


“DELHI(DEL)”.
od

SELECT * FROM EmployeeInfo WHERE Address LIKE 'DELHI(DEL)%';


C

Q16. Write a query to fetch all employees who also hold the managerial
position.

SELECT E.EmpFname, E.EmpLname, P.EmpPosition


FROM EmployeeInfo E INNER JOIN EmployeePosition P ON
E.EmpID = P.EmpID AND P.EmpPosition IN ('Manager');

Q17. Write a query to fetch the department-wise count of employees sorted


by department’s count in ascending order.

SELECT Department, count(EmpID) AS EmpDeptCount


FROM EmployeeInfo GROUP BY Department

sh
ORDER BY EmpDeptCount ASC;

to
Q18. Write a query to calculate the even and odd records from a table.
To retrieve the even records from a table, you have to use the MOD()

hu
function as follows:

As
Q19. Write a SQL query to retrieve employee details from EmployeeInfo
table who have a date of joining in the EmployeePosition table.
ith

SELECT * FROM EmployeeInfo E


W

WHERE EXISTS
(SELECT * FROM EmployeePosition P WHERE E.EmpId = P.EmpId);
e

Q20. Write a query to retrieve two minimum and maximum salaries from
the EmployeePosition table.
od

To retrieve two minimum salaries, you can write a query as below:


C

SELECT DISTINCT Salary


FROM EmployeePosition E1
WHERE 2 >= (
SELECT COUNT(DISTINCT Salary)
FROM EmployeePosition E2
WHERE E1.Salary >= E2.Salary
)
ORDER BY E1.Salary DESC;

To retrieve two maximum salaries, you can write a query as below:

sh
to
SELECT DISTINCT Salary
FROM EmployeePosition E1

hu
WHERE 2 >= (
SELECT COUNT(DISTINCT Salary)
FROM EmployeePosition E2 As
WHERE E1.Salary <= E2.Salary
)
ORDER BY E1.Salary DESC;
ith

Q21. Write a query to find the Nth highest salary from the table without
W

using TOP/limit keyword.


e

SELECT Salary
FROM EmployeePosition E1
od

WHERE N-1 = (
SELECT COUNT( DISTINCT ( E2.Salary ) )
C

FROM EmployeePosition E2
WHERE E2.Salary > E1.Salary );

Q22. Write a query to retrieve duplicate records from a table.

SELECT EmpID, EmpFname, Department, COUNT(*) AS Count


FROM EmployeeInfo
GROUP BY EmpID, EmpFname, Department
HAVING COUNT(*) > 1;

Q23. Write a query to retrieve the list of employees working in the same
department.

sh
SELECT DISTINCT E.EmpID, E.EmpFname, E.Department

to
FROM EmployeeInfo E
JOIN EmployeeInfo E1 ON E.Department = E1.Department

hu
WHERE E.EmpID != E1.EmpID;

As
Q24. Write a query to retrieve the last 3 records from the EmployeeInfo
table.
ith

SELECT * FROM EmployeeInfo WHERE


EmpID <=3 UNION SELECT * FROM
W

(SELECT * FROM EmployeeInfo E ORDER BY E.EmpID DESC)


AS E1 WHERE E1.EmpID <=3;
e

Q25. Write a query to find the third-highest salary from the EmpPosition
table.
od
C

Q26. Write a query to display the first and the last record from the
EmployeeInfo table.

To display the first record from the EmployeeInfo table, you can write a
query as follows:
SELECT * FROM EmployeeInfo WHERE EmpID = (SELECT MIN(EmpID)
FROM EmployeeInfo);

To display the last record from the EmployeeInfo table, you can write a
query as follows:

sh
SELECT * FROM EmployeeInfo WHERE EmpID = (SELECT MAX(EmpID)
FROM EmployeeInfo);

to
Q27. Write a query to add email validation to your database

hu
As
Q28. Write a query to retrieve Departments who have less than 2
employees working in it.

SELECT DEPARTMENT, COUNT(EmpID) AS 'EmpNo'


ith

FROM EmployeeInfo
GROUP BY DEPARTMENT
W

HAVING COUNT(EmpID) < 2;


e

Q29. Write a query to retrieve EmpPostion along with total salaries paid for
each of them.
od

SELECT EmpPosition, SUM(Salary) from EmployeePosition GROUP BY


C

EmpPosition;

Q30. Write a query to fetch 50% records from the EmployeeInfo table.

SELECT * FROM EmployeeInfo WHERE EmpID <= (SELECT


COUNT(EmpID)/2 from EmployeeInfo);
Q31. How do you read the last five records from a database using a SQL
query?

SELECT *
FROM employeeinfo
ORDER BY EmpID DESC

sh
LIMIT 5;

to
hu
Q32. Write a SQL query that will provide you with the 10th-highest
employee salary from an Employee table.
As
SELECT salary
FROM (
ith

SELECT salary, ROW_NUMBER() OVER (ORDER BY salary DESC) AS


row_num
W

FROM employeeposition
) AS ranked_salary
WHERE row_num = 10;
e
od
C

Q33. Write a query to get the last record from a table.

SELECT * FROM employeeinfo


ORDER BY EmpID DESC LIMIT 1;
Query Set - 2

sh
SQL Query Interview Questions and Answers

to
We have created three sample tables: Student Table, Program Table,
and Scholarship Table. We will be using these tables to perform various

hu
query operations.

Student Table
As
ith

STUDENT_ID FIRST_NAME LAST_NAME GPA ENROLLMENT_DATE MAJOR


W

Computer
201 Shivansh Mahajan 8.79 2021-09-01 09:30:00
Science
e
od
C

Mathematic
202 Umesh Sharma 8.44 2021-09-01 08:30:00
s
203 Rakesh Kumar 5.60 2021-09-01 10:00:00 Biology

204 Radha Sharma 9.20 2021-09-01 12:45:00 Chemistry

sh
to
205 Kush Kumar 7.85 2021-09-01 08:30:00 Physics

hu
206 Prem Chopra
As9.56 2021-09-01 09:24:00 History
ith

207 Pankaj Vats 9.78 2021-09-01 02:30:00 English


W
e

Mathematic
208 Navleen Kaur 7.00 2021-09-01 06:30:00
s
od
C

Program Table

STUDENT_REF_ID PROGRAM_NAME PROGRAM_START_DATE


201 Computer Science 2021-09-01 00:00:00

202 Mathematics 2021-09-01 00:00:00

sh
to
208 Mathematics 2021-09-01 00:00:00

hu
205 Physics
As 2021-09-01 00:00:00
ith

204 Chemistry 2021-09-01 00:00:00


W
e

207 Psychology 2021-09-01 00:00:00


od
C

206 History 2021-09-01 00:00:00


203 Biology 2021-09-01 00:00:00

Scholarship Table

sh
STUDENT_REF_ID SCHOLARSHIP_AMOUNT SCHOLARSHIP_DATE

to
hu
201 5000 2021-10-15 00:00:00
As
202 4500 2022-08-18 00:00:00
ith
W

203 3000 2022-01-25 00:00:00


e
od

201 4000 2021-10-15 00:00:00


C

Let us start by taking a look at some of the most asked SQL Query
interview questions:
1. Write a SQL query to fetch “FIRST_NAME” from the Student table in
upper case and use ALIAS name as STUDENT_NAME.

SELECT upper(FIRST_NAME) as STUDENT_NAME from Student;

Output:
SHIVANSH

sh
UMESH
RAKESH

to
RADHA
KUSH

hu
PREM
PANKAJ As
NAVLEEN

2. Write a SQL query to fetch unique values of MAJOR Subjects from


ith

Student table.

SELECT DISTINCT MAJOR from STUDENT;


W

or
SELECT MAJOR FROM STUDENT GROUP BY(MAJOR);
e

Output:
od

Computer Science
Mathematics
C

Biology
Chemistry
Physics
History
English
3. Write a SQL query to print the first 3 characters of FIRST_NAME
from Student table.

SELECT SUBSTRING(FIRST_NAME, 1, 3) FROM Student;

Output:
Shi

sh
Ume
Rak

to
Rad
Kus

hu
Pre
Pan As
Nav

4. Write a SQL query to find the position of alphabet (‘a’) int the first
ith

name column ‘Shivansh’ from Student table.

SELECT INSTR(FIRST_NAME, 'a') FROM Student WHERE FIRST_NAME =


W

'Shivansh';

Output:
e

5
od

5. Write a SQL query that fetches the unique values of MAJOR Subjects
from Student table and print its length.
C

SELECT MAJOR,LENGTH(MAJOR) FROM Student GROUP BY(MAJOR);


or
SELECT DISTINCT MAJOR, LENGTH(MAJOR) FROM Student;

Output:
MAJOR LENGTH(MAJOR)

Computer Science 16

sh
to
Mathematics 11

hu
As
Biology 7
ith

Chemistry 9
W
e
od

Physics 7
C

History 7
English 7

6. Write a SQL query to print FIRST_NAME from the Student table after
replacing ‘a’ with ‘A’.

sh
SELECT REPLACE(FIRST_NAME, 'a', 'A') FROM Student;

to
Output:

hu
ShivAnsh
Umesh
RAkesh
As
RAdhA
Kush
ith

Prem
PAnkAj
W

NAvleen

7. Write a SQL query to print the FIRST_NAME and LAST_NAME from


e

Student table into single column COMPLETE_NAME.


od

SELECT CONCAT(FIRST_NAME, ' ', LAST_NAME) AS COMPLETE_NAME FROM


Student;
C

Output:
Shivansh Mahajan
Umesh Sharma
Rakesh Kumar
Radha Sharma
Kush Kumar
Prem Chopra
Pankaj Vats
Navleen Kaur

8. Write a SQL query to print all Student details from Student table
order by FIRST_NAME Ascending and MAJOR Subject descending .

sh
SELECT * FROM Student ORDER BY FIRST_NAME , MAJOR DESC;

to
Output:

hu
STUDENT FIRST_NA LAST_NA GP ENROLLMENT_
MAJOR
_ID ME ME A DATE
As
ith

7.8 2021-09-01
205 Kush Kumar Physics
5 08:30:00
W
e
od

2021-09-01 Mathem
208 Navleen Kaur 7
06:30:00 atics
C
9.7 2021-09-01
207 Pankaj Vats English
8 02:30:00

sh
9.5 2021-09-01
206 Prem Chopra History
6 09:24:00

to
hu
2021-09-01 Chemistr
204 Radha Sharma 9.2
12:45:00 y
As
ith

2021-09-01
203 Rakesh Kumar 5.6 Biology
10:00:00
W
e
od

8.7 2021-09-01 Compute


201 Shivansh Mahajan
9 09:30:00 r Science
C
8.4 2021-09-01 Mathem
202 Umesh Sharma
4 08:30:00 atics

9. Write a SQL query to print details of the Students with the

sh
FIRST_NAME as ‘Prem’ and ‘Shivansh’ from Student table.

to
SELECT * from Student WHERE FIRST_NAME IN ('Prem' , 'Shivansh');

Output:

hu
STUDENT FIRST_NA LAST_NA GP ENROLLMENT_D MAJO
As
_ID ME ME A ATE R
ith

Compu
W

8.7 2021-09-01 ter


201 Shivansh Mahajan
9 09:30:00 Scienc
e
e
od
C

9.5 2021-09-01 Histor


206 Prem Chopra
6 09:24:00 y
10. Write a SQL query to print details of the Students excluding
FIRST_NAME as ‘Prem’ and ‘Shivansh’ from Student table.

SELECT * from Student WHERE FIRST_NAME NOT IN ('Prem',


'Shivansh');

Output:

sh
STUDENT FIRST_NA LAST_NA GP ENROLLMENT_
MAJOR
_ID ME ME A DATE

to
hu
8.4 2021-09-01 Mathem
202 Umesh Sharma
As
4 08:30:00 atics
ith

2021-09-01
W

203 Rakesh Kumar 5.6 Biology


10:00:00
e
od

2021-09-01 Chemistr
204 Radha Sharma 9.2
12:45:00 y
C
7.8 2021-09-01
205 Kush Kumar Physics
5 08:30:00

sh
9.7 2021-09-01
207 Pankaj Vats English
8 02:30:00

to
hu
2021-09-01 Mathem
208 Navleen Kaur 7
06:30:00 atics
As
ith

11. Write a SQL query to print details of the Students whose


FIRST_NAME ends with ‘a’.
W

SELECT * FROM Student WHERE FIRST_NAME LIKE '%a';

Output:
e
od

STUDENT FIRST_NA LAST_NA GP ENROLLMENT_D MAJO


_ID ME ME A ATE R
C
2021-09-01 Chemis
204 Radha Sharma 9.2
12:45:00 try

12. Write an SQL query to print details of the Students whose

sh
FIRST_NAME ends with ‘a’ and contains six alphabets.

to
SELECT * FROM Student WHERE FIRST_NAME LIKE '_____a';

hu
13. Write an SQL query to print details of the Students whose GPA lies
between 9.00 and 9.99. As
SELECT * FROM Student WHERE GPA BETWEEN 9.00 AND 9.99;

Output:
ith

STUDENT FIRST_NA LAST_NA GP ENROLLMENT_D MAJO


W

_ID ME ME A ATE R
e
od

2021-09-01 Chemis
204 Radha Sharma 9.2
12:45:00 try
C
9.5 2021-09-01
206 Prem Chopra History
6 09:24:00

sh
9.7 2021-09-01
207 Pankaj Vats English
8 02:30:00

to
hu
14. Write an SQL query to fetch the count of Students having Major
Subject ‘Computer Science’. As
SELECT Major, COUNT(*) as TOTAL_COUNT FROM Student WHERE MAJOR =
'Computer Science';
ith

Output:
W

MAJOR TOTAL_COUNT
e
od

Computer Science 1
C

15. Write an SQL query to fetch Students full names with GPA >= 8.5
and <= 9.5.
SELECT CONCAT(FIRST_NAME, ' ', LAST_NAME) AS FULL_NAME FROM
Student WHERE GPA BETWEEN 8.5 and 9.5;

Output:
Shivansh Mahajan
Radha Sharma

16. Write an SQL query to fetch the no. of Students for each MAJOR

sh
subject in the descending order.

to
SELECT MAJOR, COUNT(MAJOR) from Student group by MAJOR order by
COUNT(MAJOR) DESC;

hu
Output:
As
MAJOR COUNT(MAJOR)
ith

Mathematics 2
W
e

Physics 1
od
C

History 1
English 1

Computer Science 1

sh
to
Chemistry 1

hu
Biology 1
As
ith

17. Display the details of students who have received scholarships,


including their names, scholarship amounts, and scholarship dates.
W

SELECT
Student.FIRST_NAME,
e

Student.LAST_NAME,
od

Scholarship.SCHOLARSHIP_AMOUNT,
Scholarship.SCHOLARSHIP_DATE
C

FROM
Student
INNER JOIN
Scholarship ON Student.STUDENT_ID =
Scholarship.STUDENT_REF_ID;
Output:

FIRST_NA LAST_NA SCHOLARSHIP_AMO SCHOLARSHIP_D


ME ME UNT ATE

sh
2021-10-15
Shivansh Mahajan 5000
00:00:00

to
hu
2022-08-18
Umesh Sharma 4500
As 00:00:00
ith

2022-01-25
Rakesh Kumar 3000
00:00:00
W
e

2021-10-15
od

Shivansh Mahajan 4000


00:00:00
C

18. Write an SQL query to show only odd rows from Student table.

SELECT * FROM Student WHERE student_id % 2 != 0;

Output:
STUDENT FIRST_NA LAST_NA GP ENROLLMENT_D MAJO
_ID ME ME A ATE R

sh
Compu
8.7 2021-09-01 ter
201 Shivansh Mahajan
9 09:30:00 Scienc

to
e

hu
As 2021-09-01 Biolog
203 Rakesh Kumar 5.6
10:00:00 y
ith

7.8 2021-09-01 Physic


W

205 Kush Kumar


5 08:30:00 s
e
od

9.7 2021-09-01 Englis


207 Pankaj Vats
8 02:30:00 h
C

19. Write an SQL query to show only even rows from Student table.

SELECT * FROM Student WHERE student_id % 2 = 0;


Output:

STUDENT FIRST_NA LAST_NA GP ENROLLMENT_


MAJOR
_ID ME ME A DATE

sh
8.4 2021-09-01 Mathem
202 Umesh Sharma

to
4 08:30:00 atics

hu
2021-09-01 Chemistr
204 Radha Sharma
As 9.2
12:45:00 y
ith

9.5 2021-09-01
206 Prem Chopra History
W

6 09:24:00
e
od

2021-09-01 Mathem
208 Navleen Kaur 7
06:30:00 atics
C

20. List all students and their scholarship amounts if they have received
any. If a student has not received a scholarship, display NULL for the
scholarship details.
SELECT
Student.FIRST_NAME,
Student.LAST_NAME,
Scholarship.SCHOLARSHIP_AMOUNT,
Scholarship.SCHOLARSHIP_DATE
FROM

sh
Student
LEFT JOIN

to
Scholarship ON Student.STUDENT_ID =
Scholarship.STUDENT_REF_ID;

hu
21. Write an SQL query to show the top n (say 5) records of Student
table order by descending GPA.
As
SELECT * from Student ORDER BY GPA DESC LIMIT 5;

Output:
ith

STUDENT FIRST_NA LAST_NA GP ENROLLMENT_


W

MAJOR
_ID ME ME A DATE
e
od

9.7 2021-09-01
207 Pankaj Vats English
8 02:30:00
C
9.5 2021-09-01
206 Prem Chopra History
6 09:24:00

2021-09-01 Chemistr

sh
204 Radha Sharma 9.2
12:45:00 y

to
hu
8.7 2021-09-01 Compute
201 Shivansh Mahajan
9
As 09:30:00 r Science

8.4 2021-09-01 Mathem


ith

202 Umesh Sharma


4 08:30:00 atics
W

22. Write an SQL query to determine the nth (say n=5) highest GPA
e

from a table.
od

SELECT * FROM Student ORDER BY GPA DESC LIMIT 5, 1;

Output:
C

STUDENT_ FIRST_NA LAST_NA GP ENROLLMENT_D MAJ


ID ME ME A ATE OR
7.8 2021-09-01
205 Kush Kumar Phys
5 08:30:00

23. Write an SQL query to determine the 5th highest GPA without

sh
using LIMIT keyword.

to
SELECT * FROM Student s1
WHERE 4 = (

hu
SELECT COUNT(DISTINCT (s2.GPA))
FROM Student s2
As
WHERE s2.GPA >= s1.GPA
);
ith

Output:
W

STUDENT FIRST_NA LAST_NA GP ENROLLMENT_D MAJO


_ID ME ME A ATE R
e
od

Compu
C

8.7 2021-09-01 ter


201 Shivansh Mahajan
9 09:30:00 Scienc
e
24. Write an SQL query to fetch the list of Students with the same GPA.

SELECT s1.* FROM Student s1, Student s2 WHERE s1.GPA = s2.GPA


AND s1.Student_id != s2.Student_id;

25. Write an SQL query to show the second highest GPA from a
Student table using sub-query.

sh
SELECT MAX(GPA) FROM Student
WHERE GPA NOT IN(SELECT MAX(GPA) FROM Student);

to
Output:

hu
9.56

26. Write an SQL query to show one row twice in results from a table.
As
SELECT * FROM Student
UNION ALL
ith

SELECT * FROM Student ORDER BY STUDENT_ID;

27. Write an SQL query to list STUDENT_ID who does not get
W

Scholarship.
e

SELECT STUDENT_ID FROM Student


od

WHERE STUDENT_ID NOT IN (SELECT STUDENT_REF_ID FROM


Scholarship);

Output:
C

204
205
206
207
208
28. Write an SQL query to fetch the first 50% records from a table.

SELECT * FROM Student WHERE STUDENT_ID <= (SELECT


COUNT(STUDENT_ID)/2 FROM Student);

29. Write an SQL query to fetch the MAJOR subject that have less than
4 people in it.

sh
SELECT MAJOR, COUNT(MAJOR) AS MAJOR_COUNT FROM Student GROUP BY
MAJOR HAVING COUNT(MAJOR) < 4;

to
Output:

hu
MAJOR MAJOR_COUNT As
Biology 1
ith
W

Chemistry 1
e
od

Computer Science 1
C

English 1
History 1

Mathematics 2

sh
to
Physics 1

hu
30. Write an SQL query to show all MAJOR subject along with the
number of people in there.
As
SELECT MAJOR, COUNT(MAJOR) AS ALL_MAJOR FROM Student GROUP BY
ith

MAJOR;

Output:
W

MAJOR ALL_MAJOR
e
od

Biology 1
C

Chemistry 1
Computer Science 1

English 1

sh
to
History 1

hu
Mathematics 2
As
ith

Physics 1
W

31. Write an SQL query to show the last record from a table.
e

SELECT * FROM Student WHERE STUDENT_ID = (SELECT MAX(STUDENT_ID)


od

FROM STUDENT);

Output:
C

STUDENT FIRST_NA LAST_NA GP ENROLLMENT_


MAJOR
_ID ME ME A DATE
2021-09-01 Mathem
208 Navleen Kaur 7
06:30:00 atics

32. Write an SQL query to fetch the first row of a table.

sh
SELECT * FROM Student WHERE STUDENT_ID = (SELECT MIN(STUDENT_ID)
FROM Student);

to
Output:

hu
STUDENT FIRST_NA LAST_NA
As GP ENROLLMENT_D MAJO
_ID ME ME A ATE R
ith

Compu
8.7 2021-09-01 ter
W

201 Shivansh Mahajan


9 09:30:00 Scienc
e
e
od

33. Write an SQL query to fetch the last five records from a table.
C

SELECT *
FROM (
SELECT *
FROM Student
ORDER BY STUDENT_ID DESC
LIMIT 5
) AS subquery
ORDER BY STUDENT_ID;

Output:

STUDENT FIRST_NA LAST_NA GP ENROLLMENT_

sh
MAJOR
_ID ME ME A DATE

to
hu
2021-09-01 Chemistr
204 Radha Sharma 9.2
As 12:45:00 y

7.8 2021-09-01
ith

205 Kush Kumar Physics


5 08:30:00
W

9.5 2021-09-01
e

206 Prem Chopra History


6 09:24:00
od
C

9.7 2021-09-01
207 Pankaj Vats English
8 02:30:00
2021-09-01 Mathem
208 Navleen Kaur 7
06:30:00 atics

34. Write an SQL query to fetch three max GPA from a table using

sh
co-related subquery.

SELECT DISTINCT GPA FROM Student S1

to
WHERE 3 >= (SELECT COUNT(DISTINCT GPA) FROM Student S2 WHERE
S1.GPA <= S2.GPA) ORDER BY S1.GPA DESC;

hu
Output:
9.78
As
9.56
9.2
ith

35. Write an SQL query to fetch three min GPA from a table using
co-related subquery.
W

SELECT DISTINCT GPA FROM Student S1


e

WHERE 3 >= (SELECT COUNT(DISTINCT GPA) FROM Student S2 WHERE


S1.GPA >= S2.GPA) ORDER BY S1.GPA;
od

Output:
5.6
C

7
7.85

36. Write an SQL query to fetch nth max GPA from a table.

SELECT DISTINCT GPA FROM Student S1


WHERE n >= (SELECT COUNT(DISTINCT GPA) FROM Student S2 WHERE
S1.GPA <= S2.GPA) ORDER BY S1.GPA DESC;

37. Write an SQL query to fetch MAJOR subjects along with the max
GPA in each of these MAJOR subjects.

SELECT MAJOR, MAX(GPA) as MAXGPA FROM Student GROUP BY MAJOR;

Output:

sh
to
MAJOR MAXGPA

hu
Biology 5.6
As
ith

Chemistry 9.2
W

Computer Science 8.79


e
od

English 9.78
C

History 9.56
Mathematics 8.44

Physics 7.85

sh
38. Write an SQL query to fetch the names of Students who has highest

to
GPA.

hu
SELECT FIRST_NAME, GPA FROM Student WHERE GPA = (SELECT MAX(GPA)
FROM Student); As
Output:
ith

FIRST_NAME GPA
W

Pankaj 9.78
e
od

39. Write an SQL query to show the current date and time.
C

Query to get current date :


SELECT CURDATE();
Query to get current date and time :
SELECT NOW();
40. Write a query to create a new table which consists of data and
structure copied from the other table (say Student) or clone the table
named Student.

CREATE TABLE CloneTable AS SELECT * FROM Student;

41. Write an SQL query to update the GPA of all the students in

sh
‘Computer Science’ MAJOR subject to 7.5.

UPDATE Student SET GPA = 4.0 WHERE MAJOR = 'Computer Science';

to
42. Write an SQL query to find the average GPA for each major.

hu
SELECT MAJOR, AVG(GPA) AS AVERAGE_GPA FROM Student GROUP BY
MAJOR;
As
Output:
ith

MAJOR AVERAGE_GPA
W

Biology 5.6
e
od

Chemistry 9.2
C

Computer Science 4
English 9.78

History 9.56

sh
to
Mathematics 7.72

hu
Physics 7.85
As
ith

43. Write an SQL query to show the top 3 students with the highest
GPA.
W

SELECT * FROM Student ORDER BY GPA DESC LIMIT 3;

Output:
e
od

STUDENT FIRST_NA LAST_NA GP ENROLLMENT_D MAJO


_ID ME ME A ATE R
C
9.7 2021-09-01
207 Pankaj Vats English
8 02:30:00

9.5 2021-09-01

sh
206 Prem Chopra History
6 09:24:00

to
hu
2021-09-01 Chemis
204 Radha Sharma 9.2
As 12:45:00 try

44. Write an SQL query to find the number of students in each major
ith

who have a GPA greater than 7.5.

SELECT MAJOR, COUNT(STUDENT_ID) AS HIGH_GPA_COUNT FROM Student


W

WHERE GPA > 3.5 GROUP BY MAJOR;

Output:
e
od

MAJOR HIGH_GPA_COUNT
C

Biology 1
Chemistry 1

Computer Science 1

sh
to
English 1

hu
History 1
As
ith

Mathematics 2
W

Physics 1
e
od

45. Write an SQL query to find the students who have the same GPA as
C

‘Shivansh Mahajan’.

SELECT * FROM Student WHERE GPA = (SELECT GPA FROM Student WHERE
FIRST_NAME = 'Shivansh'
AND LAST_NAME = 'Mahajan');

Output:
STUDENT FIRST_NA LAST_NA GP ENROLLMENT_D MAJO
_ID ME ME A ATE R

Compu

sh
2021-09-01 ter
201 Shivansh Mahajan 4
09:30:00 Scienc

to
e

hu
As
ith
W

Indexing in MySQL
e
od
C

MySQL CREATE INDEX Statement


The CREATE INDEX statement is used to create indexes in tables.

Indexes are used to retrieve data from the database more quickly than
otherwise. The users cannot see the indexes, they are just used to speed up
searches/queries.
Note: Updating a table with indexes takes more time than updating a table without
(because the indexes also need an update). So, only create indexes on columns that will
be frequently searched against.

CREATE INDEX Syntax


Creates an index on a table. Duplicate values are allowed:

sh
CREATE INDEX index_name

to
ON table_name (column1, column2, ...);

hu
CREATE UNIQUE INDEX Syntax As
Creates a unique index on a table. Duplicate values are not allowed:

CREATE UNIQUE INDEX index_name


ith

ON table_name (column1, column2, ...);


W
e

MySQL CREATE INDEX Example


od

The SQL statement below creates an index named "idx_lastname" on the


"LastName" column in the "Persons" table:
C

CREATE INDEX idx_lastname

ON Persons (LastName);
If you want to create an index on a combination of columns, you can list the
column names within the parentheses, separated by commas:

CREATE INDEX idx_pname

ON Persons (LastName, FirstName);

sh
DROP INDEX Statement

to
The DROP INDEX statement is used to delete an index in a table.

hu
ALTER TABLE table_name
As
DROP INDEX index_name;
ith

How to Create Index in MySQL


W

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. It
e

creates an entry for each value of the indexed columns. We use it to quickly find
the record without searching each row in a database table whenever the table is
od

accessed. We can create an index by using one or more columns of the table for
efficient access to the records.
C

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.

Need for Indexing in MySQL


Suppose we have a contact book that contains names and mobile numbers of
the user. In this contact book, we want to find the mobile number of Martin
Williamson. If the contact book is an unordered format means the name of the
contact book is not sorted alphabetically, we need to go over all pages and read
every name until we will not find the desired name that we are looking for. This
type of searching name is known as sequential searching.

To find the name and contact of the user from table contactbooks, generally, we
used to execute the following query:

sh
​ SELECT mobile_number FROM contactbooks WHERE first_name =
'Martin' AND last_name = 'Taybu';

to
This query is very simple and easy. Although it finds the phone number and
name of the user fast, the database searches entire rows of the table until it will

hu
not find the rows that you want. Assume, the contactbooks table contains
millions of rows, then, without an index, the data retrieval takes a lot of time to
find the result. In that case, the database indexing plays an important role in
As
returning the desired result and improves the overall performance of the query.

MySQL CREATE INDEX Statement


Generally, we create an index at the time of table creation in the database. The
ith

following statement creates a table with an index that contains two columns col2
and col3.
W

​ mysql> CREATE TABLE t_index(


​ col1 INT PRIMARY KEY,
​ col2 INT NOT NULL,
​ col3 INT NOT NULL,
e

​ col4 VARCHAR(20),
od

​ INDEX (col2,col3)
​ );
If we want to add index in table, we will use the CREATE INDEX statement as
C

follows:

​ mysql> CREATE INDEX [index_name] ON [table_name] (column


names)
In this statement, index_name is the name of the index, table_name is the name
of the table to which the index belongs, and the column_names is the list of
columns.
Let us add the new index for the column col4, we use the following statement:

​ mysql> CREATE INDEX ind_1 ON t_index(col4);


By default, MySQL allowed index type BTREE if we have not specified the type of
index. The following table shows the different types of an index based on the
storage engine of the table.

Example

sh
In this example, we are going to create a table student and perform the CREATE
INDEX statement on that table.

Table Name: student

to
hu
As
ith

Now, execute the following statement to return the result of the student whose
class is CS branch:
W

​ mysql> SELECT studentid, firstname, lastname FROM student WHERE


class = 'CS';
This statement will give the following output:
e
od
C

In the above table, we can see the four rows that are indicating the students
whose class is the CS branch.
If you want to see how MySQL performs this query internally, execute the
following statement:

​ mysql> EXPLAIN SELECT studentid, firstname, lastname FROM student


WHERE class = 'CS';
You will get the output below. Here, MySQL scans the whole table that contains
seven rows to find the student whose class is the CS branch.

sh
to
Now, let us create an index for a class column using the following statement.

hu
​ mysql> CREATE INDEX class ON student (class);
After executing the above statement, the index is created successfully. Now, run
the below statement to see how MySQL internally performs this query.
As
​ mysql> EXPLAIN SELECT studentid, firstname, lastname FROM student
WHERE class = 'CS';
ith

The above statement gives output, as shown below:


W

In this output, MySQL finds four rows from the class index without scanning the
whole table. Hence, it increases the speed of retrieval of records on a database
e

table.
od

If you want to show the indexes of a table, execute the following statement:

​ mysql> SHOW INDEXES FROM student;


C

It will give the following output.


sh
to
👉
YouTube

hu
https://youtube.com/@codewithashutosh247?si=rXike59WnLhUEUkL
As
👉
Whatsapp Group -
https://chat.whatsapp.com/Iy2Ag6hE35WENehlmNcctV
ith

👉
Telegram Group -
W

https://t.me/+3jqmwqzNp3xlMTZl

👉
Git & GitHub -
e

https://github.com/AshutoshG1?tab=repositories
od
C

You might also like