SQL Interview Questions
SQL Interview Questions
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)
CREATE TABLE Students ( /* Create table with multiple fields as primary key */
ID INT NOT NULL
LastName VARCHAR(255)
CONSTRAINT PK_Student
PRIMARY KEY (ID, FirstName)
);
Name VARCHAR(255)
);
LastName VARCHAR(255)
CONSTRAINT PK_Student
UNIQUE (ID, FirstName)
);
Name VARCHAR(255)
LibraryID INT
Name VARCHAR(255)
LibraryID INT FOREIGN KEY (Library_ID) REFERENCES Library(LibraryID)
);
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;
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.
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;
21. 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;
22. What is Cursor? How to use a Cursor?
A database cursor is a control structure that allows for 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.
Students Table
Studen
Address Books Issued Salutation
t
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 -
Student_I
Book Issued
D
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.
Student_I Studen
Address Salutation_ID
D t
Student_I
Book Issued
D
Salutation_I
Salutation
D
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}.
A scalar function returns a single value based on the input value. Following are the widely
used SQL scalar functions:
LEN() - Calculates the total length of the given field (column).
UCASE() - Converts a collection of string values to uppercase characters.
LCASE() - Converts a collection of string values to lowercase characters.
MID() - Extracts substrings from a collection of string values in a table.
CONCAT() - Concatenates two or more strings.
RAND() - Generates a random collection of numbers of given length.
ROUND() - Calculates the round off integer value for a numeric field (or
decimal point values).
NOW() - Returns the current data & time.
FORMAT() - Sets the format to display a collection of values.
34. 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:
DECLARE score INT DEFAULT NULL; /* Set the default value => "score" */
SELECT awards FROM achievements /* Update "score" via SELECT query */
WHERE id = number INTO score;
IF score IS NULL THEN SET total = 0; /* Termination condition */
ELSE
CALL calctotal(number+1); /* Recursive call */
SET total = total + score; /* Action after recursion */
END IF;
END $$ /* End of procedure */
DELIMITER ; /* Reset the delimiter */