Most Common SQL Interview Questions with Answers

Most Common SQL Interview Questions with Answers

Day 54 of 60 :Top SQL Interview Questions and Their Detailed Answers

The following are the most popular and useful SQL interview questions and answers for fresher and experienced candidates. These questions are created specifically to familiarise you with the types of questions you might encounter during your SQL interview. According to our experiences, good interviewers rarely plan to ask any specific topic during the interview. Instead, questioning usually begins with a basic understanding of the subject, and based on your responses, further discussion happened.

1) What is SQL?

SQL stands for the Structured Query Language. It is the standard language used to maintain the relational database and perform many different data manipulation operations on the data. SQL was initially invented in 1970. It is a database language used for database creation, deletion, fetching and modifying rows, etc. sometimes, it is pronounced as 'sequel.' We can also use it to handle organized data comprised of entities (variables) and relations between different entities of the data.


2) When SQL appeared?

SQL first appeared in 1974. It is one of the most used languages for maintaining the relational database. In 1986, SQL became the standard of the American National Standards Institute (ANSI) and ISO (International Organization for Standardization) in 1987.


3) What are the usages of SQL?

SQL is responsible for maintaining the relational data and the data structures present in the database. Some of the common usages are given below:

  • To retrieve data from a database

  • To inserts records in a database

  • To updates records in a database

  • To delete records from a database

  • To create new databases

  • To create new tables in a database

  • To create views in a database

  • To perform complex operations on the database.

5) What are the subsets of SQL?

The following are the four significant subsets of the SQL:

  • Data definition language (DDL): It defines the data structure that consists of commands like CREATE, ALTER, DROP, etc.

  • Data manipulation language (DML): It is used to manipulate existing data in the database. The commands in this category are SELECT, UPDATE, INSERT, etc.

  • Data control language (DCL): It controls access to the data stored in the database. The commands in this category include GRANT and REVOKE.

  • Transaction Control Language (TCL): It is used to deal with the transaction operations in the database. The commands in this category are COMMIT, ROLLBACK, SET TRANSACTION, SAVEPOINT, etc.


6) What is the purpose of DDL Language?

DDL stands for Data definition language. It is the subset of a database that defines the data structure of the database when the database is created. For example, we can use the DDL commands to add, remove, or modify tables. It consists of the following commands: CREATE, ALTER and DELETE database objects such as schema, tables, indexes, view, sequence, etc.

Example

CREATE TABLE Students  

(  

Roll_no INT,  

Name VARCHAR(45),  

Branch VARCHAR(30),  

);

7) What is the purpose of DML Language?

Data manipulation language makes the user able to retrieve and manipulate data in a relational database. The DML commands can only perform read-only operations on data. We can perform the following operations using DDL language:

  • Insert data into the database through the INSERT command.

  • Retrieve data from the database through the SELECT command.

  • Update data in the database through the UPDATE command.

  • Delete data from the database through the DELETE command.

8) What is the purpose of DCL Language?

Data control language allows users to control access and permission management to the database. It is the subset of a database, which decides that what part of the database should be accessed by which user at what point of time. It includes two commands, GRANT and REVOKE.

GRANT: It enables system administrators to assign privileges and roles to the specific user accounts to perform specific tasks on the database.

REVOKE: It enables system administrators to revoke privileges and roles from the user accounts so that they cannot use the previously assigned permission on the database.

9) What are tables and fields in the database?

  • A table is a set of organized data in the form of rows and columns.

  • It enables users to store and display records in the structure format.

  • It is similar to worksheets in the spreadsheet application.

  • Here rows refer to the tuples, representing the simple data item, and columns are the attribute of the data items present in a particular row.

  • Columns can categorize as vertical, and Rows are horizontal.

  • Fields are the components to provide the structure for the table.

  • It stores the same category of data in the same data type.

  • A table contains a fixed number of columns but can have any number of rows known as the record.

  • It is also called a column in the table of the database. It represents the attribute or characteristics of the entity in the record.

  • Example :

    • Table: Student

    • Field: Stud_rollno, Stud_name, Date of Birth, Branch, etc.

