SQL Interview Questions
SQL Interview Questions
SELECT *
FROM students
WHERE first_name LIKE 'K%'
● Omitting the patterns using the NOT keyword
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%'
● Matching a pattern anywhere using the % wildcard twice
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%'
● Using the _ wildcard to match pattern at a specific position
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%'
● Matching patterns for a specific length
The _ wildcard plays an important role as a limitation when it matches exactly one
character. It limits the length and position of the matched results. For example -
DELIMITER $$
CREATE PROCEDURE FetchAllStudents()
BEGIN
SELECT * FROM myDB.students;
END $$
DELIMITER ;
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.
7. What is OLTP?
OLTP stands for Online Transaction Processing, is a class of software applications
capable of supporting transaction-oriented programs. An essential attribute of an OLTP
system is its ability to maintain concurrency. To avoid single points of failure, OLTP
systems are often decentralized. These systems are usually designed for a large
number of users who conduct short transactions. Database queries are usually simple,
require sub-second response times, and return relatively few records. Here is an insight
into the working of an OLTP system [ Note - The figure is not important for interviews ] -
Real-Life Problems
Detailed reports
Attempt Now
8. What is User-defined function? What are its various types?
The user-defined functions in SQL are like functions in any other programming
language that accept parameters, perform complex calculations, and return a value.
They are written to use the logic repetitively whenever required. There are two types of
SQL user-defined functions:
● 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.
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".
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.
● (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;
17. What is a Foreign Key?
A FOREIGN KEY comprises of single or collection of fields in a table that essentially
refers to the PRIMARY KEY in another table. Foreign key constraint ensures referential
integrity in the relation between two tables.
The table with the foreign key constraint is labeled as the child table, and the table
containing the candidate key is labeled as the referenced or parent table.
CREATE TABLE Students ( /* Create table with foreign key - Way 1 */
ID INT NOT NULL
Name VARCHAR(255)
LibraryID INT
PRIMARY KEY (ID)
FOREIGN KEY (Library_ID) REFERENCES Library(LibraryID)
);
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)
);
● 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.
21. 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.
● 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.
SELECT COUNT(studentId), country
FROM myDB.students
WHERE country != "INDIA"
GROUP BY country
HAVING COUNT(studentID) > 5;
29. What are UNION, MINUS and INTERSECT commands?
The UNION operator combines and returns the result-set retrieved by two or more
SELECT statements.
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 Contacts;
SELECT name FROM Students /* Fetch the union of queries with duplicates*/
UNION ALL
SELECT name FROM Contacts;
SELECT name FROM Students /* Fetch names from students */
MINUS /* that aren't present in contacts */
SELECT name FROM Contacts;
SELECT name FROM Students /* Fetch names from students */
INTERSECT /* that are present in contacts as well */
SELECT name FROM Contacts;
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.
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.
A scalar function returns a single value based on the input value. Following are the
widely used SQL scalar functions:
TRUNCATE TABLE
table_1,
table_2,
table_3;
4. Define tokens in PostgreSQL?
A token in PostgreSQL is either a keyword, identifier, literal, constant, quotes identifier,
or any symbol that has a distinctive personality. They may or may not be separated
using a space, newline or a tab. If the tokens are keywords, they are usually commands
with useful meanings. Tokens are known as building blocks of any PostgreSQL code.
CREATE DATABASE
8. How will you change the datatype of a column?
This can be done by using the ALTER TABLE statement as shown below:
Syntax:
SELECT nextval('serial_num');
We can also use this sequence while inserting new records using the INSERT
command:
DROP DATABASE
14. What are ACID properties? Is PostgreSQL compliant with ACID?
ACID stands for Atomicity, Consistency, Isolation, Durability. They are database
transaction properties which are used for guaranteeing data validity in case of errors
and failures.
● 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:
19. 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.
'interviewbit' ~* '.*INTervIewBit.*'
22. How will you take backup of the database in PostgreSQL?
We can achieve this by using the pg_dump tool for dumping all object contents in the
database into a single file. The steps are as follows: