sql-interview-questions-1
sql-interview-questions-1
5. What is the In the end, multiple-choice questions are provided to test your understanding.
difference
between SQL
and MySQL?
7. What are
Constraints in
SQL?
8. What is a
Primary Key?
9. What is a
UNIQUE SQL Interview Questions
constraint?
1. What is Database?
10. What is a
A database is an organized collection of data, stored and retrieved digitally from a remote or local computer system.
Foreign Key?
Databases can be vast and complex, and such databases are developed using fixed design and modeling approaches.
11. What is a Join?
List its 2. What is DBMS?
different types. 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
12. What is a Self-
serving as an interface between the database and its end-users or application software.
Join?
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.
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)
);
write a sql statement to add primary key 't_id' to the table 'teachers'. +
Write a SQL statement to add primary key constraint 'pk_a' for table 'table_a' and fields 'col_b, col_c'. +
9. What is a UNIQUE constraint?
A UNIQUE constraint ensures that all values in a column are different. This provides uniqueness for the column(s) and
helps identify each row uniquely. Unlike primary key, there can be multiple unique constraints defined per table. The
code syntax for UNIQUE is quite similar to that of PRIMARY KEY and can be used interchangeably.
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
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;
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.
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 indexes can improve the performance of most query operations because they provide a linear-access path to
data stored in the database.
Write a SQL statement to create a UNIQUE INDEX "my_index" on "my_table" for fields "column_1" & "column_2". +
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.
Write a SQL query to update the field "status" in table "applications" from 0 to 1. +
Write a SQL query to select the field "app_id" in table "applications" where "app_id" less than 1000. +
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 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
Write a SQL query to fetch "names" that are present in either table "accounts" or in table "registry". +
Write a SQL query to fetch "names" that are present in "accounts" but not in table "registry". +
Write a SQL query to fetch "names" from table "contacts" that are neither present in "accounts.name" nor in
+
"registry.name".
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.
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.
Write an SQL statement to select all from table "Limited" with alias "Ltd". +
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 -
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.
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.
For the above relation to exist in 3NF, all possible candidate keys in the 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 are deleted
and the table structure is removed from the database.
Write a SQL query to remove first 1000 records from table 'Temporary' based on 'id'. +
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 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.
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:
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 '__K%'
Syntax:
CREATE DATABASE
46. How can we start, restart and stop the PostgreSQL server?
To start the PostgreSQL server, we run:
Starting PostgreSQL: ok
Range Partitioning: This method is done by partitioning based on a range of values. This method is most
commonly used upon date fields to get monthly, weekly or yearly data. In the case of corner cases like value
belonging to the end of the range, for example: if the range of partition 1 is 10-20 and the range of partition 2 is 20-
30, and the given value is 10, then 10 belongs to the second partition and not the first.
List Partitioning: This method is used to partition based on a list of known values. Most commonly used when we
have a key with a categorical value. For example, getting sales data based on regions divided as countries, cities, or
states.
Hash Partitioning: This method utilizes a hash function upon the partition key. This is done when there are no
specific requirements for data division and is used to access data individually. For example, you want to access data
based on a specific product, then using hash partition would result in the dataset that we require.
The type of partition key and the type of method used for partitioning determines how positive the performance and the
level of manageability of the partitioned table are.
We can also use the statement for removing data from multiple tables all at once by mentioning the table names
separated by comma as shown below:
TRUNCATE TABLE
table_1,
table_2,
table_3;
To get the next number 101 from the sequence, we use the nextval() method as shown below:
SELECT nextval('serial_num');
We can also use this sequence while inserting new records using the INSERT command:
If the database has been deleted successfully, then the following message would be shown:
DROP DATABASE
Atomicity: This property ensures that the transaction is completed in all-or-nothing way.
Consistency: This ensures that updates made to the database is valid and follows rules and restrictions.
Isolation: This property ensures integrity of transaction that are visible to all other transactions.
Durability: This property ensures that the committed transactions are stored permanently in the database.
PostgreSQL is compliant with ACID properties.
59. How do you check the rows affected as part of previous transactions?
SQL standards state that the following three phenomena should be prevented whilst concurrent transactions. SQL
standards define 4 levels of transaction isolations to deal with these phenomena.
Dirty reads: If a transaction reads data that is written due to concurrent uncommitted transaction, these reads are
called dirty reads.
Phantom reads: This occurs when two same queries when executed separately return different rows. For example,
if transaction A retrieves some set of rows matching search criteria. Assume another transaction B retrieves new
rows in addition to the rows obtained earlier for the same search criteria. The results are different.
Non-repeatable reads: This occurs when a transaction tries to read the same row multiple times and gets different
values each time due to concurrency. This happens when another transaction updates that data and our current
transaction fetches that updated data, resulting in different values.
To tackle these, there are 4 standard isolation levels defined by SQL standards. They are as follows:
Read Uncommitted – The lowest level of the isolations. Here, the transactions are not isolated and can read data
that are not committed by other transactions resulting in dirty reads.
Read Committed – This level ensures that the data read is committed at any instant of read time. Hence, dirty reads
are avoided here. This level makes use of read/write lock on the current rows which prevents
read/write/update/delete of that row when the current transaction is being operated on.
Repeatable Read – The most restrictive level of isolation. This holds read and write locks for all rows it operates
on. Due to this, non-repeatable reads are avoided as other transactions cannot read, write, update or delete the rows.
Serializable – The highest of all isolation levels. This guarantees that the execution is serializable where execution
of any concurrent operations are guaranteed to be appeared as executing serially.
The following table clearly explains which type of unwanted reads the levels avoid:
60. What can you tell about WAL (Write Ahead Logging)?
Write Ahead Logging is a feature that increases the database reliability by logging changes before any changes are done
to the database. This ensures that we have enough information when a database crash occurs by helping to pinpoint to
what point the work has been complete and gives a starting point from the point where it was discontinued.
61. What is the main disadvantage of deleting data from an existing table using the DROP
TABLE command?
DROP TABLE command deletes complete data from the table along with removing the complete table structure too. In
case our requirement entails just remove the data, then we would need to recreate the table to store data in it. In such
cases, it is advised to use the TRUNCATE command.
62. How do you perform case-insensitive searches using regular expressions in
PostgreSQL?
To perform case insensitive matches using a regular expression, we can use POSIX (~*) expression from pattern
matching operators. For example:
'interviewbit' ~* '.*INTervIewBit.*'
Step 2: Execute pg_dump program to take the dump of data to a .tar folder as shown below:
The database dump will be stored in the sample_data.tar file on the location specified.
Conclusion:
SQL is a language for the database. It has a vast scope and robust capability of creating and manipulating a 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 many 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
an additional level of control and in-depth understanding of the application.
PostgreSQL being an open-source database system having extremely robust and sophisticated ACID, Indexing, and
Transaction supports has found widespread popularity among the developer community.
PostgreSQL Download
PostgreSQL Tutorial
SQL Guide
SQL Vs MySQL
PostgreSQL vs MySQL
SQL Vs NoSQL
SQL IDE
SQL Projects
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.
3. 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 additional memory and allows for speedy retrieval of records.
10. Normalization which has neither composite values nor partial dependencies?
Second Normal Formal
11. 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
13. What is the name of the component that requests data to the PostgreSQL server?
Client
Thin Client
Workstation
Interface
UPDATE
ADD
APPEND
INSERT
15. What is the order of results shown by default if the ASC or DESC parameter is not specified with the ORDER BY
command?
16. Which command is used to tell PostgreSQL to make all changes made to the database permanent?
Submit
Execute
Apply
Commit
17. What is a pre-requisite for creating a database in PostgreSQL?To create a database in PostgreSQL, you must have
the special CREATEDB privilege or
Admin privilege
18. What command is used for restoring the backup of PostgreSQL which was created using pg_dump?
19. What allows us to define how various tables are related to each other formally in a database?
Views
Database manager
Only SQL