10) What is a primary key?

  • A primary key is a field or the combination of fields that uniquely identify each record in the table.

  • It is one of a special kind of unique key.

  • If the column contains a primary key, it cannot be null or empty.

  • A table can have duplicate columns, but it cannot have more than one primary key.

  • It always stores unique values into a column.

For example, the ROLL Number can be treated as the primary key for a student in the university or college.

SQL Interview Questions and Answers

We can define a primary key into a student table as follows:

CREATE TABLE Student (    

    roll_number INT PRIMARY KEY,    

    name VARCHAR(45),     

);

11) What is a foreign key?

  • The foreign key is used to link one or more tables together. It is also known as the referencing key.

  • A foreign key is specified as a key that is related to the primary key of another table.

  • It means a foreign key field in one table refers to the primary key field of the other table.

  • It identifies each row of another table uniquely that maintains the referential integrity.

  • The primary key-foreign key relationship is a very crucial relationship as it maintains the ACID properties of the database sometimes.

  • It also prevents actions that would destroy links between the child and parent tables.

We can define a foreign key into a table as follows:

CONSTRAINT constraint_name]    
    FOREIGN KEY [foreign_key_name] (col_name, ...)    
    REFERENCES parent_tbl_name (col_name,...)

12) What is a unique key?

  • A unique key is a single or combination of fields that ensure all values stores in the column will be unique.

  • It means a column cannot stores duplicate values.

  • This key provides uniqueness for the column or set of columns.

  • For example, the email addresses and roll numbers of student's tables should be unique.

  • It can accept a null value but only one null value per column.

  • It ensures the integrity of the column or group of columns to store different values into a table.

We can define a unique key into a table as follows:

CREATE TABLE table_name(    
    col1 datatype,    
    col2 datatype UNIQUE,    
    ...    
);

13) What is the difference between a primary key and a unique key?

The primary key and unique key both are essential constraints of the SQL. The main difference among them is that the primary key identifies each record in the table. In contrast, the unique key prevents duplicate entries in a column except for a NULL value. The following comparison chart explains it more clearly:

Primary KeyUnique Key
The primary key act as a unique identifier for each record in the table.The unique key is also a unique identifier for records when the primary key is not present in the table.
We cannot store NULL values in the primary key column.We can store NULL value in the unique key column, but only one NULL is allowed.
We cannot change or delete the primary key column values.We can modify the unique key column values.

14) What is a Database?

A database is an organized collection of data that is structured into tables, rows, columns, and indexes. It helps the user to find the relevant information frequently. It is an electronic system that makes data access, data manipulation, data retrieval, data storing, and data management very easy. Almost every organization uses the database for storing the data due to its easily accessible and high operational ease. The database provides perfect access to data and lets us perform required tasks.

The following are the common features of a database:

  • Manages large amounts of data

  • Accurate

  • Easy to update

  • Security

  • Data integrity

  • Easy to research data

15) What is meant by DBMS?

DBMS stands for Database Management System. It is a software program that primarily functions as an interface between the database and the end-user. It provides us the power such as managing the data, the database engine, and the database schema to facilitate the organization and manipulation of data using a simple query in almost no time. It is like a File Manager that manages data in a database rather than saving it in file systems. Without the database management system, it would be far more difficult for the user to access the database's data.

The following are the components of a DBMS:

  • Software

  • Data

  • Procedures

  • Database Languages

  • Query Processor

  • Database Manager

  • Database Engine

  • Reporting

16) What are the different types of database management systems?

