SQL Interview Questions CHEAT SHEET
SQL Interview Questions CHEAT SHEET
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.
5. What is the difference between SQL and MySQL?
SQL is a standard language for retrieving and manipulating structured databases. On the contrary, MySQL is a relational database
management system, like SQL Server, Oracle or IBM DB2, that is used to manage SQL databases.
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 a single field as primary key */
ID INT NOT NULL
Name VARCHAR(255)
PRIMARY KEY (ID)
);
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)
);
Q => Write a SQL statement to add primary key constraint 'pk_a' for table 'table_a' and fields 'col_b, col_c'. +
Q => What type of integrity constraint does the foreign key ensure? +
Q => Write a SQL statement to add a FOREIGN KEY 'col_fk' 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
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;
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:
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.
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" 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". +
20. 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 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.
SELECT COUNT(studentId), country
FROM myDB.students
WHERE country != "INDIA"
GROUP BY country
HAVING COUNT(studentID) > 5;
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 with duplicates*/
UNION ALL
SELECT name FROM Contacts;
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". +
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.
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.
Q => Write an SQL statement to select all from table "Limited" with alias "Ltd". +
Students Table
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 -
Sara Amanora Park Town 94 Until the Day I Die (Emily Carpenter) Ms.
Sara 24th Street Park Avenue Beautiful Bad (Annie Ward) Mrs.
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.
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. +
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.
OLAP stands for Online Analytical Processing, a class of software programs which are characterized by 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.
37. What is Collation? What are the different types of Collation Sensitivity?
Collation refers to a set of rules that determine how data is sorted and compared. Rules defining the correct character sequence
are used to sort the character data. It incorporates options for specifying case-sensitivity, accent marks, kana character types and
character width. Below are the different types of collation sensitivity:
Case sensitivity: A and a are treated differently.
Accent sensitivity: a and á are treated differently.
Kana sensitivity: Japanese kana characters Hiragana and Katakana are treated differently.
Width sensitivity: Same character represented in single-byte (half-width) and double-byte (full-width) are treated differently.
DELIMITER $$
CREATE PROCEDURE FetchAllStudents()
BEGIN
SELECT * FROM myDB.students;
END $$
DELIMITER ;
40. How to create empty tables with the same structure as another table?
Creating empty tables with the same structure can be done smartly by fetching the records of one table into a new table using the
INTO operator while fixing a WHERE clause to be false for all records. Hence, SQL prepares the new table with a duplicate
structure to accept the fetched records but since no records get fetched due to the WHERE clause in action, nothing is inserted
into the new table.
SELECT *
FROM students
WHERE first_name LIKE 'K%'
SELECT *
FROM students
WHERE first_name NOT LIKE 'K%'
SELECT *
FROM students
WHERE first_name LIKE '%Q%'
SELECT *
FROM students
WHERE first_name LIKE '__K%'
A table in SQL must have a primary key associated with it to uniquely identify its records.
Primary key may or may not be unique but can be comprised of multiple fields.
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?
MODIFY
UPDATE
ALTER TABLE
SAVE AS
Sorts the result set in descending order using the DESC keyword.
It does not require additonal memory and allows for speedy retrieval of records.
Q - An SQL query to delete a table from the database and memory while keeping the structure of the
table intact?
SELF JOIN
INNER JOIN
VIEW
NONE