Wa0012.
Wa0012.
Q. 1. What is SQL?
SQL is a database language designed for the retrieval and management of data
in a relational database. SQL is the standard language for database management.
SQL programming language uses various commands for different operations.
SQL Commands:
o SQL commands are instructions. It is used to communicate with the
database. It is also used to perform specific tasks, functions, and queries
of data.
o SQL can perform various tasks like create a table, add data to tables, drop
the table, modify the table, and set permission for users.
Structured Query Language (SQL) Commands from the name itself it’s very
obvious that we are going to discuss different SQL Commands. SQL is the
foundation of relational databases, which are one of the most common
databases. As a result, SQL abilities are required in almost every employment
role. In this blog on SQL Commands, SQL is the industry standard for database
management. It is a database language that allows you to manage and retrieve
data from relational databases. All relational database management systems
(RDBMS) like SQL Server, MySQL, Oracle, Sybase, Postgres, MS-Access use
SQL as their standard database language.
Consider the following two tables for reference while to solve the SQL
queries for practical.
• Table – EmployeeDetails
• Table – EmployeeSalary
First create database:
mysql> create database EmployeeDetails;
Query OK, 1 row affected (0.00 sec)
Change the database:
mysql> use EmployeeDetails;
Database changed
Q. 9. Write an SQL query to get all the EmpIds which are present in either
of the tables – ‘EmployeeDetails’ and ‘EmployeeSalary’.
Ans. In order to get unique employee ids from both the tables, we can use
Union clause which can combine the results of the two SQL queries and return
unique rows.
Ans: mysql> SELECT EmpId FROM EmployeeDetails where EmpId IN
(SELECT EmpId FROM EmployeeSalary);
+-------+
| EmpId |
+-------+
| 121 |
| 321 |
| 421 |
+-------+
3 rows in set (0.01 sec)
Q. 10. Write an SQL query to get the EmpIds that are present in
EmployeeDetails but not in EmployeeSalary.
Ans. Using sub query-
Ans: mysql> SELECT EmpId FROM EmployeeDetails where EmpId Not IN
(SELECT EmpId FROM EmployeeSalary);
+-------+
| EmpId |
+-------+
| 244 |
| 610 |
| 110 |
| 245 |
| 127 |
| 213 |
| 753 |
+-------+
7 rows in set (0.01 sec)
Q. 11. Write an SQL query to get the employee full names and replace the
space with ‘-’.
Ans. Using ‘Replace’ function-
mysql> SELECT REPLACE(FullName,'','-')FROM EmployeeDetails;
+--------------------------+
| REPLACE(FullName,'','-') |
+--------------------------+
| John Snow |
| Walter White |
| Kuldeep Rana |
| Ranjeet Ravat |
| Sanjay Pawar |
| jaya Kumari |
| Shruti Sharma |
| Sandeep Rajput |
| John Dsouja |
| Ritesh Deshmukh |
+--------------------------+
10 rows in set (0.01 sec)
Q. 12. Write an SQL query to get the position of a given character(s) in a
field.
Ans. Using ‘Instr’ function-
mysql> SELECT INSTR('FullName','Snow')FROM EmployeeDetails;
+------------------------+
| INSTR('FullName','Snow') |
+------------------------+
| 6|
| 0|
| 0|
| 0|
| 0|
| 0|
| 0|
| 0|
| 0|
| 0|
+------------------------+
10 rows in set (0.00 sec)
Q. 13. Write an SQL query to display both the EmpId and ManagerId
together.
Ans. Here we can use the CONCAT command.
mysql> SELECT CONCAT(EmpId,ManagerId) as NewId FROM
EmployeeDetails;
+--------+
| NewId |
+--------+
| 121321 |
| 321986 |
| 421876 |
| 244651 |
| 610540 |
| 110350 |
| 245148 |
| 127345 |
| 213114 |
| 753165 |
+--------+
10 rows in set (0.00 sec)
Q. 14. Write a query to get only the first name(string before space) from
the FullName column of the EmployeeDetails table.
Ans. In this question, we are required to first get the location of the space
character in the FullName field and then extract the first name out of the
FullName field.
For finding the location we will use the LOCATE method in MySQL and
CHARINDEX in SQL SERVER and for fetching the string before space, we
will use the SUBSTRING OR MID method.
MySQL – using MID
mysql> SELECT MID(FullName,1,LOCATE('',FullName)) FROM
EmployeeDetails;
+-----------------------------------------------------+
| MID('FullName',1,LOCATE('FullName'); |
+-----------------------------------------------------+
|J |
|W |
|K |
|R |
|S |
|j |
|S |
|S |
|J |
|R |
+----------------------------------------------------+
10 rows in set (0.01 sec)
Q. 15. Write an SQL query to upper case the name of the employee and
lower case the city values.
Ans. We can use SQL Upper and Lower functions to achieve the intended
results.
mysql> SELECT UPPER('FullName'),LOWER('City') FROM
EmployeeDetails;
+-----------------+--------------------------+
| UPPER('FullName') | LOWER('City') |
+-----------------+--------------------------+
| JOHN SNOW | toronto |
| WALTER WHITE | california |
| KULDEEP RANA | new delhi |
| RANJEET RAVAT | mumbai |
| SANJAY PAWAR | chennai |
| JAYA KUMARI | pune |
| SHRUTI SHARMA | jalna |
| SANDEEP RAJPUT | beed |
| JOHN DSOUJA | london |
| RITESH DESHMUKH | America |
+-----------------+--------------------------+
10 rows in set (0.00 sec)
Q. 16. Write an SQL query to find the count of the total occurrences of a
particular character – ‘n’ in the FullName field.
Ans. Here, we can use the ‘Length’ function. We can subtract the total length of
the FullName field with a length of the FullName after replacing the character –
‘n’.
mysql> SELECT FullName, LENGTH('FullName') -
LENGTH(REPLACE('FullName','n',''))FROM EmployeeDetails;
+----------------- +-----------------------------------------------------+
| FullName LENGTH(FullName) -
LENGTH(REPLACE('FullName','n','')) |
+----------------- +-----------------------------------------------------+
| John Snow | 2|
| Walter White | 0|
| Kuldeep Rana | 1|
| Ranjeet Ravat | 1|
| Sanjay Pawar | 1|
| jaya Kumari | 0|
| Shruti Sharma | 0|
| Sandeep Rajput | 1|
| John Dsouja | 1|
| Ritesh Deshmukh | 0|
+-----------------+-----------------------------------------------------+
10 rows in set (0.00 sec)
**Update existing data in tables using SQL queries
Q. 17. Write an SQL query to update the employee names by removing
leading and trailing spaces.
Ans. Using the ‘Update’ command with the ‘LTRIM’ and ‘RTRIM’ function.
mysql> UPDATE EmployeeDetails SET
FullName=LTRIM(RTRIM('FullName'));
Query OK, 0 rows affected (0.01 sec)
Rows matched: 10 Changed: 0 Warnings: 0
Q. 18. Get all the employees who are not working on any project.
Ans. Commonly used – Is NULL operator.
mysql> SELECT EmpId FROM EmployeeSalary WHERE Project IS NULL;
Empty set (0.00 sec)
Q. 19. Write an SQL query to get employee names having a salary greater
than or equal to 5000 and less than or equal to 10000.
Ans. Here, we will use BETWEEN in the ‘where’ clause to return the EmpId of
the employees with salary satisfying the required criteria and then use it as
subquery to find the fullName of the employee from EmployeeDetails table.
mysql> SELECT FullName FROM EmployeeDetails WHERE EmpId IN
(SELECT EmpId FROM EmployeeSalary WHERE Salary BETWEEN 5000
AND 10000);
+----------------+
| FullName |
+----------------+
| John Snow |
| Walter White |
+-----------------+
2 rows in set (0.00 sec)
Q. 20. Write an SQL query to find the current date-time.
mysql> SELECT NOW();SQL Server- SELECT getdate();
+---------------------+
| NOW() |
+---------------------+
| 2021-12-31 12:31:34 |
+---------------------+
1 row in set (0.00 sec)
Q. 21. Write an SQL query to get all the Employees details from
EmployeeDetails table that joined in the Year 2020.
Ans. Using BETWEEN for the date range ’01-01-2020′ AND ’31-12-2020′-
mysql> SELECT * FROM EmployeeDetails WHERE DateOfJoining
BETWEEN '2020/01/01'AND'2020/12/31';
Empty set (0.00 sec)
Also, we can extract year part from the joining date (using YEAR in mySQL)-
mysql> SELECT*FROM EmployeeDetails WHERE
YEAR(DateOfJoining)='2020';
Empty set (0.00 sec)
Q. 22. Write an SQL query to get all employee records from
EmployeeDetails table who have a salary record in EmployeeSalary table.
Ans. Using ‘Exists’-
mysql> SELECT * FROM EmployeeDetails E WHERE EXISTS (SELECT *
FROM EmployeeSalary S WHERE E.EmpId=S.EmpId);
+-------+--------------+-----------+---------------+---------------------+
| EmpId | FullName | ManagerId | DateOfJoining | City |
+-------+------------------+-----------+---------------+-----------------+
| 121 | John Snow | 321 | 2014-01-31 | Toronto |
| 321 | Walter White | 986 | 2015-01-30 | California |
| 421 | Kuldeep Rana | 876 | 2016-11-27 | New Delhi |
+-------+--------------+-----------+---------------+------------+
3 rows in set (0.00 sec)
Q. 23. Write an SQL query to get project-wise count of employees sorted by
project’s count in descending order.
Ans. The query has two requirements – first to fetch the project-wise count and
then to sort the result by that count.
For project-wise count, we will be using the GROUP BY clause and for sorting,
we will use the ORDER BY clause on the alias of the project-count.
mysql> SELECT Project,count(EmpId)EmpProjectCount FROM
EmployeeSalary GROUP BY Project ORDER BY EmpProjectCount DESC;
+---------+-----------------------+
| Project | EmpProjectCount |
+---------+-----------------------+
| P1 | 2 |
| P2 | 2 |
| P3 | 2 |
| P5 | 2 |
| P4 | 1 |
| P6 | 1 |
+---------+-----------------------+
6 rows in set (0.00 sec)
Q. 24. Write a query to get employee names and salary records. Display the
employee details even if the salary record is not present for the employee.
Ans. This is again one of the very common interview questions in which the
interviewer just wants to check the basic knowledge of SQL JOINS.
Here, we can use left join with EmployeeDetail table on the left side of the
EmployeeSalary table.
mysql> SELECT E.FullName,S.Salary FROM EmployeeDetails E LEFT JOIN
EmployeeSalary S ON E.EmpId=S.EmpId;
+--------------------+--------------+
| FullName | Salary |
+--------------------+------------+
| John Snow | 8000 |
| Walter White | 10000 |
| Kuldeep Rana | 12000 |
| Ranjeet Ravat | NULL |
| Sanjay Pawar | NULL |
| jaya Kumari | NULL |
| Shruti Sharma | NULL |
| Sandeep Rajput | NULL |
| John Dsouja | NULL |
| Ritesh Deshmukh | NULL |
+-----------------+----------------+
10 rows in set (0.00 sec
Q. 25. Write an SQL get to get all the Employees who are also managers
from the EmployeeDetails table.
Ans. Here, we have to use Self-Join as the requirement wants us to analyze the
EmployeeDetails table as two tables. We will use different aliases ‘E’ and ‘M’
for the same EmployeeDetails table.
mysql> SELECT DISTINCT E.FullName FROM EmployeeDetails E INNER
JOIN EmployeeDetails M ON E.EmpID=M.ManagerID;
+----------------+
| FullName |
+----------------+
| Walter White |
+----------------+
1 row in set (0.00 sec)
Q. 26. Write an SQL query to get duplicate records from EmployeeDetails
(without considering the primary key – EmpId).
Ans. In order to find duplicate records from the table, we can use GROUP BY
on all the fields and then use the HAVING clause to return only those fields
whose count is greater than 1 i.e. the rows having duplicate records.
mysql> SELECT FullName,ManagerId, DateOfJoining,City, COUNT(*)
FROM EmployeeDetails GROUP BY FullName,
ManagerId,DateOfJoining,City HAVING COUNT(*)>1;
Empty set (0.00 sec).
**Delete data from tables using SQL queries
Q. 27. Write an SQL query to remove duplicates from a table without using
a temporary table.
Ans. Here, we can use delete with dubbed and inner join. We will check for the
equality of all the matching records and then remove the row with higher
EmpId.
mysql> DELETE E1 FROM EmployeeDetails E1 INNER JOIN
EmployeeDetails E2 WHERE E1.EmpId>E2.EmpId AND
E1.FullName=E2.FullName AND E1.ManagerId=E2.managerId AND
E1.DateOfJoining=E2.DateOfJoining AND E1.City=E2.City;
Query OK, 0 rows affected (0.00 sec)
** Use data normalization techniques to design and create efficient
database schemas.
1NF Example
In our database, we have two people with the same name Robert Phil, but they
live in different places.
A foreign key can have a different name from its primary key
It ensures rows in one table have corresponding rows in another
Unlike the Primary key, they do not have to be unique. Most often they
aren’t
Foreign keys can be null even though primary keys can not
Why do you need a foreign key?
Suppose, a novice inserts a record in Table B such as
You will only be able to insert values into your foreign key that exist in the
unique key in the parent table. This helps in referential integrity.
Now, if somebody tries to insert a value in the membership id field that does not
exist in the parent table, an error will be shown!
Consider the table 1. Changing the non-key column Full Name may change
Salutation.
Rule 1- Be in 2NF
Rule 2- Has no transitive functional dependencies
To move our 2NF table into 3NF, we again need to again divide our table.
3NF Example
Below is a 3NF example in SQL database:
We have again divided our tables and created a new table which stores
Salutations.
There are no transitive functional dependencies, and hence our table is in 3NF