The database management systems can be categorized into several types. Some of the important lists are given below:

  • Hierarchical databases (DBMS)

  • Network databases (IDMS)

  • Relational databases (RDBMS

  • Object-oriented databases

  • Document databases (Document DB)

  • Graph databases

  • ER model databases

  • NoSQL databases

17) What is RDBMS?

  • RDBMS stands for Relational Database Management System.

  • It is a database management system based on a relational model.

  • It facilitates you to manipulate the data stored in the tables by using relational operators.

  • RDBMS stores the data into the collection of tables and links those tables using the relational operators easily whenever required.

  • Examples of relational database management systems are Microsoft Access, MySQL, SQL Server, Oracle database, etc.

18) What is Normalization in a Database?

Normalization is used to minimize redundancy and dependency by organizing fields and table of a database.There are some rules of database normalization, which is commonly known as Normal From, and they are:

  • First normal form(1NF)

  • Second normal form(2NF)

  • Third normal form(3NF)

  • Boyce-Codd normal form(BCNF)

Using these steps, the redundancy, anomalies, inconsistency of the data in the database can be removed.

19) What is an Index in SQL?

  • An index is a disc structure associated with a table or view that speeds up row retrieval.

  • It reduces the cost of the query because the query's high cost will lead to a fall in its performance.

  • It is used to increase the performance and allow faster retrieval of records from the table.

  • Indexing reduces the number of data pages we need to visit to find a particular data page.

  • It also has a unique value meaning that the index cannot be duplicated.

  • An index creates an entry for each value which makes it faster to retrieve data.

  • For example: Suppose we have a book which carries the details of the countries. If you want to find out information about India, why will you go through every page of that book? You could directly go to the index. Then from the index, you can go to that particular page where all the information about India is given.

20) What are the different types of indexes in SQL?

SQL indexes are nothing more than a technique of minimizing the query's cost. The higher the query's cost, the worse the query's performance. The following are the different types of Indexes supported in SQL:

  • Unique Index

  • Clustered Index

  • Non-Clustered Index

  • Bit-Map Index

  • Normal Index

  • Composite Index

  • B-Tree Index

  • Function-Based Index

21) What are the differences between SQL, MySQL, and SQL Server?

The following comparison chart explains their main differences:

SQLMySQLSQL Server
SQL or Structured Query Language is useful for managing our relational databases. It is used to query and operate the database.MySQL is the popular database management system used for managing the relational database. It is a fast, scalable, and easy-to-use database.SQL Server is an RDBMS database system mainly developed for the Windows system to store, retrieve, and access data requested by the developer.
SQL first appeared in 1974.MySQL first appeared on May 23, 1995.SQL Server first appeared on April 24, 1989.
SQL was developed by IBM Corporation.MySQL was developed by Oracle Corporation.SQL Server was developed by Microsoft Company.
SQL is a query language for managing databases.MySQL is database software that uses SQL language to conduct with the database.SQL Server is also a software that uses SQL language to conduct with the database.
SQL has no variables.MySQL can use variables constraints and data types.SQL Server can use variables constraints and data types.
SQL is a programming language, so that it does not get any updates. Its commands are always fixed and remain the same.MySQL is software, so it gets frequent updation.SQL Server is also software, so it gets frequent updation.

22) What is the difference between SQL and PL/SQL?

The following comparison chart explains their main differences:

SQLPL/SQL
SQL is a database structured query language used to communicate with relational databases. It was developed by IBM Corporations and first appeared in 1974.PL/SQL or Procedural Language/Structured Query Language is a dialect of SQL used to enhance the capabilities of SQL. Oracle Corporation developed it in the early 90's. It uses SQL as its database language.
SQL is a declarative and data-oriented language.PL/SQL is a procedural and application-oriented language.
SQL has no variables.PL/SQL can use variables constraints and data types.
SQL can execute only a single query at a time.PL/SQL can execute a whole block of code at once.
SQL query can be embedded in PL/SQL.PL/SQL cannot be embedded in SQL as SQL does not support any programming language and keywords.
SQL can directly interact with the database server.PL/SQL cannot directly interact with the database server.
SQL is like the source of data that we need to display.PL/SQL provides a platform where SQL data will be shown.

22) Which are joins in SQL? Name the most commonly used SQL joins?

