66 SQL Interview Questions Last Updated On Dec 19, 2022
66 SQL Interview Questions Last Updated On Dec 19, 2022
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.
6. What are Tables and Fields?
A table is an organized collection of data stored in the form of rows and columns. Columns can
be categorized as vertical and rows as horizontal. The columns in a table are called fields while
the rows can be referred to as records.
7. What are Constraints in SQL?
Constraints are used to specify the rules concerning data in the table. It can be applied for single
or multiple fields in an SQL table during the creation of the table or after creating using the
ALTER TABLE command. The constraints are:
• 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.
8. What is a Primary Key?
The PRIMARY KEY constraint uniquely identifies each row in a table. It must contain UNIQUE
values and has an implicit NOT NULL constraint.
A table in SQL is strictly restricted to have one and only one primary key, which is comprised of
single or multiple fields (columns).
1 CREATE TABLE Students ( /* Create table with a single field as primary key /
2 ID INT NOT NULL
3 Name VARCHAR(255)
4 PRIMARY KEY (ID)
5 );
6
7 CREATE TABLE Students ( / Create table with multiple fields as primary key /
8 ID INT NOT NULL
9 LastName VARCHAR(255)
10 FirstName VARCHAR(255) NOT NULL,
11 CONSTRAINT PK_Student
12 PRIMARY KEY (ID, FirstName)
13 );
14
15 ALTER TABLE Students / Set a column as primary key /ADD PRIMARY KEY (ID);
16 ALTER TABLE Students / Set multiple columns as primary key */ADD CONSTRAINT PK
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.
1 CREATE TABLE Students ( /* Create table with a single field as unique /
2 ID INT NOT NULL UNIQUE
3 Name VARCHAR(255)
4 );
5
6 CREATE TABLE Students ( / Create table with multiple fields as unique /
7 ID INT NOT NULL
8 LastName VARCHAR(255)
9 FirstName VARCHAR(255) NOT NULLCONSTRAINT PK_Student
10 UNIQUE (ID, FirstName)
11 );
12
13 ALTER TABLE Students / Set a column as unique /ADD UNIQUE (ID);
14 ALTER TABLE Students / Set multiple columns as unique /ADD CONSTRAINT PK_Stude
• LEFT (OUTER) JOIN: Retrieves all the records/rows from the left and the matched
records/rows from the right table.
1 SELECT *FROM Table_A A
2 LEFT JOIN Table_B B
3 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.
1 SELECT *FROM Table_A A
2 RIGHT JOIN Table_B B
3 ON A.col = B.col;
• FULL (OUTER) JOIN: Retrieves all the records where there is a match in either the left or
right table.
1 SELECT *FROM Table_A A
2 FULL JOIN Table_B B
3 ON A.col = B.col;
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.
1 CREATE UNIQUE INDEX myIndex
2 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.
• Clustered and Non-Clustered Index:
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.
Write a SQL statement to create a UNIQUE INDEX "my_index" on "my_table" for
fields "column_1" & "column_2".
15. What is the difference between Clustered and Non-clustered index?
As explained above, the differences can be broken down into three small factors -
• 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.
16. What is Data Integrity?
Data Integrity is the assurance of accuracy and consistency of data over its entire life-cycle and is
a critical aspect of the design, implementation, and usage of any system which stores,
processes, or retrieves data. It also defines integrity constraints to enforce business rules on the
data when it is entered into an application or a database.
17. What is a Query?
A query is a request for data or information from a database table or combination of tables. A
database query can be either a select query or an action query.
1 SELECT fname, lname /* select query */FROM myDb.students
2 WHERE student_id = 1;
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).
1 SELECT *FROM myDB.students
2 WHERE graduation_year = 2019ORDER 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.
1 SELECT COUNT(studentId), country
2 FROM myDB.students
3 WHERE country != "INDIA"
4 GROUP BY country
5 HAVING COUNT(studentID) > 5;
1 SELECT name FROM Students /* Fetch the union of queries /UNIONSELECT name FROM
2 SELECT name FROM Students / Fetch the union of queries with duplicates*/UNION
1 SELECT name FROM Students /* Fetch names from students /INTERSECT / that ar
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".
22. What is Cursor? How to use a Cursor?
A database cursor is a control structure that allows for the traversal of records in a database.
Cursors, in addition, facilitates processing after traversal, such as retrieval, addition, and
deletion of database records. They can be viewed as a pointer to one row in a set of rows.
Working with SQL Cursor:
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.
1 DECLARE @name VARCHAR(50) /* Declare All Required Variables /DECLARE db_cursor
2 FROM myDB.students
3 WHERE parent_name IN ('Sara', 'Ansh')
4 OPEN db_cursor /* Open cursor and Fetch data into @name /
5 FETCH next
6 FROM db_cursor
7 INTO @nameCLOSE db_cursor / Close the cursor and deallocate the resources */DE
Write an SQL statement to select all from table "Limited" with alias "Ltd".
26. What is a View?
A view in SQL is a virtual table based on the result-set of an SQL statement. A view contains rows
and columns, just like a real table. The fields in a view are fields from one or more real tables in
the database.
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 -
Students Table (1st Normal Form)
• Second Normal 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.
Students Table (2nd Normal Form)
Books Table (2nd Normal Form)
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.
• Third Normal Form
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.
Students Table (3rd Normal Form)
For the above relation to exist in 3NF, all possible candidate keys in the above relation should be
{P, RS, QR, T}.
• Boyce-Codd Normal Form
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.
30. What are the TRUNCATE, DELETE and DROP statements?
DELETE statement is used to delete rows from a table.
1 DELETE FROM Candidates
2 WHERE CandidateId > 1000;
TRUNCATE command is used to delete all the rows from the table and free the space containing
the table.
1 TRUNCATE TABLE Candidates;
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.
1 DROP TABLE Candidates;
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.
1 SELECT * INTO Students_copy
2 FROM Students WHERE 1 = 2;
46. How can we start, restart and stop the PostgreSQL server?
• To start the PostgreSQL server, we run:
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:
1 TRUNCATE TABLE
2 table_1,
3 table_2,
4 table_3;
To get the next number 101 from the sequence, we use the nextval() method as shown below:
1 SELECT nextval('serial_num');
We can also use this sequence while inserting new records using the INSERT command:
1 INSERT INTO ib_table_name VALUES (nextval('serial_num'), 'interviewbit');
If the database has been deleted successfully, then the following message would be shown:
1 DROP DATABASE
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.
For more information, you can refer here.
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:
1 'interviewbit' ~* '.*INTervIewBit.*'
Step 2: Execute pg_dump program to take the dump of data to a .tar folder as shown below:
1 pg_dump -U postgres -W -F t sample_data > C:\Users\admin\pgbackup\sample_data.ta
The database dump will be stored in the sample_data.tar file on the location specified.
64. Does PostgreSQL support full text search?
Full-Text Search is the method of searching single or collection of documents stored on a
computer in a full-text based database. This is mostly supported in advanced database systems
like SOLR or ElasticSearch. However, the feature is present but is pretty basic in PostgreSQL.
65. What are parallel queries in PostgreSQL?
Parallel Queries support is a feature provided in PostgreSQL for devising query plans capable of
exploiting multiple CPU processors to execute the queries faster.
66. Differentiate between commit and checkpoint.
The commit action ensures that the data consistency of the transaction is maintained and it
ends the current transaction in the section. Commit adds a new record in the log that describes
the COMMIT to the memory. Whereas, a checkpoint is used for writing all changes that were
committed to disk up to SCN which would be kept in datafile headers and control files.
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.