SQL Technical Interview Questions
SQL Technical Interview Questions
Content
Introduction
Select Command
Update Command
Delete Command
Functions
Structure of Select
Sub Queries
Joins
Normalization
Dependencies
Types of Normalization
Constraints
Data:
Data Refers to small volume of facts and Figures.
Database:
Database refers to Large volume of Facts and figures.
→ Storing Permanently
→ Retrieving Efficiently
Note:
Managing the Facts and Figures are very important.
Ledger
The large volume of facts and figures stored on the ledger should be transfered to computers and
managed.
Then people started to demand for a software to manage the large volume of a facts and figures
(Database).
SQL:
SQL stands for Structured query Language It is a Language. It is a language which is used to
communicate with the database.
Creating a table
Create table Person
(
name varchar2(10),
age number,
gender varchar2(6),
percentage number
);
Ex: Create a table for storing the following details of a patient.
Create table Patient
(
P_id number,
P_name varchar2(10),
P_gender varchar2(6),
Treatment varchar2(15),
Address varchar2(15)
);
Patient:
1. Create a table
RAM
HDD
PERSON
RAM
HDD
SQL >
SQL> conn
name varchar2(10),
age number,
gender varchar2(6),
percentage number
);
Table created.
SQL> insert into Person values('Ankit', 22; Male', 78);
1 row created.
HDD
SELECT:
In SQL, the data can be retrieved using select command.
Syntax:
Que1) Write a query to display the id of all the students from the student table
Output:-
Que2) Write a query to display id and name of all students from the student table.
Output:
Output:-
Que4) Write a query to display id, name, age and gender of all the students from the student table.
Output:-
Que5) Write a query to display all the data from student table.
Ans) select id, name, age, gender, sem from student
(Or)
Output:
Que6) Write a query to display name of students whose age is greater than 25 from the student
table.
Output:
Que7) Write a query to display id, name, age and gender from student table whose gender is Male.
Ans) select id, name, age, gender from student where gender = ‘Male’
Output:
Que8) Write a query to display all the columns where sem is 6 from the student table.
Ans) select id, name, age, gender, sem from student where sem=6
(or)
Output:
Projection:
Projection is the process of retrieving all the records from table without restriction. To perform
projection select command and from clause is used.
Selection:
Selection is the process of retrieving the specific records from the table with restriction. To
perform selection, select command, from, and where clause is used.
Select with Operators
Write a query to display all the Columns from Employee table where salary is greater. than 41000
Write a query to display the id, name, email and Salary from employee table by reducing the Salary
of 1000 rs.
Write a query to display the id, name, email and salary from employee table by giving hike of 10
percent
> select id, name, email, salary + (salary * 10/100) from Employee
Write a query to display the id, name, email and Salary from employee table by reducing the salary
by 20 percent
Write a query to display the half yearly Salary from Employee table.
Precedence of Operators:-
OPERATORS PRECEDENCE
* 1
/ 2
+ 3
- 4
UPDATE
To update or modify the existing record or cell in a table is called as updation. I can be achieved
by using update command in SQL
Syntax :-
where condition;
Eg: Write a query to update the email to ‘ vivek123@g mail.com’ from customer with name Vivek
in Bank table
Write a query to update the password to ‘pooja7777’ for the customer with name ‘pooja’ in Bank
table
> update bank set balance = 91000 where name =’ Darshan’ and accno=5555
DELETE
5 row(s) deleted.
Write a query to delete the record of Customer whose name is 'priya' from table.
1 Row'(s) deleted.
1 Row'(s) deleted
FUNCTIONS
Que1) Write a query to display names in uppercase from student table.
Output-
Output:-
Que3) Write a query to display length of all name from student table.
Output:
Que4) Write a query to concentrate the data of name and age from student table.
Output:
Que5) Write a query to the substring of name from 2nd position in student table.
Output:
Que6) Write a query to the substring of name from 2nd position and extract 3 characters in student
table.
Output:
Que7) Write a query to display the position of a the Character 'a' in all the names in student table.
Ans) select instr(name, 'a') from student
Output:-
Que8) Write a query to trim leading '2' in all age in student table.
Output:-
Que9) Write a query to the trim trailing 'e' in all gender in student table.
ans) select trim (tralling ‘ e’ from gender) from student
Qutput:
Output:
Que11) Write a query to display the average of all the ages of student.
Ans) select avg (age) from student
Output:
Que12 ) Write a query to display the sum of all the ages of student table.
Output:
Output:
Que14) Wnite a query to display the total number of rows of student table.
Ans)select count(*) from student
Output:-
lower()
length ()
concat()
substr()
instr()
trim()
max()
sum()
avg ()
count()
Que1) Write a query to display the team and sum of salaries in each team from Employee table.
from Employee
group by team
Output:-
Que 2) Write a query to display the team and maximum salary of the employees in each team from
Employee table.
from Employee
group by team
Output:
Que3) Write a query to display the team & sum of salaries in each team from Employee table
where sum of salary is greater than 100000.
from Employee
group by team
Output:
Que4) Write a query to display the team and maximum Salary in each team where maximum
salary in greater than 40000 in Employee table.
from Employee
group by team
Output:
Que5) WAQ to display the team and maximum salary in each team where maximum salary is
greater than 40000 in Employee
from employee
group by team
Output:
Que6) WAQ to display the team and maximum salary in each team where maximum salary is
greater than 40000 in Employee table in descending order.
from employee
group by team
having max(salary)>4000 .
Output:
Que7) WAQ to display the team and maximum salary in each team Where age is greater than 23
and the maximum salary than 46000 from employee table in descending order.
from Employee
where age>23
group by team
Output:-
Structure of select
Select → What data to be displayed
Que1) WAQ to display the id, name and salary of the employees whose salary is greater than
Suraj’s salary from the Employee table.
from Employee
Output:
Que2) Write a query to display the id, name, age and salary of the employees whose age is equal
to Kavya’s age from the Employee table.
Output:
Que3) WAQ to display name, age and team of all the employees whose age is greater than
‘Rimjhim’ age and who is working in the same team where Naveen is working from the Employee
table.
from Employee
and
Output:
Joins:
Joins:A join clause is used to combine the records from two or more tables by comparing
them.
Types of joins:-
1. Equi join or Inner join
2. Natural join
3. Outer Join
4. Cross join
Equi Join: It is used to compare the tables and returns all the rows when there is atleast one
match in both tables. It is also called as Inner join
Inner Join: It is used to compare the tables and returns all the rows when there is atleast one
match in both table but it maintains only one copy of the column common
Que) Write a query to display all the rows from table 1 and table2 where table1 column B is equal
to table2 column B using inner join keyword..
ans) select *
Output:-
Que) Write a query to display all the rows from table1 and table2 using natural join keyword.
Ans) Select *
Output:
Que) Write a query to display the emp_ld, name and salary from Employee table whose dept_id
in Employee table is equal to dept_id in Department table using the equi join
ans) select emp_id, emp_name, emp_salary from Employee, Department where Employee.
dept_id= Department.dept_id
Output:
Que) Write a query to display all the rows from tables1 & table2 where table1 column column B
is equal to table2 column B using equi join.
Ans) select *
Output:-
Left Outer Join: It returns all the rows from the left table & matched rows from the right table.
Right Outer Join: It returns all the rows from the right talbe & matched rows from the left
table.
Full Outer Join: It returns all the rows(matched and unmatched) from the both the table.
Que) Waite a query to display all the rows from table1 and table2 using left outer join keyword.
Ans) select *
Output:-
Que) Write a quely to display all the rows from table1 and table2 using right outer join keyword.
Ans) select *
on table1.B=table 2.B
Output:-
Que) Write a query to display all the rows from table1 and table2 using full outer join keyword.
Ans) select *
on table1. B=table2.B
Output:
Cross Join: It returns cartesian product of the records from both the tables. It is also called as
cartesian join.
Que )Write a query to display all the rows from tablet and table 2 using cross join keyword.
Ans) Select *
Output:
Que ) Write a query to display all the rows from employee table and Department table whose
dept_id in Employee table is equal to dept_id in Department table by uing Inner join keyword.
Ans) select * from Employee inner join Department on Employee.dept_id = Department. dept-id
Output:
Que) Write a query to display all the rows from Employee table and Department table by uing
natural join keyword.
Output:
Que) Write a query to perform the left outer join on employee table and Department table.
Ans) select *
Output:-
Que) Write a query to perform the right outer join on Employee table & Department table.
Ans) select *
on Employee.dept_id = Department.dept_id
Output:
Que) Write a query to perform the full outer join on Employee table and Department table.
Ans) select *
Output:
NORMALIZATION
Normalization is the process of decomposing or splitting the tables to resolve the problems.
Problems like:-
1. Spurious Tuples
2. Anomalies
3. Data Redundancy
1. Spurious Tuples: Spurious Tuples are such tuples which are not present in original table but
gets generated. When table is decomposed and further joined.
2. Anomalies: The problems that occur in table while performing insertion, updation or deletion
operation.
3. Data Redundancy: The repetition of same data within the table which leads to memory
wastage is called data redundancy.
Dependencies
1. Functional Dependency
2. Partial Dependency
3. Transitive Dependency
(or)
If in a table, more than 1 determinants are present, then it will lead to partial dependency.
3. Transitive Dependency: When an indirect relation causes functional dependency then it
is called as transitive dependency.
Types of Normalization:
1. INF (First Normal Form)
Employee-Project
2NF (Second Normal Form)
A relation or table is said to be in 2NF when
Project
Employee
Project Employee
Project
Employee
Rating
Project Employee
BCNF-(Boyce-Codd Normal Form)
A relation or table is said to be in BCNF when
Project
Employee
Rating
Project _Employee
Create Project table:
Project
PName varchar2(80)
);
Rating
Create table Rating
Hourlycharges number
);
Employee
Rating varchar2(2),
Rating (Rating)
);
Creating Project _Employee Table:-
Project_Employee
PNo number,
ENo number,
);
CONSTRAINTS
Constraints are the rules or restrictions which are applied on the columns.
2. Not Null
3. Primary key
4. Foreign key
5. Check
6. Default
1. Unique :- It ensures that the column of a table will have unique values that is all values will
be different.
Example :-
id number Unique,
age number,
gender varchar2(6),
marks number,
Sem numbers);
2. Not Null :- It ensures that the column of a table will not have null values.
Example :-
age number,
gender varchar2(6),
marks number,
Sem number
);
3. Primary Key :- It is combination of unique and not null constraints.
• It ensures that column of a table cannot have duplicate values and also cannot have null
values.
• A table can have only one primary key column.
Example :-
age number,
gender varchar2(6),
marks number,
sem number
);
4. Foreign key:- It ensures that data present in a column of a table refers to the data of
primary Key column of parent table.
Example:-
Create table Student
age number,
gender varchar2(6),
marks number,
sem number,
did number,
);
);
5. Check-It ensures that the Column of a table will contain only such values which satisfy the
specified check condition.
Example:-
id number,
name varchar2(10),
gender varchar2(6),
marks number
);
6. Default:- It ensures that Column of a table will have a specified default value if no value is
given by the user.
Example:-
id number,
age number,
gender varchar2(6),
marks number,
);
Important Interview Questions:
1. What is Database?
2. What is DBMS?
3. What are Different Types in DBMS?
4. What is RDBMS? How is it different from DBMS?
5. What is SQL?
6. What is the difference between SQL and MySQL?
7. What are Tables and Fields?
8. What are Constraints in SQL?
9. What is a Primary Key?
10. What is a UNIQUE constraint?
11. What is a Foreign Key?
12. What is a Join? List its different types.
13. What is a Self-Join?
14. What is a Cross-Join?
15. What is an Index? Explain its different types.
16. What is the difference between Clustered and Non-clusteredindex?
17. What is Data Integrity?
18. What is a Query?
19. What is a Subquery? What are its types?
20. What is the SELECT statement?
21. What are some common clauses used with SELECT query in SQL?
22. What are UNION, MINUS and INTERSECT commands?
23. What is Cursor? How to use a Cursor?
24. What are Entities and Relationships?
25. List the different types of relationships in SQL.
26. What is an Alias in SQL?
27. What is a View?
28. What is Normalization?
29. What is Denormalization?
30. What are the various forms of Normalization?
31. What are the TRUNCATE, DELETE and DROP statements?
32. What is the difference between DROP and TRUNCATE statements?
33. What is the difference between DELETE and TRUNCATE
statements?
34. What are Aggregate and Scalar functions?
35. What is User-defined function? What are its various types?
36. What is OLTP?
37. What are the differences between OLTP and OLAP?
38. What is Collation? What are the different types of Collation
Sensitivity?
39. What is a Stored Procedure?
40. What is a Recursive Stored Procedure?
41. How to create empty tables with the same structure as anothertable?
42. What is Pattern Matching in SQL?
1. What is Database?
A database is an organized collection of data, stored and retrieved digitally from a remote or local computer system. Databas es can be vast and complex,
and such databases are developed using fixed design and modeling approaches.
2. What is DBMS?
DBMS stands for Database Management System. DBMS is a system software responsible for the creation, retrieval, updation, and management of the
database. It ensures that our data is consistent, organized, and is easily accessible by serving as an inte rface between the database and its end-users or
application software.
Distributed Database
Unlike a centralized database system, in distributed systems, data is distributed among different database systems of an organization. These database systems
are connected via communication links. Such links help the end-users to access the data easily. Examples of the Distributed database are Apache Cassandra,
HBase, Ignite, etc.
Relational Database
This database is based on the relational data model, which stores data in the form of rows(tuple) and columns(attributes), and together forms a table(relation).
A relational database uses SQL for storing, manipulating, as well as maintaining the data. E.F. Codd invented the database in 1970. Each table in the database
carries a key that makes the data unique from others. Examples of Relational databases are MySQL, Microsoft SQL Server, Oracle, etc.
NoSQL Database
Non-SQL/Not Only SQL is a type of database that is used for storing a wide range of data sets. It is not a relational database as it stores data not only in tabular
form but in several different ways. It came into existence when the demand for building modern applications increased. Thus, NoSQL presented a wide variety
of database technologies in response to the demands. We can further divide a NoSQL database into the following four types:
Cloud Database
A type of database where data is stored in a virtual environment and executes over the cloud computing platform. It provides users with various cloud
computing services (SaaS, PaaS, IaaS, etc.) for accessing the database. There are numerous cloud platforms, but the best options are:
o Amazon Web Services(AWS)
o Microsoft Azure
o Kamatera
o PhonixNAP
o ScienceSoft
o Google Cloud SQL, etc.
Object-oriented Databases
The type of database that uses the object-based data model approach for storing data in the database system. The data is represented and stored as objects
which are similar to the objects used in the object-oriented programming language.
Hierarchical Databases
It is the type of database that stores data in the form of parent-children relationship nodes.
Network Databases
It is the database that typically follows the network data model. Here, the representation of data is in the form of nodes connected via links between them.
Unlike the hierarchical database, it allows each record to have multiple children and parent nodes to form a generalized graph structure.
Personal Database
Collecting and storing data on the user's system defines a Personal Database. This database is basically designed for a single user.
5. What is SQL?
SQL stands for Structured Query Language. It is the standard language for relational database management systems. It is especially useful in handling
organized data comprised of entities (variables) and relations between different entities of the data.
• NOT NULL - Restricts NULL value from being inserted into a column.
• CHECK - Verifies that all values in a field satisfy a condition.
• DEFAULT - Automatically assigns a default value if no value has been specified for the field.
• UNIQUE - Ensures unique values to be inserted into the field.
• INDEX - Indexes a field providing faster retrieval of records.
• PRIMARY KEY - Uniquely identifies each record in a table.
• FOREIGN KEY - Ensures referential integrity for a record in another table.
CREATE TABLE Students ( /* Create table with multiple fields as primary key
*/
ID INT NOT NULL
LastName VARCHAR(255)
FirstName VARCHAR(255) NOT NULL,
CONSTRAINT PK_Student
PRIMARY KEY (ID, FirstName)
);
• (INNER) JOIN: Retrieves records that have matching values in both tables involved in the join. This is the widely used join for queries.
SELECT *
FROM Table_A
JOIN Table_B;
SELECT *
FROM Table_A
INNER JOIN Table_B;
• LEFT (OUTER) JOIN: Retrieves all the records/rows from the left and the matched records/rows from the right table.
SELECT *
FROM Table_A A
LEFT JOIN Table_B B
ON A.col = B.col;
• RIGHT (OUTER) JOIN: Retrieves all the records/rows from the right and the matched records/rows from the left table.
SELECT *
FROM Table_A A
RIGHT JOIN Table_B B
ON A.col = B.col;
• FULL (OUTER) JOIN: Retrieves all the records where there is a match in either the left or right table.
SELECT *
FROM Table_A A
FULL JOIN Table_B B
ON A.col = B.col;
There are different types of indexes that can be created for different purposes:
Unique indexes are indexes that help maintain data integrity by ensuring that no two rows of data in a table have identical key values. Once a unique
index has been defined for a table, uniqueness is enforced whenever keys are added or changed within the index.
Non-unique indexes, on the other hand, are not used to enforce constraints on the tables with which they are associated. Instead, non- unique indexes are
used solely to improve query performance by maintaining a sorted order of data values that are used frequently.
Clustered indexes are indexes whose order of the rows in the database corresponds to the order of the rows in the index. This is why only one clustered
index can exist in a given table, whereas, multiple non-clustered indexes can exist in the table.
The only difference between clustered and non-clustered indexes is that the database manager attempts to keep the data in the database in the same order
as the corresponding keys appear in the clustered index.
Clustering indexes can improve the performance of most query operations because they provide a linear-access path to data stored in the database.
• Clustered index modifies the way records are stored in a database based on the indexed column. A non-clustered index creates a separate entity within
the table which references the original table.
• Clustered index is used for easy and speedy retrieval of data from the database, whereas, fetching records from the non-clustered index is relatively
slower.
• In SQL, a table can have a single clustered index whereas it can have multiple non-clustered indexes.
• A correlated subquery cannot be considered as an independent query, but it can refer to the column in a table listed in the FROM of the main query.
• A non-correlated subquery can be considered as an independent query and the output of the subquery is substituted in the main query.
21. What are some common clauses used with SELECT query in SQL?
Some common SQL clauses used in conjuction with a SELECT query are as follows:
• WHERE clause in SQL is used to filter records that are necessary, based on specific conditions.
• ORDER BY clause in SQL is used to sort the records based on some field(s) in ascending (ASC) or descending order (DESC).
SELECT *
FROM myDB.students
WHERE graduation_year = 2019
ORDER BY studentID DESC;
• GROUP BY clause in SQL is used to group records with identical data and can be used in conjunction with some aggregation functions to produce
summarized results from the database.
• HAVING clause in SQL is used to filter records in combination with the GROUP BY clause. It is different from WHERE, since the WHERE
clause cannot filter aggregated records.
Certain conditions need to be met before executing either of the above statements in SQL -
• Each SELECT statement within the clause must have the same number of columns
• The columns must also have similar data types
• The columns in each SELECT statement should necessarily have the same order
1. DECLARE a cursor after any variable declaration. The cursor declaration must always be associated with a SELECT Statement.
2. Open cursor to initialize the result set. The OPEN statement must be called before fetching rows from the result set.
3. FETCH statement to retrieve and move to the next row in the result set.
4. Call the CLOSE statement to deactivate the cursor.
5. Finally use the DEALLOCATE statement to delete the cursor definition and release the associated resources.
Relationships: Relations or links between entities that have something to do with each other. For example - The employee's table in a company's
database can be associated with the salary table in the same database.
An alias is represented explicitly by the AS keyword but in some cases, the same can be performed without it as well. Nevertheless, using the AS
keyword is always a good practice.
SELECT A.emp_name AS "Employee" /* Alias using AS keyword */
B.emp_name AS "Supervisor"
FROM employee A, employee B /* Alias without AS keyword */
WHERE A.emp_sup = B.emp_id;
Students Table
Windsor Street777
Ansh Dracula (Bram Stoker) Mr.
As we can observe, the Books Issued field has more than one value per record, and to convert it into 1NF, this has to be resolved into separate individual
records for each book issued. Check the following table in 1NF form -
A relation is in second normal form if it satisfies the conditions for the first normal form and does not contain any partial dependency. A relation in 2NF
has no partial dependency, i.e., it has no non-prime attribute that depends on any proper subset of any candidate key of the table. Often, specifying a
single column Primary Key is the solution to the problem. Examples -
Example 1 - Consider the above example. As we can observe, the Students Table in the 1NF form has a candidate key in the form of [Student, Address]
that can uniquely identify all records in the table. The field Books Issued (non-prime attribute) depends partially on the Student field. Hence, the table is
not in 2NF. To convert it into the 2nd Normal Form, we will partition the tables into two while specifying a new Primary Key attribute to identify the
individual records in the Students table. The Foreign Key constraint will be set on the other table to ensure referential integrity.
Here, WX is the only candidate key and there is no partial dependency, i.e., any proper subset of WX doesn’t determine any non-prime attribute in the
relation.
A relation is said to be in the third normal form, if it satisfies the conditions for the second normal form and there is no transitive dependency between
the non-prime attributes, i.e., all non-prime attributes are determined only by the candidate keys of the relation and not by any other non-prime attribute.
Example 1 - Consider the Students Table in the above example. As we can observe, the Students Table in the 2NF form has a single candidate key
Student_ID (primary key) that can uniquely identify all records in the table. The field Salutation (non-prime attribute), however, depends on the Student
Field rather than the candidate key. Hence, the table is not in 3NF. To convert it into the 3rd Normal Form, we will once again partition the tables into
two while specifying a new Foreign Key constraint to identify the salutations for individual records in the Students table. The Primary Key constraint
for the same will be set on the Salutations table to identify each record uniquely.
Salutation_ID Salutation
1 Ms.
2 Mr.
3 Mrs.
For the above relation to exist in 3NF, all possible candidate keys in the above relation should be {P, RS, QR, T}.
A relation is in Boyce-Codd Normal Form if satisfies the conditions for third normal form and for every functional dependency, Left-Hand- Side is super
key. In other words, a relation in BCNF has non-trivial functional dependencies in form X –> Y, such that X is always a super key. For example - In the
above example, Student_ID serves as the sole unique identifier for the Students Table and Salutation_ID for the Salutations Table, thus these tables exist
in BCNF. The same cannot be said for the Books Table and there can be several books with common Book Names and the same Student_ID.
TRUNCATE command is used to delete all the rows from the table and free the space containing the table.
DROP command is used to remove an object from the database. If you drop a table, all the rows in the table are deleted and the table structure is
removed from the database.
Note: All aggregate functions described above ignore NULL values except for the COUNT function.
A scalar function returns a single value based on the input value. Following are the widely used SQL scalar functions:
• Scalar Function: As explained earlier, user-defined scalar functions return a single scalar value.
• Table-Valued Functions: User-defined table-valued functions return a table as output.
o Inline: returns a table data type based on a single SELECT statement.
o Multi-statement: returns a tabular result-set but, unlike inline, multiple SELECT statements can be used inside the function body.
OLAP stands for Online Analytical Processing, a class of software programs that are characterized by the relatively low frequency of online
transactions. Queries are often too complex and involve a bunch of aggregations. For OLAP systems, the effectiveness measure relies highly on response
time. Such systems are widely used for data mining or maintaining aggregated, historical data, usually in multi- dimensional schemas.
DELIMITER $$
CREATE PROCEDURE FetchAllStudents()
BEGIN
SELECT * FROM myDB.students;
END $$
DELIMITER ;
The % wildcard matches zero or more characters of any type and can be used to define wildcards both before and after the pattern. Search a student in
your database with first name beginning with the letter K:
SELECT *
FROM students
WHERE first_name LIKE 'K%'
Use the NOT keyword to select records that don't match the pattern. This query returns all students whose first name does not begin with K.
SELECT *
FROM students
WHERE first_name NOT LIKE 'K%'
Search for a student in the database where he/she has a K in his/her first name.
SELECT *
FROM students
WHERE first_name LIKE '%Q%'
The _ wildcard matches exactly one character of any type. It can be used in conjunction with % wildcard. This query fetches all students with letter K at the
third position in their first name.
SELECT *
FROM students
WHERE first_name LIKE ' K%'