SQL joins are used to retrieve data from multiple tables into a meaningful result set. It is performed whenever you need to fetch records from two or more tables. They are used with SELECT statement and join conditions.

The following are the most commonly used joins in SQL:

  • INNER JOIN

  • LEFT OUTER JOIN

  • RIGHT OUTER JOIN


23) What are the different types of joins in SQL?

Joins are used to merge two tables or retrieve data from tables. It depends on the relationship between tables. According to the ANSI standard, the following are the different types of joins used in SQL:

  • INNER JOIN

  • SELF JOIN

  • LEFT OUTER JOIN

  • RIGHT OUTER JOIN

  • FULL OUTER JOIN

  • CROSS JOIN

SQL Interview Questions and Answers

24)What are the set operators in SQL?

  • We use the set operators to merge data from one or more tables of the same kind.

  • Although the set operators are like SQL joins, there is a significant distinction. SQL joins combine columns from separate tables, whereas SQL set operators combine rows from different queries.

  • SQL queries that contain set operations are called compound queries. The set operators in SQL are categories into four different types:

SQL Interview Questions and Answers

A. UNION: It combines two or more results from multiple SELECT queries into a single result set. It has a default feature to remove the duplicate rows from the tables. The following syntax illustrates the Union operator:

SELECT columns FROM table1    
UNION    
SELECT columns FROM table2;

B. UNION ALL: This operator is similar to the Union operator, but it does not remove the duplicate rows from the output of the SELECT statements. The following syntax illustrates the UNION ALL operator:

SELECT columns FROM table1    
UNION  ALL  
SELECT columns FROM table2;

C. INTERSECT: This operator returns the common records from two or more SELECT statements. It always retrieves unique records and arranges them in ascending order by default. Here, the number of columns and data types should be the same. The following syntax illustrates the INTERSECT operator:

SELECT columns FROM table1    
INTERSECT  
SELECT columns FROM table2;

D. MINUS: This operator returns the records from the first query, which is not found in the second query. It does not return duplicate values. The following syntax illustrates the MINUS operator:

SELECT columns FROM table1    
MINUS  
SELECT columns FROM table2;

25) What is the difference between IN and BETWEEN operators?

The following comparison chart explains their main differences:

BETWEEN OperatorIN Operator
This operator is used to selects the range of data between two values. The values can be numbers, text, and dates as well.It is a logical operator to determine whether or not a specific value exists within a set of values. This operator reduces the use of multiple OR conditions with the query.
It returns records whose column value lies in between the defined range.It compares the specified column's value and returns the records when the match exists in the set of values.
The following syntax illustrates this operator:
SELECT * FROM table_name
WHERE column_name BETWEEN 'value1' AND 'value2';The following syntax illustrates this operator:
SELECT * FROM table_name
WHERE column_name IN ('value1','value 2');

26) What is the difference between DELETE and TRUNCATE statements in SQL?

The main difference between them is that the delete statement deletes data without resetting a table's identity, whereas the truncate command resets a particular table's identity. The following comparison chart explains it more clearly:

No.DELETETRUNCATE
1)The delete statement removes single or multiple rows from an existing table depending on the specified condition.The truncate command deletes the whole contents of an existing table without the table itself. It preserves the table structure or schema.
2)DELETE is a DML command.TRUNCATE is a DML command.
3)We can use the WHERE clause in the DELETE command.We cannot use the WHERE clause with TRUNCATE.
4)DELETE statement is used to delete a row from a table.TRUNCATE statement is used to remove all the rows from a table.
5)DELETE is slower because it maintained the log.TRUNCATE statement is faster than DELETE statement as it deletes entire data at a time without maintaining transaction logs.
6)You can roll back data after using the DELETE statement.It is not possible to roll back after using the TRUNCATE statement.
7)DELETE query takes more space.TRUNCATE query occupies less space.

27) What is the ACID property in a database?

