SQL Interview Questions CHEAT SHEET (2021) - InterviewBit
SQL Interview Questions CHEAT SHEET (2021) - InterviewBit
This guide will help you to brush up your SQL skills, regain your confidence and be job
ready!
In this guide you will find a collection of real world SQL interview questions asked in
companies like Google, Oracle, Amazon and Microsoft etc. Each question comes with a
perfectly written answer inline, saving your interview preparation time.
This guide also contains some sql practice problems which you can solve right away
which is simply the fastest and easiest way for clearing your basic concepts of SQL.
1. What is Database?
A database is an organized collection of data, stored and retrieved digitally from a remote or local
computer system. Databases 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 interface between the database and its end users
or application softwares.
4. 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.
A table in SQL is strictly restricted to have one and only one primary key, which is comprised of single
or multiple fields (columns).
CREATE TABLE Students ( /* Create table with a single field as primary key */
Name VARCHAR(255)
);
CREATE TABLE Students ( /* Create table with multiple fields as primary key */
LastName VARCHAR(255)
CONSTRAINT PK_Student
PRIMARY KEY (ID, FirstName)
);
Q => Write a SQL statement to add PRIMARY KEY 't_id' to the table 'teachers'. +
Q => Write a SQL statement to add primary key constraint 'pk_a' for table 'table_a' and fields
'col_b, col_c'. +
Name VARCHAR(255)
);
LastName VARCHAR(255)
);
The table with the foreign key constraint is labelled as the child table, and the table containing the
candidate key is labelled as the referenced or parent table.
CREATE TABLE Students ( /* Create table with foreign key - Way 1 */
Name VARCHAR(255)
LibraryID INT
);
Name VARCHAR(255)
);
Q => What type of integrity constraint does the foreign key ensure? +
Q => Write a SQL statement to add a FOREIGN KEY 'col_fk' in 'table_y' that references
'col_pk' in 'table_x'. +
(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
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
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
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
ON A.col = B.col;
Q => Write a SQL statement to CROSS JOIN 'table_1' with 'table_2' and fetch 'col_1' from
table_1 & 'col_2' from table_2 respectively. Do not use alias. +
Q => Write a SQL statement to perform SELF JOIN for 'Table_X' with alias 'Table_1' and
'Table_2', on columns 'Col_1' and 'Col_2' respectively. +
There are different types of indexes that can be created for different purposes:
Unique and Non-Unique Index:
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.
ON students (enroll_no);
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.
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 index can improve the performance of most query operations because they provide a linear-
access path to data stored in the database.
Q => Write a SQL statement to create a UNIQUE INDEX "my_index" on "my_table" for fields
"column_1" & "column_2". +
1. Clustered index modifies the way records are stored in a database based on the indexed column.
Non-clustered index creates a separate entity within the table which references the original table.
2. 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.
3. In SQL, a table can have a single clustered index whereas it can have multiple non-clustered
indexes.
FROM myDb.students
WHERE student_id = 1;
WHERE student_id = 1;
FROM myDb.contacts
WHERE roll_no IN (
SELECT roll_no
FROM myDb.students
A correlated subquery cannot be considered as an independent query, but it can refer 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 subquery
is substituted in the main query.
Q => Write a SQL query to update the field "status" in table "applications" from 0 to 1. +
Q => Write a SQL query to select the field "app_id" in table "applications" where "app_id"
less than 1000. +
Q => Write a SQL query to fetch the field "app_name" from "apps" where "apps.id" is equal
to the above collection of "app_id". +
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
GROUP BY clause in SQL is used to group records with identical data and can be used in
conjuction 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 WHERE clause cannot filter aggregated records.
FROM myDB.students
GROUP BY country
The MINUS operator in SQL is used to remove duplicates from the result-set obtained by the second
SELECT query from the result-set obtained by the first SELECT query and then return the filtered
results from the first.
The INTERSECT clause in SQL combines the result-set fetched by the two SELECT statements where
records from one match the other and then returns this intersection of result-sets.
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
SELECT name FROM Students /* Fetch the union of queries */
UNION
SELECT name FROM Students /* Fetch the union of queries with duplicates*/
UNION ALL
Q => Write a SQL query to fetch "names" that are present in either table "accounts" or in
table "registry". +
Q => Write a SQL query to fetch "names" that are present in "accounts" but not in table
"registry". +
Q => Write a SQL query to fetch "names" from table "contacts" that are neither present in
"accounts.name" nor in "registry.name". +
SELECT name
FROM myDB.students
FETCH next
FROM db_cursor
INTO @name
DEALLOCATE db_cursor
Relationships: Relations or links between entities that have something to do with each other. For
example - The employees table in a company's database can be associated with the salary table in the
same database.
24. List the different types of relationships in SQL.
One-to-One - This can be defined as the relationship between two tables where each record in one
table is associated with the maximum of one record in the other table.
One-to-Many & Many-to-One - This is the most commonly used relationship where a record in a
table is associated with multiple records in the other table.
Many-to-Many - This is used in cases when multiple instances on both sides are needed for
defining a relationship.
Self Referencing Relationships - This is used when a table needs to define a relationship with
itself.
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.
B.emp_name AS "Supervisor"
Q => Write an SQL statement to select all from table "Limited" with alias "Ltd". +
Students Table
Sara Mrs.
Avenue Woman 99 (Greer Macallister)
As we can observe, the Books Issued field has more than one values 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 -
Example 1 - Consider the above example. As we can observe, Students Table in 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 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.
Example 1 - Consider the Students Table in the above example. As we can observe, Students Table
in 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 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.
Q -> S
T -> P
For the above relation to exist in 3NF, all possible candidate keys in above relation should be {P, RS,
QR, T}.
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
is deleted and the table structure is removed from the database.
Q => Write a SQL query to remove first 1000 records from table 'Temporary' based on 'id'. +
Q => Write a SQL statement to delete the table 'Temporary' while keeping its relations intact.
+
The DELETE command deletes only the rows from the table based on the condition given in the where
clause or deletes all the rows from the table if no condition is specified. But it does not free the space
containing the table.
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.
Inline: returns a table data type based on a single SELECT statement.
Multi-statement: returns a tabular result-set but, unlike inline, multiple SELECT statements can be
used inside the function body.
BEGIN
SELECT * FROM myDB.students;
END $$
DELIMITER ;
) BEGIN
DECLARE score INT DEFAULT NULL; /* Set the default value => "score" */
SELECT awards FROM achievements /* Update "score" via SELECT query */
ELSE
END IF;
SELECT *
FROM students
SELECT *
FROM students
SELECT *
FROM students
SELECT *
FROM students
FROM students
FROM students
Conclusion
SQL is a language for the database. It has a vast scope and robust capability of creating and
manipulating variety of database objects using commands like CREATE, ALTER, DROP etc and also in
loading the database objects using commands like INSERT.
It also provides options for Data
Manipulation using commands like DELETE, TRUNCATE and also does effective retrieval of data using
cursor commands like FETCH, SELECT etc. There are many such commands which provide a large
amount of control to the programmer to interact with the database in an efficient way without wasting
much resources.
The popularity of SQL has grown so much that almost every programmer relies on
this to implement their application's storage functionalities thereby making it an exciting language to
learn. Learning this provides the developer a benefit of understanding the data structures used for
storing the organization's data and giving additional level of control and in-depth understanding of the
application.
Primary key defines a realtionship between two tables.
A table in SQL must have a primary key associated with it to uniquely identify its
records.
A table in SQL is indexed by default based on its primary key.
Primary key may or may not be unique but can be comprised of multiple fields.
Q - Which statement is false for a FOREIGN KEY constraint?
Foreign key defines a relationship between two tables.
Foreign Key is automatically created when two tables are joined.
Foreign Key uniquely identifies all the records in the referenced table.
Foreign key may or may not be unique but can be comprised of multiple fields.
Q - What is a Query?
A SELECT or UPDATE statement in SQL.
A request for data from a table in the database.
A request to input data from the user.
A request for data from single or multiple tables in the database.
Structured Question Language
Strong Query Language
Structured Query Language
Strong Question Language
MODIFY
UPDATE
ALTER TABLE
SAVE AS
SELECT * FROM people WHERE name = "%bar%";
SELECT * FROM people WHERE name LIKE "%bar%";
SELECT * FROM people WHERE name IN ("bar");
SELECT * FROM people WHERE name = "_bar_"
Q - Which statement is false for ORDER BY statement?
Requires a ASC or DESC keyword explicitly to sort the result set.
Sorts the result set in descending order using the DESC keyword.
Can sort based on multiple columns.
None of the above.
SELECT UNIQUE column_name FROM table_name;
SELECT DISTINCT column_name FROM table_name;
SELECT column_name FROM table_name WHERE COUNT(column_name) = 1;
SELECT UNIQUE column_name FROM table_name WHERE COUNT(column_name) = 1;
It is easier to create and manipulate.
It requires extra memory but allows for speedy retrieval of records.
It does not require additonal memory and allows for speedy retrieval of records.
None of the above.
Second Normal Formal
Third Normal Form
Boyce-Codd Normal Form
All of the above
Q - An SQL query to delete a table from the database and memory while keeping
the structure of the table intact?
DROP TABLE table_name;
DROP FROM TABLE table_name;
DELETE FROM TABLE table_name;
TRUNCATE TABLE table_name;
Q - Which of the following is known as a virtual table in SQL?
SELF JOIN
INNER JOIN
VIEW
NONE
Blog (https://www.interviewbit.com/blog/)
About Us (/pages/about_us/)
FAQ (/pages/faq/)
Contact Us (/pages/contact_us/)
Terms (/pages/terms/)
Privacy Policy (/pages/privacy/)
Like Us
(https://www.facebook.com/interviewbit)
Follow Us
(https://twitter.com/interview_bit)
Email
(mailto:[email protected])