The ACID properties are meant for the transaction that goes through a different group of tasks. A transaction is a single logical order of data. It provides properties to maintain consistency before and after the transaction in a database. It also ensures that the data transactions are processed reliably in a database system.

The ACID property is an acronym for Atomicity, Consistency, Isolation, and Durability.

Atomicity: It ensures that all statements or operations within the transaction unit must be executed successfully. If one part of the transaction fails, the entire transaction fails, and the database state is left unchanged. Its main features are COMMIT, ROLLBACK, and AUTO-COMMIT.

Consistency: This property ensures that the data must meet all validation rules. In simple words, we can say that the database changes state only when a transaction will be committed successfully. It also protects data from crashes.

Isolation: This property guarantees that the concurrent property of execution in the transaction unit must be operated independently. It also ensures that statements are transparent to each other. The main goal of providing isolation is to control concurrency in a database.

Durability: This property guarantees that once a transaction has been committed, it persists permanently even if the system crashes, power loss, or failed.

28) Is a blank space or zero the same as a NULL value?

No. The NULL value is not the same as zero or a blank space. The following points explain their main differences:

  • A NULL value is a value, which is 'unavailable, unassigned, unknown or not applicable.' It would be used in the absence of any value. We can perform arithmetic operations on it. On the other hand, zero is a number, and a blank space is treated as a character.

  • The NULL value can be treated as an unknown and missing value, but zero and blank spaces differ from the NULL value.

  • We can compare a blank space or a zero to another blank space or a zero. On the other hand, one NULL may not be the same as another NULL. NULL indicates that no data has been provided or that no data exists.

29) How do we use the DISTINCT statement? What is its use?

The DISTINCT keyword is used to ensure that the fetched value always has unique values. It does not allow to have duplicate values. The DISTINCT keyword is used with the SELECT statement and retrieves different values from the table's column. We can use it with the help of the following syntax:

SELECT DISTINCT column_lists FROM table_name WHERE [condition];

Suppose we have a table 'customer' containing eight records in which the name column has some duplicate values.

SQL Interview Questions and Answers

If we want to get the name column without any duplicate values, the DISTINCT keyword is required. Executing the below command will return a name column with unique values.

SQL Interview Questions and Answers

30) What is the default ordering of data using the ORDER BY clause? How could it be changed?

The ORDER BY clause is used to sort the table data either in ascending or descending order. By default, it will sort the table in ascending order. If we want to change its default behavior, we need to use the DESC keyword after the column name in the ORDER BY clause.

The syntax to do this is given below:

SELECT expressions FROM tables    
WHERE conditions    
ORDER BY expression [ASC | DESC];
  • We have taken a customer table in the previous example. Now, we will demonstrate the ORDER BY clause on them as well.

  • In the below output, we can see that the first query will sort the table data in ascending order based on the name column. However, if we run the second query by specifying the DESC keyword, the table's order is changed in descending order.

SQL Interview Questions and Answers

31) What is the difference between the WHERE and HAVING clauses?

The main difference is that the WHERE clause is used to filter records before any groupings are established, whereas the HAVING clause is used to filter values from a group. The below comparison chart explains the most common differences:

WHEREHAVING
This clause is implemented in row operations.This clause is implemented in column operations.
It does not allow to work with aggregate functions.It can work with aggregate functions.
This clause can be used with the SELECT, UPDATE, and DELETE statements.This clause can only be used with the SELECT statement.

32) How many Aggregate functions are available in SQL?

The aggregate function is used to determine and calculate several values in a table and return the result as a single number. For example, the average of all values, the sum of all values, and the maximum and minimum value among particular groupings of values.

The following syntax illustrates how to use aggregate functions:

function_name (DISTINCT | ALL expression)

SQL provides seven (7) aggregate functions, which are given below:

  • AVG(): This function is used to returns the average value from specified columns.

  • COUNT(): This function is used to returns the number of table rows, including rows with null values.

  • MAX(): This function is used to returns the largest value among the group.

  • MIN(): This function is used to returns the smallest value among the group.

  • SUM(): This function is used to returns the total summed values(non-null) of the specified column.

  • FIRST(): This function is used to returns the first value of an expression.

  • LAST(): This function is used to returns the last value of an expression.

SQL Query Interview Questions for freshers

1. Write an SQL query to fetch the EmpId and FullName of all the employees working under the Manager with id – ‘986’.
We can use the EmployeeDetails table to fetch the employee details with a where clause for the manager-

SELECT  EmpId, FullName
FROM EmployeeDetails
WHERE ManagerId = 986;

2. Write an SQL query to fetch the different projects available from the EmployeeSalary table.
While referring to the EmployeeSalary table, we can see that this table contains project values corresponding to each employee, or we can say that we will have duplicate project values while selecting Project values from this table.

So, we will use the distinct clause to get the unique values of the Project.

SELECT DISTINCT(Project)
FROM EmployeeSalary;

3. Write an SQL query to fetch the count of employees working in project ‘P1’.
Here, we would be using aggregate function count() with the SQL where clause-

SELECT COUNT(*) 
FROM EmployeeSalary 
WHERE Project = 'P1';

**4. Write an SQL query to find the maximum, minimum, and average salary of the employees.
**We can use the aggregate function of SQL to fetch the max, min, and average values-

SELECT Max(Salary), 
Min(Salary), 
AVG(Salary) 
FROM EmployeeSalary;

5. Write an SQL query to find the employee id whose salary lies in the range of 9000 and 15000.
Here, we can use the ‘Between’ operator with a where clause.

SELECT EmpId, Salary
FROM EmployeeSalary
WHERE Salary BETWEEN 9000 AND 15000;

6. Write an SQL query to fetch those employees who live in Toronto and work under the manager with ManagerId – 321.
Since we have to satisfy both the conditions – employees living in ‘Toronto’ and working in Project ‘P2’. So, we will use the AND operator here-

SELECT EmpId, City, ManagerId
FROM EmployeeDetails
WHERE City='Toronto' AND ManagerId='321';

7. Write an SQL query to fetch all the employees who either live in California or work under a manager with ManagerId – 321.
This interview question requires us to satisfy either of the conditions – employees living in ‘California’ and working under Manager with ManagerId – 321. So, we will use the OR operator here-

SELECT EmpId, City, ManagerId
FROM EmployeeDetails
WHERE City='California' OR ManagerId='321';

8. Write an SQL query to fetch all those employees who work on Projects other than P1.
Here, we can use the NOT operator to fetch the rows which are not satisfying the given condition.

SELECT EmpId
FROM EmployeeSalary
WHERE NOT Project='P1';

Or using the ‘not equal to’ operator-

SELECT EmpId
FROM EmployeeSalary
WHERE Project <> 'P1';

For the difference between NOT and <> SQL operators, check this link – Difference between the NOT and != operators.

9. Write an SQL query to display the total salary of each employee adding the Salary with Variable value.
Here, we can simply use the ‘+’ operator in SQL.

SELECT EmpId,
Salary+Variable as TotalSalary 
FROM EmployeeSalary;

10. Write an SQL query to fetch the employees whose name begins with any two characters, followed by a text “hn” and ends with any sequence of characters.
For this question, we can create an SQL query using like operator with ‘_’ and ‘%’ wild card characters, where ‘_’ matches a single character and ‘%’ matches ‘0 or multiple characters.

SELECT FullName
FROM EmployeeDetails
WHERE FullName LIKE ‘__hn%’;

11. Write an SQL query to fetch all the EmpIds which are present in either of the tables – ‘EmployeeDetails’ and ‘EmployeeSalary’.
In order to get unique employee ids from both tables, we can use the Union clause which can combine the results of the two SQL queries and return unique rows.

SELECT EmpId FROM EmployeeDetails
UNION 
SELECT EmpId FROM EmployeeSalary;

12. Write an SQL query to fetch common records between two tables.
SQL Server – Using INTERSECT operator-

SELECT * FROM EmployeeSalary
INTERSECT
SELECT * FROM ManagerSalary;

MySQL – Since MySQL doesn’t have INTERSECT operator so we can use the subquery-

SELECT *
FROM EmployeeSalary
WHERE EmpId IN 
(SELECT EmpId from ManagerSalary);

13. Write an SQL query to fetch records that are present in one table but not in another table.
SQL Server – Using MINUS- operator-

SELECT * FROM EmployeeSalary
MINUS
SELECT * FROM ManagerSalary;

MySQL – Since MySQL doesn’t have a MINUS operator so we can use LEFT join-

SELECT EmployeeSalary.*
FROM EmployeeSalary
LEFT JOIN
ManagerSalary USING (EmpId)
WHERE ManagerSalary.EmpId IS NULL;

14. Write an SQL query to fetch the EmpIds that are present in both the tables – ‘EmployeeDetails’ and ‘EmployeeSalary.
Using subquery-

SELECT EmpId FROM 
EmployeeDetails 
where EmpId IN 
(SELECT EmpId FROM EmployeeSalary);

15. Write an SQL query to fetch the EmpIds that are present in EmployeeDetails but not in EmployeeSalary.
Using subquery-

SELECT EmpId FROM 
EmployeeDetails 
where EmpId Not IN 
(SELECT EmpId FROM EmployeeSalary);

16. Write an SQL query to fetch the employee’s full names and replace the space with ‘-’.
Using the ‘Replace’ function-

SELECT REPLACE(FullName, ' ', '-') 
FROM EmployeeDetails;

17. Write an SQL query to fetch the position of a given character(s) in a field.
Using the ‘Instr’ function-

SELECT INSTR(FullName, 'Snow')
FROM EmployeeDetails;

18. Write an SQL query to display both the EmpId and ManagerId together.
Here we can use the CONCAT command.

SELECT CONCAT(EmpId, ManagerId) as NewId
FROM EmployeeDetails;

19. Write a query to fetch only the first name(string before space) from the FullName column of the EmployeeDetails table.
In this question, we are required to first fetch 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

SELECT MID(FullName, 1, LOCATE(' ',FullName)) 
FROM EmployeeDetails;

SQL Server – using SUBSTRING

SELECT SUBSTRING(FullName, 1, CHARINDEX(' ',FullName)) 
FROM EmployeeDetails;

20. Write an SQL query to uppercase the name of the employee and lowercase the city values.
We can use SQL Upper and Lower functions to achieve the intended results.

SELECT UPPER(FullName), LOWER(City) 
FROM EmployeeDetails;

21. Write an SQL query to find the count of the total occurrences of a particular character – ‘n’ in the FullName field.
Here, we can use the ‘Length’ function. We can subtract the total length of the FullName field from the length of the FullName after replacing the character – ‘n’.

SELECT FullName, 
LENGTH(FullName) - LENGTH(REPLACE(FullName, 'n', ''))
FROM EmployeeDetails;

22. Write an SQL query to update the employee names by removing leading and trailing spaces.
Using the ‘Update’ command with the ‘LTRIM’ and ‘RTRIM’ functions.

UPDATE EmployeeDetails 
SET FullName = LTRIM(RTRIM(FullName));

23. Fetch all the employees who are not working on any project.
This is one of the very basic interview questions in which the interviewer wants to see if the person knows about the commonly used – Is NULL operator.

SELECT EmpId 
FROM EmployeeSalary 
WHERE Project IS NULL;

24. Write an SQL query to fetch employee names having a salary greater than or equal to 5000 and less than or equal to 10000.
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 a subquery to find the fullName of the employee from the EmployeeDetails table.

SELECT FullName 
FROM EmployeeDetails 
WHERE EmpId IN 
(SELECT EmpId FROM EmployeeSalary 
WHERE Salary BETWEEN 5000 AND 10000);

25. Write an SQL query to find the current date-time.
MySQL-

SELECT NOW();