0% found this document useful (0 votes)
287 views

SQL All

This summarizes the key points about self joins from the document: Self join allows a table to be joined with itself. It matches records within the same table based on a related column. For example, an employees table could be self joined to find employees and their supervisors by matching the employee ID to the supervisor ID field. A table alias is used to distinguish between the two instances of the table in the query. The self join uses an inner join clause to match records between the table instances.

Uploaded by

Apurva
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
287 views

SQL All

This summarizes the key points about self joins from the document: Self join allows a table to be joined with itself. It matches records within the same table based on a related column. For example, an employees table could be self joined to find employees and their supervisors by matching the employee ID to the supervisor ID field. A table alias is used to distinguish between the two instances of the table in the query. The self join uses an inner join clause to match records between the table instances.

Uploaded by

Apurva
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 122

Self Join and Its Demonstration

SELECT name, salary


FROM employee A
WHERE n-1 = (SELECT count(1)
FROM employee B Object 3

WHERE B.salary>A.salary)
Are you preparing for your SQL developer interview?
Then you have come to the right place.
This guide will help you to brush up on your SQL skills, regain your confidence
and be job-ready!
Here, you will find a collection of real-world 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.
It also covers practice problems to help you understand the basic concepts of
SQL.
We've divided this article into the following sections:
SQL Interview Questions
PostgreSQL Interview Questions
In the end, multiple-choice questions are provided to test your understanding.

Object 1

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 software.
3. What is RDBMS? How is it different from DBMS?
RDBMS stands for Relational Database Management System. The key
difference here, compared to DBMS, is that RDBMS stores data in the form of a
collection of tables, and relations can be defined between the common fields of
these tables. Most modern database management systems like MySQL,
Microsoft SQL Server, Oracle, IBM DB2, and Amazon Redshift are based on
RDBMS.

You can download a PDF version of Sql Interview Questions.

Download PDF.

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).
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)
);

ALTER TABLE Students /* Set a column as primary key */


ADD PRIMARY KEY (ID);
ALTER TABLE Students /* Set multiple columns as primary key */
ADD CONSTRAINT PK_Student /*Naming a Primary Key*/
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.
CREATE TABLE Students ( /* Create table with a single field as
unique */
ID INT NOT NULL UNIQUE
Name VARCHAR(255)
);

CREATE TABLE Students ( /* Create table with multiple fields as


unique */
ID INT NOT NULL
LastName VARCHAR(255)
FirstName VARCHAR(255) NOT NULL
CONSTRAINT PK_Student
UNIQUE (ID, FirstName)
);

ALTER TABLE Students /* Set a column as unique */


ADD UNIQUE (ID);
ALTER TABLE Students /* Set multiple columns as unique */
ADD CONSTRAINT PK_Student /* Naming a unique constraint */
UNIQUE (ID, FirstName);

10. 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 foreign key - Way 2


*/
ID INT NOT NULL PRIMARY KEY
Name VARCHAR(255)
LibraryID INT FOREIGN KEY (Library_ID) REFERENCES
Library(LibraryID)
);

ALTER TABLE Students /* Add a new foreign key */


ADD FOREIGN KEY (LibraryID)
REFERENCES Library (LibraryID);

What type of integrity constraint does the foreign key ensure?

Write a SQL statement to add a FOREIGN KEY 'col_fk' in 'table_y' that


references 'col_pk' in 'table_x'.

11. What is a Join? List its different types.


The SQL Join clause is used to combine records (rows) from two or more tables
in a SQL database based on a related column between the two.
There are four different types of JOINs in SQL:
• (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;

12. What is a Self-Join?


A self JOIN is a case of regular join where a table is joined to itself based on
some relation between its own column(s). Self-join uses the INNER JOIN or LEFT
JOIN clause and a table alias is used to assign different names to the table
within the query.
SELECT A.emp_id AS "Emp_ID",A.emp_name AS "Employee",
B.emp_id AS "Sup_ID",B.emp_name AS "Supervisor"
FROM employee A, employee B
WHERE A.emp_sup = B.emp_id;

13. What is a Cross-Join?


Cross join can be defined as a cartesian product of the two tables included in
the join. The table after join contains the same number of rows as in the cross-
product of the number of rows in the two tables. If a WHERE clause is used in
cross join then the query will work like an INNER JOIN.
SELECT stu.name, sub.subject
FROM students AS stu
CROSS JOIN subjects AS sub;

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.

14. What is an Index? Explain its different types.


A database index is a data structure that provides a quick lookup of data in a
column or columns of a table. It enhances the speed of operations accessing
data from a database table at the cost of additional writes and memory to
maintain the index data structure.
CREATE INDEX index_name /* Create Index */
ON table_name (column_1, column_2);
DROP INDEX index_name; /* Drop Index */

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.
CREATE UNIQUE INDEX myIndex
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.
SELECT fname, lname /* select query */
FROM myDb.students
WHERE student_id = 1;

UPDATE myDB.students /* action query */


SET fname = 'Captain', lname = 'America'
WHERE student_id = 1;

18. What is a Subquery? What are its types?


A subquery is a query within another query, also known as a nested
query or inner query. It is used to restrict or enhance the data to be queried
by the main query, thus restricting or enhancing the output of the main query
respectively. For example, here we fetch the contact information for students
who have enrolled for the maths subject:
SELECT name, email, mob, address
FROM myDb.contacts
WHERE roll_no IN (
SELECT roll_no
FROM myDb.students
WHERE subject = 'Maths');

There are two types of subquery - Correlated and Non-Correlated.


• 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".

19. What is the SELECT statement?


SELECT operator in SQL is used to select data from a database. The data
returned is stored in a result table, called the result-set.
SELECT * FROM myDB.students;

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.
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;

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.

DECLARE @name VARCHAR(50) /* Declare All Required Variables */


DECLARE db_cursor CURSOR FOR /* Declare Cursor Name*/
SELECT name
FROM myDB.students
WHERE parent_name IN ('Sara', 'Ansh')
OPEN db_cursor /* Open cursor and Fetch data into @name */
FETCH next
FROM db_cursor
INTO @name
CLOSE db_cursor /* Close the cursor and deallocate the resources
*/
DEALLOCATE db_cursor

23. What are Entities and Relationships?


Entity: An entity can be a real-world object, either tangible or intangible, that
can be easily identifiable. For example, in a college database, students,
professors, workers, departments, and projects can be referred to as entities.
Each entity has some associated properties that provide it an identity.
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.
25. What is an Alias in SQL?
An alias is a feature of SQL that is supported by most, if not all, RDBMSs. It is a
temporary name assigned to the table or table column for the purpose of a
particular SQL query. In addition, aliasing can be employed as an obfuscation
technique to secure the real names of database fields. A table alias is also
called a correlation name.
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.
SELECT A.emp_name AS "Employee" /* Alias using AS keyword */
B.emp_name AS "Supervisor"
FROM employee A, employee B /* Alias without AS keyword */
WHERE A.emp_sup = B.emp_id;

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.
27. What is Normalization?
Normalization represents the way of organizing structured data in the database
efficiently. It includes the creation of tables, establishing relationships between
them, and defining rules for those relationships. Inconsistency and redundancy
can be kept in check based on these rules, hence, adding flexibility to the
database.
28. What is Denormalization?
Denormalization is the inverse process of normalization, where the normalized
schema is converted into a schema that has redundant information. The
performance is improved by using redundancy and keeping the redundant data
consistent. The reason for performing denormalization is the overheads
produced in the query processor by an over-normalized structure.
29. What are the various forms of Normalization?
Normal Forms are used to eliminate or reduce redundancy in database tables.
The different forms are as follows:
• First Normal Form:
A relation is in first normal form if every attribute in that relation is a single-
valued attribute. If a relation contains a composite or multi-valued attribute,
it violates the first normal form. Let's consider the following students table.
Each student in the table, has a name, his/her address, and the books they
issued from the public library -
Students Table
Student Address Books Issued Salutation
Amanora Park Until the Day I Die (Emily Carpenter),
Sara Ms.
Town 94 Inception (Christopher Nolan)
62nd Sector A- The Alchemist (Paulo Coelho), Inferno
Ansh Mr.
10 (Dan Brown)
24th Street Park Beautiful Bad (Annie Ward), Woman
Sara Mrs.
Avenue 99 (Greer Macallister)
Windsor Street
Ansh Dracula (Bram Stoker) Mr.
777
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)
Student Address Books Issued Salutation
Amanora Park Town Until the Day I Die (Emily
Sara Ms.
94 Carpenter)
Amanora Park Town
Sara Inception (Christopher Nolan) Ms.
94
Ansh 62nd Sector A-10 The Alchemist (Paulo Coelho) Mr.
Ansh 62nd Sector A-10 Inferno (Dan Brown) Mr.
24th Street Park
Sara Beautiful Bad (Annie Ward) Mrs.
Avenue
24th Street Park
Sara Woman 99 (Greer Macallister) Mrs.
Avenue
Student Address Books Issued Salutation
Ansh Windsor Street 777 Dracula (Bram Stoker) Mr.
• 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)
Student_ID Student Address Salutation
1 Sara Amanora Park Town 94 Ms.
2 Ansh 62nd Sector A-10 Mr.
3 Sara 24th Street Park Avenue Mrs.
4 Ansh Windsor Street 777 Mr.
Books Table (2nd Normal Form)
Student_ID Book Issued
1 Until the Day I Die (Emily Carpenter)
1 Inception (Christopher Nolan)
2 The Alchemist (Paulo Coelho)
2 Inferno (Dan Brown)
3 Beautiful Bad (Annie Ward)
3 Woman 99 (Greer Macallister)
4 Dracula (Bram Stoker)
Example 2 - Consider the following dependencies in relation to R(W,X,Y,Z)
WX -> Y [W and X together determine Y]
XY -> Z [X and Y together determine Z]

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)
Student_ID Student Address Salutation_ID
1 Sara Amanora Park Town 94 1
2 Ansh 62nd Sector A-10 2
3 Sara 24th Street Park Avenue 3
4 Ansh Windsor Street 777 1
Books Table (3rd Normal Form)
Student_ID Book Issued
1 Until the Day I Die (Emily Carpenter)
1 Inception (Christopher Nolan)
2 The Alchemist (Paulo Coelho)
2 Inferno (Dan Brown)
3 Beautiful Bad (Annie Ward)
3 Woman 99 (Greer Macallister)
4 Dracula (Bram Stoker)
Salutations Table (3rd Normal Form)
Salutation_ID Salutation
1 Ms.
2 Mr.
3 Mrs.
Example 2 - Consider the following dependencies in relation to R(P,Q,R,S,T)
P -> QR [P together determine C]
RS -> T [B and C together determine D]
Q -> S
T -> P

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.
DELETE FROM Candidates
WHERE CandidateId > 1000;

TRUNCATE command is used to delete all the rows from the table and free the
space containing the table.
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.
DROP TABLE Candidates;

Write a SQL statement to wipe a table 'Temporary' from memory.

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.

31. What is the difference between DROP and TRUNCATE statements?


If a table is dropped, all things associated with the tables are dropped as well.
This includes - the relationships defined on the table with other tables, the
integrity checks and constraints, access privileges and other grants that the
table has. To create and use the table again in its original form, all these
relations, checks, constraints, privileges and relationships need to be redefined.
However, if a table is truncated, none of the above problems exist and the
table retains its original structure.
32. What is the difference between DELETE and TRUNCATE
statements?
The TRUNCATE command is used to delete all the rows from the table and free
the space containing the table.
The DELETE command deletes only the rows from the table based on the
condition given in the where clause or deletes all the rows from the table if no
condition is specified. But it does not free the space containing the table.
33. What are Aggregate and Scalar functions?
An aggregate function performs operations on a collection of values to return a
single scalar value. Aggregate functions are often used with the GROUP BY and
HAVING clauses of the SELECT statement. Following are the widely used SQL
aggregate functions:
• AVG() - Calculates the mean of a collection of values.
• COUNT() - Counts the total number of records in a specific table or view.
• MIN() - Calculates the minimum of a collection of values.
• MAX() - Calculates the maximum of a collection of values.
• SUM() - Calculates the sum of a collection of values.
• FIRST() - Fetches the first element in a collection of values.
• LAST() - Fetches the last element in a collection of values.
Note: All aggregate functions described above ignore NULL values except for
the COUNT function.
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 a given length.
• ROUND() - Calculates the round-off integer value for a numeric field (or
decimal point values).
• NOW() - Returns the current date & 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:
• 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.
35. 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 ] -
36. What are the differences between OLTP and OLAP?
OLTP stands for Online Transaction Processing, is a class of software
applications capable of supporting transaction-oriented programs. An important
attribute of an OLTP system is its ability to maintain concurrency. OLTP systems
often follow a decentralized architecture to avoid single points of failure. These
systems are generally designed for a large audience of end-users who conduct
short transactions. Queries involved in such databases are generally simple,
need fast response times, and return relatively few records. A number of
transactions per second acts as an effective measure for such systems.
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:
• 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.
38. What is a Stored Procedure?
A stored procedure is a subroutine available to applications that access a
relational database management system (RDBMS). Such procedures are stored
in the database data dictionary. The sole disadvantage of stored procedure is
that it can be executed nowhere except in the database and occupies more
memory in the database server. It also provides a sense of security and
functionality as users who can't access the data directly can be granted access
via stored procedures.
DELIMITER $$
CREATE PROCEDURE FetchAllStudents()
BEGIN
SELECT * FROM myDB.students;
END $$
DELIMITER ;

39. What is a Recursive Stored Procedure?


A stored procedure that calls itself until a boundary condition is reached, is
called a recursive stored procedure. This recursive function helps the
programmers to deploy the same set of code several times as and when
required. Some SQL programming languages limit the recursion depth to
prevent an infinite loop of procedure calls from causing a stack overflow, which
slows down the system and may lead to system crashes.
DELIMITER $$ /* Set a new delimiter => $$ */
CREATE PROCEDURE calctotal( /* Create the procedure */
IN number INT, /* Set Input and Ouput variables */
OUT total INT
) BEGIN
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 */

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 * INTO Students_copy
FROM Students WHERE 1 = 2;

41. What is Pattern Matching in SQL?


SQL pattern matching provides for pattern search in data if you have no clue as
to what that word should be. This kind of SQL query uses wildcards to match a
string pattern, rather than writing the exact word. The LIKE operator is used in
conjunction with SQL Wildcards to fetch the required information.
• Using the % wildcard to perform a simple search
The % wildcard matches zero or more characters of any type and can be used
to define wildcards both before and after the pattern. Search a student in your
database with first name beginning with the letter K:
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 -
SELECT * /* Matches first names with three or more letters */
FROM students
WHERE first_name LIKE '___%'

SELECT * /* Matches first names with exactly four characters */


FROM students
WHERE first_name LIKE '____'

PostgreSQL Interview Questions


42. What is PostgreSQL?
PostgreSQL was first called Postgres and was developed by a team led by
Computer Science Professor Michael Stonebraker in 1986. It was developed to
help developers build enterprise-level applications by upholding data integrity
by making systems fault-tolerant. PostgreSQL is therefore an enterprise-level,
flexible, robust, open-source, and object-relational DBMS that supports flexible
workloads along with handling concurrent users. It has been consistently
supported by the global developer community. Due to its fault-tolerant nature,
PostgreSQL has gained widespread popularity among developers.
43. How do you define Indexes in PostgreSQL?
Indexes are the inbuilt functions in PostgreSQL which are used by the queries to
perform search more efficiently on a table in the database. Consider that you
have a table with thousands of records and you have the below query that only
a few records can satisfy the condition, then it will take a lot of time to search
and return those rows that abide by this condition as the engine has to perform
the search operation on every single to check this condition. This is
undoubtedly inefficient for a system dealing with huge data. Now if this system
had an index on the column where we are applying search, it can use an
efficient method for identifying matching rows by walking through only a few
levels. This is called indexing.
Select * from some_table where table_col=120

44. How will you change the datatype of a column?


This can be done by using the ALTER TABLE statement as shown below:
Syntax:
ALTER TABLE tname
ALTER COLUMN col_name [SET DATA] TYPE new_data_type;

45. What is the command used for creating a database in PostgreSQL?


The first step of using PostgreSQL is to create a database. This is done by using
the createdb command as shown below: createdb db_name
After running the above command, if the database creation was successful,
then the below message is shown:
CREATE DATABASE

46. How can we start, restart and stop the PostgreSQL server?
• To start the PostgreSQL server, we run:

service postgresql start

• Once the server is successfully started, we get the below message:

Starting PostgreSQL: ok

• To restart the PostgreSQL server, we run:

service postgresql restart

Once the server is successfully restarted, we get the message:


Restarting PostgreSQL: server stopped
ok

• To stop the server, we run the command:

service postgresql stop

Once stopped successfully, we get the message:


Stopping PostgreSQL: server stopped
ok

47. What are partitioned tables called in PostgreSQL?


Partitioned tables are logical structures that are used for dividing large tables
into smaller structures that are called partitions. This approach is used for
effectively increasing the query performance while dealing with large database
tables. To create a partition, a key called partition key which is usually a table
column or an expression, and a partitioning method needs to be defined. There
are three types of inbuilt partitioning methods provided by Postgres:
• 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.
48. 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.
49. What is the importance of the TRUNCATE statement?
TRUNCATE TABLE name_of_table statement removes the data efficiently and
quickly from the table.
The truncate statement can also be used to reset values of the identity
columns along with data cleanup as shown below:
TRUNCATE TABLE name_of_table
RESTART IDENTITY;
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;

50. What is the capacity of a table in PostgreSQL?


The maximum size of PostgreSQL is 32TB.
51. Define sequence.
A sequence is a schema-bound, user-defined object which aids to generate a
sequence of integers. This is most commonly used to generate values to
identity columns in a table. We can create a sequence by using the CREATE
SEQUENCE statement as shown below:
CREATE SEQUENCE serial_num START 100;

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:
INSERT INTO ib_table_name VALUES (nextval('serial_num'),
'interviewbit');

52. What are string constants in PostgreSQL?


They are character sequences bound within single quotes. These are using
during data insertion or updation to characters in the database.
There are special string constants that are quoted in dollars.
Syntax: $tag$<string_constant>$tag$ The tag in the constant is optional and
when we are not specifying the tag, the constant is called a double-dollar string
literal.
53. How can you get a list of all databases in PostgreSQL?
This can be done by using the command \l -> backslash followed by the lower-
case letter L.
54. How can you delete a database in PostgreSQL?
This can be done by using the DROP DATABASE command as shown in the
syntax below:
DROP DATABASE database_name;

If the database has been deleted successfully, then the following message
would be shown:
DROP DATABASE

55. 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.
• 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.
56. Can you explain the architecture of PostgreSQL?
• The architecture of PostgreSQL follows the client-server model.
• The server side comprises of background process manager, query processer,
utilities and shared memory space which work together to build PostgreSQL’s
instance that has access to the data. The client application does the task of
connecting to this instance and requests data processing to the services. The
client can either be GUI (Graphical User Interface) or a web application. The
most commonly used client for PostgreSQL is pgAdmin.
57. What do you understand by multi-version concurrency control?
MVCC or Multi-version concurrency control is used for avoiding unnecessary
database locks when 2 or more requests tries to access or modify the data at
the same time. This ensures that the time lag for a user to log in to the
database is avoided. The transactions are recorded when anyone tries to
access the content.
For more information regarding this, you can refer here.
58. What do you understand by command enable-debug?
The command enable-debug is used for enabling the compilation of all libraries
and applications. When this is enabled, the system processes get hindered and
generally also increases the size of the binary file. Hence, it is not
recommended to switch this on in the production environment. This is most
commonly used by developers to debug the bugs in their scripts and help them
spot the issues. For more information regarding how to debug, you can
refer here.
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:
Isolation levels Dirty Reads Phantom Reads Non-repeatable reads
Read Uncommitted Might occur Might occur Might occur
Read Committed Won’t occur Might occur Might occur
Repeatable Read Won’t occur Might occur Won’t occur
Serializable Won’t occur Won’t occur Won’t occur
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:
'interviewbit' ~* '.*INTervIewBit.*'

63. 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:
Step 1: Navigate to the bin folder of the PostgreSQL installation path.
C:\>cd C:\Program Files\PostgreSQL\10.0\bin

Step 2: Execute pg_dump program to take the dump of data to a .tar folder as
shown below:
pg_dump -U postgres -W -F t sample_data >
C:\Users\admin\pgbackup\sample_data.tar

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.
Top 65 SQL Interview Questions You Must Prepare In 2022
Last updated on Nov 23,2021958.1K Views

Aayushi Johari A technophile who likes writing about different technologies and spreading
knowledge.

• 6 Comments

• Bookmark

1 / 3 Blog from SQL Interview Questions

RDBMS is one of the most commonly used databases to date, and


therefore SQL skills are indispensable in most of the job roles. In this SQL
Interview Questions article, I will introduce you to the most frequently asked
questions on SQL (Structured Query Language). This article is the perfect guide
for you to learn all the concepts related to SQL, Oracle, MS SQL Server, and
MySQL database. Our Top 65 SQL Interview Questions article is the one-stop
resource from where you can boost your interview preparation.

Want to Upskill yourself to get ahead in your career? Check out the Top
Trending Technologies.
Let’s get started!

SQL Interview Questions


1. What is the difference between SQL and MySQL?
2. What are the different subsets of SQL?
3. What do you mean by DBMS? What are its different types?
4. What do you mean by table and field in SQL?
5. What are joins in SQL?
6. What is the difference between CHAR and VARCHAR2 datatype in SQL?
7. What is the Primary key?
8. What are Constraints?
9. What is the difference between DELETE and TRUNCATE statements?
10.What is a Unique key?
Q1. What is the difference between SQL and MySQL?
SQL vs MySQL

SQL MySQL
SQL is a standard language which stands for
Structured Query Language based on the English MySQL is a database management system.
language
MySQL is an RDMS (Relational Database
SQL is the core of the relational database which
Management System) such as SQL Server,
is used for accessing and managing database
Informix etc.
Q2. What are the different subsets of SQL?
• Data Definition Language (DDL) – It allows you to perform various
operations on the database such as CREATE, ALTER, and DELETE objects.
• Data Manipulation Language(DML) – It allows you to access and
manipulate data. It helps you to insert, update, delete and retrieve data
from the database.
• Data Control Language(DCL) – It allows you to control access to the
database. Example – Grant, Revoke access permissions.
Q3. What do you mean by DBMS? What are its different types?
A Database Management System (DBMS)
is a software application that interacts with
the user, applications, and the database itself
to capture and analyze data. A database is a
structured collection of data.
A DBMS allows a user to interact with the database. The data stored in the
database can be modified, retrieved and deleted and can be of any type like
strings, numbers, images, etc.

There are two types of DBMS:

• Relational Database Management System: The data is stored in relations


(tables). Example – MySQL.
• Non-Relational Database Management System: There is no concept of
relations, tuples and attributes. Example – MongoDB
Q4. What do you mean by table and field in SQL?
A table refers to a collection of data in an organised manner in form of rows
and columns. A field refers to the number of columns in a table. For example:

Table: StudentInformation
Field: Stu Id, Stu Name, Stu Marks

Q5. What are joins in SQL?


A JOIN clause is used to combine rows from two or more tables, based on a
related column between them. It is used to merge two tables or retrieve data
from there. There are 4 types of joins, as you can refer to below:
• Inner join: Inner Join in SQL is the most common type of join. It is used
to return all the rows from multiple tables where the join condition is
satisfied.
• Left Join: Left Join in SQL is used to return all the rows from the left

table but only the matching rows from the right table where the join
condition is fulfilled.

• Right Join: Right Join in SQL is used to return all the rows from the right

table but only the matching rows from the left table where the join
condition is fulfilled.
• Full Join: Full join returns all the records when there is a match in any of

the tables. Therefore, it returns all the rows from the left-hand side table
and all the rows from the right-hand side table.

Q6. What is the difference between CHAR and VARCHAR2 datatype in


SQL?
Both Char and Varchar2 are used for characters datatype but varchar2 is used
for character strings of variable length whereas Char is used for strings of fixed
length. For example, char(10) can only store 10 characters and will not be able
to store a string of any other length whereas varchar2(10) can store any length
i.e 6,8,2 in this variable.

Q7. What is a Primary key?


• A Primary key in SQL is a column (or collection of
columns) or a set of columns that uniquely
identifies each row in the table.
• Uniquely identifies a single row in the table

• Null values not allowed

Example- In the Student table, Stu_ID is the primary key.

Q8. What are Constraints?


Constraints in SQL are used to specify the limit on the data type of the table. It
can be specified while creating or altering the table statement. The sample of
constraints are:

• NOT NULL

• CHECK

• DEFAULT

• UNIQUE

• PRIMARY KEY

• FOREIGN KEY

Q9. What is the difference between DELETE and TRUNCATE


statements?
DELETE vs TRUNCATE
DELETE TRUNCATE
Delete command is used to delete a row in a Truncate is used to delete all the rows from a
table. table.
You can rollback data after using delete
You cannot rollback data.
statement.
It is a DML command. It is a DDL command.
It is slower than truncate statement. It is faster.
Q10. What is a Unique key?
• Uniquely identifies a single row in the table.

• Multiple values allowed per table.

• Null values allowed.

Apart from this SQL Interview Questions blog, if you want to get trained from
professionals on this technology, you can opt for structured training from
edureka!

Q11. What is a Foreign key in SQL?


• Foreign key maintains referential integrity by enforcing a link between
the data in two tables.
• The foreign key in the child table references the primary key in the parent
table.
• The foreign key constraint prevents actions that would destroy links
between the child and parent tables.
Q12. What do you mean by data integrity?
Data Integrity defines the accuracy as well as the consistency of the data
stored in a database. It also defines integrity constraints to enforce business
rules on the data when it is entered into an application or a database.

Q13. What is the difference between clustered and non-clustered


index in SQL?
The differences between the clustered and non clustered index in SQL are :

1. Clustered index is used for easy retrieval of data from the database and
its faster whereas reading from non clustered index is relatively slower.
2. Clustered index alters the way records are stored in a database as it sorts
out rows by the column which is set to be clustered index whereas in a
non clustered index, it does not alter the way it was stored but it creates
a separate object within a table which points back to the original table
rows after searching.
3. One table can only have one clustered index whereas it can have many
non clustered index.

Q14. Write a SQL query to display the current date?


In SQL, there is a built-in function called GetDate() which helps to return the
current timestamp/date.

Q15.What do you understand by query optimization?


The phase that identifies a plan for evaluation query which has the least
estimated cost is known as query optimization.

The advantages of query optimization are as follows:

• The output is provided faster

• A larger number of queries can be executed in less time

• Reduces time and space complexity

SQL Interview Questions


Q16. What do you mean by Denormalization?
Denormalization refers to a technique which is used to access data from higher
to lower forms of a database. It helps the database managers to increase the
performance of the entire infrastructure as it introduces redundancy into a
table. It adds the redundant data into a table by incorporating database queries
that combine data from various tables into a single table.

Q17. What are Entities and Relationships?


Entities: A person, place, or thing in the real world about which data can be
stored in a database. Tables store data that represents one type of entity. For
example – A bank database has a customer table to store customer
information. The customer table stores this information as a set of attributes
(columns within the table) for each customer.

Relationships: Relation or links between entities that have something to do


with each other. For example – The customer name is related to the customer
account number and contact information, which might be in the same table.
There can also be relationships between separate tables (for example,
customer to accounts).

Q18. What is an Index?


An index refers to a performance tuning method of allowing faster retrieval of
records from the table. An index creates an entry for each value and hence it
will be faster to retrieve data.

Q19. Explain different types of index in SQL.


There are three types of index in SQL namely:

Unique Index:
This index does not allow the field to have duplicate values if the column is
unique indexed. If a primary key is defined, a unique index can be applied
automatically.

Clustered Index:
This index reorders the physical order of the table and searches based on the
basis of key values. Each table can only have one clustered index.

Non-Clustered Index:
Non-Clustered Index does not alter the physical order of the table and
maintains a logical order of the data. Each table can have many nonclustered
indexes.

Q20. What is Normalization and what are the advantages of it?


Normalization in SQL is the process of organizing data to avoid duplication and
redundancy. Some of the advantages are:

• Better Database organization

• More Tables with smaller rows

• Efficient data access

• Greater Flexibility for Queries

• Quickly find the information

• Easier to implement Security


• Allows easy modification

• Reduction of redundant and duplicate data

• More Compact Database

• Ensure Consistent data after modification

Apart from this SQL Interview Questions Blog, if you want to get trained from
professionals on this technology, you can opt for structured training from
edureka!

Q21. What is the difference between DROP and TRUNCATE commands?


DROP command removes a table and it cannot be rolled back from the
database whereas TRUNCATE command removes all the rows from the table.

SQL Essentials Training & Certification


• Course Duration
• Real-life Case Studies
• Assignments
• Lifetime Access
Q22. Explain different types of Normalization.
There are many successive levels of normalization. These are called normal
forms. Each consecutive normal form depends on the previous one.The first
three normal forms are usually adequate.

• First Normal Form (1NF) – No repeating groups within rows

• Second Normal Form (2NF) – Every non-key (supporting) column value is


dependent on the whole primary key.
• Third Normal Form (3NF) – Dependent solely on the primary key and no
other non-key (supporting) column value.
Q23. What is the ACID property in a database?
ACID stands for Atomicity, Consistency, Isolation, Durability. It is used to ensure
that the data transactions are processed reliably in a database system.

• Atomicity: Atomicity refers to the transactions that are completely done


or failed where transaction refers to a single logical operation of a data. It
means if one part of any transaction fails, the entire transaction fails and
the database state is left unchanged.
• Consistency: Consistency ensures that the data must meet all the
validation rules. In simple words, you can say that your transaction never
leaves the database without completing its state.
• Isolation: The main goal of isolation is concurrency control.

• Durability: Durability means that if a transaction has been committed, it


will occur whatever may come in between such as power loss, crash or
any sort of error.
Q24. What do you mean by “Trigger” in SQL?
Trigger in SQL is are a special type of stored procedures that are defined to
execute automatically in place or after data modifications. It allows you to
execute a batch of code when an insert, update or any other query is executed
against a specific table.

Q25. What are the different operators available in SQL?


There are three operators available in SQL, namely:

1. Arithmetic Operators
2. Logical Operators
3. Comparison Operators
Apart from this SQL Interview Questions blog, if you want to get trained from
professionals on this technology, you can opt for structured training from
edureka!

Q26. Are NULL values same as that of zero or a blank space?


A NULL value is not at all same as that of zero or a blank space. NULL value
represents a value which is unavailable, unknown, assigned or not applicable
whereas a zero is a number and blank space is a character.
Q27. What is the difference between cross join and natural join?
The cross join produces the cross product or Cartesian product of two tables
whereas the natural join is based on all the columns having the same name
and data types in both the tables.

Q28. What is subquery in SQL?


A subquery is a query inside another query where a query is defined to retrieve
data or information back from the database. In a subquery, the outer query is
called as the main query whereas the inner query is called subquery.
Subqueries are always executed first and the result of the subquery is passed
on to the main query. It can be nested inside a SELECT, UPDATE or any other
query. A subquery can also use any comparison operators such as >,< or =.

Q29. What are the different types of a subquery?


There are two types of subquery namely, Correlated and Non-Correlated.

Correlated subquery: These are queries which select the data from a table
referenced in the outer query. It is not considered as an independent query as it
refers to another table and refers the column in a table.

Non-Correlated subquery: This query is an independent query where the


output of subquery is substituted in the main query.

SQL Interview Questions


Q30. List the ways to get the count of records in a table?
To count the number of records in a table in SQL, you can use the below
commands:

SELECT * FROM table1

SELECT COUNT(*) FROM table1

SELECT rows FROM sysindexes WHERE id = OBJECT_ID(table1) AND indid < 2


Apart from this SQL Interview Questions Blog, if you want to get trained from
professionals on this technology, you can opt for structured training from
edureka!

Q31. Write a SQL query to find the names of employees that begin
with ‘A’?
To display name of the employees that begin with ‘A’, type in the below
command:

1SELECT * FROM Table_name WHERE EmpName like 'A%'


Q32. Write a SQL query to get the third-highest salary of an employee from
employee_table?
1SELECT TOP 1 salary
2FROM(
3SELECT TOP 3 salary
4FROM employee_table
5ORDER BY salary DESC) AS emp
6ORDER BY salary ASC;
Q33. What is the need for group functions in SQL?
Group functions work on the set of rows and return one result per group. Some
of the commonly used group functions are: AVG, COUNT, MAX, MIN, SUM,
VARIANCE.

Q34 . What is a Relationship and what are they?


Relation or links are between entities that have something to do with each
other. Relationships are defined as the connection between the tables in a
database. There are various relationships, namely:

• One to One Relationship.

• One to Many Relationship.

• Many to One Relationship.

• Self-Referencing Relationship.

Q35. How can you insert NULL values in a column while inserting the
data?
NULL values in SQL can be inserted in the following ways:

• Implicitly by omitting column from column list.

• Explicitly by specifying NULL keyword in the VALUES clause


Q36. What is the main difference between ‘BETWEEN’ and ‘IN’
condition operators?
BETWEEN operator is used to display rows based on a range of values in a row
whereas the IN condition operator is used to check for values contained in a
specific set of values.

Example of BETWEEN:
SELECT * FROM Students where ROLL_NO BETWEEN 10 AND 50;
Example of IN:
SELECT * FROM students where ROLL_NO IN (8,15,25);

Q37. Why are SQL functions used?


SQL functions are used for the following purposes:

• To perform some calculations on the data

• To modify individual data items

• To manipulate the output

• To format dates and numbers

• To convert the data types

Q38. What is the need for MERGE statement?


This statement allows conditional update or insertion of data into a table. It
performs an UPDATE if a row exists, or an INSERT if the row does not exist.

Q39. What do you mean by recursive stored procedure?


Recursive stored procedure refers to a stored procedure which calls by itself
until it reaches some boundary condition. This recursive function or procedure
helps the programmers to use the same set of code n number of times.

Q40. What is CLAUSE in SQL?


SQL clause helps to limit the result set by providing a condition to the query. A
clause helps to filter the rows from the entire set of records.

For example – WHERE, HAVING clause.


Apart from this SQL Interview Questions Blog, if you want to get trained from
professionals on this technology, you can opt for a structured training from
edureka! Click below to know more.

Q41. What is the difference between ‘HAVING’ CLAUSE and a ‘WHERE’


CLAUSE?
HAVING clause can be used only with SELECT statement. It is usually used in a
GROUP BY clause and whenever GROUP BY is not used, HAVING behaves like a
WHERE clause.
Having Clause is only used with the GROUP BY function in a query whereas
WHERE Clause is applied to each row before they are a part of the GROUP BY
function in a query.

Q42. List the ways in which Dynamic SQL can be executed?


Following are the ways in which dynamic SQL can be executed:

• Write a query with parameters.

• Using EXEC.

• Using sp_executesql.

Q43. What are the various levels of constraints?


Constraints are the representation of a column to enforce data entity and
consistency. There are two levels of a constraint, namely:

• column level constraint

• table level constraint

Q44. How can you fetch common records from two tables?
You can fetch common records from two tables using INTERSECT. For example:

Databases Training

SQL ESSENTIALS TRAINING & CERTIFICATION


SQL Essentials Training & Certification
Reviews

5(8565)
MYSQL DBA CERTIFICATION TRAINING
MySQL DBA Certification Training
Reviews

5(5182)

MONGODB CERTIFICATION TRAINING COURSE


MongoDB Certification Training Course
Reviews

4(15708)

APACHE CASSANDRA CERTIFICATION TRAINING


Apache Cassandra Certification Training
Reviews

5(12541)

TERADATA CERTIFICATION TRAINING


Teradata Certification Training
Reviews

5(2665)

MASTERING NEO4J GRAPH DATABASE CERTIFICATION TRAINING


Mastering Neo4j Graph Database Certification Training
Reviews

5(901)

1 Select studentID from student. <strong>INTERSECT </strong> Select StudentID from Exam
Q45. List some case manipulation functions in SQL?
There are three case manipulation functions in SQL, namely:

• LOWER: This function returns the string in lowercase. It takes a string as


an argument and returns it by converting it into lower case. Syntax:
LOWER(‘string’)
• UPPER: This function returns the string in uppercase. It takes a string as
an argument and returns it by converting it into uppercase. Syntax:
UPPER(‘string’)
• INITCAP: This function returns the string with the first letter in uppercase
and rest of the letters in lowercase. Syntax:
INITCAP(‘string’)

Apart from this SQL Interview Questions blog, if you want to get trained from
professionals on this technology, you can opt for a structured training from
edureka! Click below to know more.

Q46. What are the different set operators available in SQL?

Some of the available set operators are – Union, Intersect or Minus operators.

Q47. What is an ALIAS command?


ALIAS command in SQL is the name that can be given to any table or a column.
This alias name can be referred in WHERE clause to identify a particular table
or a column.

For example-

Select emp.empID, dept.Result from employee emp, department as dept where


emp.empID=dept.empID
In the above example, emp refers to alias name for employee table and dept
refers to alias name for department table.

Q48. What are aggregate and scalar functions?


Aggregate functions are used to evaluate mathematical calculation and returns
a single value. These calculations are done from the columns in a table. For
example- max(),count() are calculated with respect to numeric.

Scalar functions return a single value based on the input value. For example –
UCASE(), NOW() are calculated with respect to string.

Q49. How can you fetch alternate records from a table?


You can fetch alternate records i.e both odd and even row numbers. For
example- To display even numbers, use the following command:
Select studentId from (Select rowno, studentId from student) where
mod(rowno,2)=0

Now, to display odd numbers:

Select studentId from (Select rowno, studentId from student) where


mod(rowno,2)=1
Q50. Name the operator which is used in the query for pattern
matching?
LIKE operator is used for pattern matching, and it can be used as -.

1. % – It matches zero or more characters.


For example- select * from students where studentname like ‘a%’

_ (Underscore) – it matches exactly one character.


For example- select * from student where studentname like ‘abc_’

Apart from this SQL Interview Questions Blog, if you want to get trained from
professionals on this technology, you can opt for structured training from
edureka!

Q51. How can you select unique records from a table?


You can select unique records from a table by using the DISTINCT keyword.

Select DISTINCT studentID from Student


Using this command, it will print unique student id from the table Student.

Q52. How can you fetch first 5 characters of the string?


There are a lot of ways to fetch characters from a string. For example:

Select SUBSTRING(StudentName,1,5) as studentname from student

Q53. What is the main difference between SQL and PL/SQL?


SQL is a query language that allows you to issue a single query or execute a
single insert/update/delete whereas PL/SQL is Oracle’s “Procedural Language”
SQL, which allows you to write a full program (loops, variables, etc.) to
accomplish multiple operations such as selects/inserts/updates/deletes.
Q54. What is a View?
A view is a virtual table which consists of a subset of data contained in a table.
Since views are not present, it takes less space to store. View can have data of
one or more tables combined and it depends on the relationship.

Q55. What are Views used for?


A view refers to a logical snapshot based on a table or another view. It is used
for the following reasons:

• Restricting access to data.

• Making complex queries simple.

• Ensuring data independence.

• Providing different views of same data.

Q56. What is a Stored Procedure?


A Stored Procedure is a function which consists of many SQL statements to
access the database system. Several SQL statements are consolidated into a
stored procedure and execute them whenever and wherever required which
saves time and avoid writing code again and again.

Q57. List some advantages and disadvantages of Stored Procedure?


Advantages:
A Stored Procedure can be used as a modular programming which means
create once, store and call for several times whenever it is required. This
supports faster execution. It also reduces network traffic and provides better
security to the data.

Disadvantage:
The only disadvantage of Stored Procedure is that it can be executed only in
the database and utilizes more memory in the database server.

Q58. List all the types of user-defined functions?


There are three types of user-defined functions, namely:

• Scalar Functions
• Inline Table-valued functions

• Multi-statement valued functions

Scalar returns the unit, variant defined the return clause. Other two types of
defined functions return table.

Q59. What do you mean by Collation?


Collation is defined as a set of rules that determine how data can be sorted as
well as compared. Character data is sorted using the rules that define the
correct character sequence along with options for specifying case-sensitivity,
character width etc.

SQL Essentials Training & Certification


Weekday / Weekend Batches
Q60. What are the different types of Collation Sensitivity?
Following are the different types of collation sensitivity:

• Case Sensitivity: A and a and B and b.

• Kana Sensitivity: Japanese Kana characters.

• Width Sensitivity: Single byte character and double-byte character.

• Accent Sensitivity.

Apart from this SQL Interview Questions Blog, if you want to get trained from
professionals on this technology, you can opt for structured training from
edureka!

Q61. What are Local and Global variables?


Local variables:
These variables can be used or exist only inside the function. These variables
are not used or referred by any other function.
Global variables:
These variables are the variables which can be accessed throughout the
program. Global variables cannot be created whenever that function is called.

Q62. What is Auto Increment in SQL?


Autoincrement keyword allows the user to create a unique number to get
generated whenever a new record is inserted into the table.
This keyword is usually required whenever PRIMARY KEY in SQL is used.

AUTO INCREMENT keyword can be used in Oracle and IDENTITY keyword can be
used in SQL SERVER.

Q63. What is a Datawarehouse?


Datawarehouse refers to a central repository of data where the data is
assembled from multiple sources of information. Those data are consolidated,
transformed and made available for the mining as well as online processing.
Warehouse data also have a subset of data called Data Marts.

Q64. What are the different authentication modes in SQL Server? How
can it be changed?
Windows mode and Mixed Mode – SQL and Windows. You can go to the below
steps to change authentication mode in SQL Server:

• Click Start> Programs> Microsoft SQL Server and click SQL Enterprise
Manager to run SQL Enterprise Manager from the Microsoft SQL Server
program group.
• Then select the server from the Tools menu.

• Select SQL Server Configuration Properties, and choose the Security


page.
Q65. What are STUFF and REPLACE function?
STUFF Function: This function is used to overwrite existing character or
inserts a string into another string. Syntax:
STUFF(string_expression,start, length, replacement_characters)
where,
string_expression: it is the string that will have characters substituted
start: This refers to the starting position
length: It refers to the number of characters in the string which are substituted.
replacement_string: They are the new characters which are injected in the
string.

REPLACE function: This function is used to replace the existing characters of


all the occurrences. Syntax:
REPLACE (string_expression, search_string, replacement_string)
Here every search_string in the string_expression will be replaced with the
replacement_string.
So this brings us to the end of the SQL interview questions blog. I hope this set
of SQL Interview Questions will help you ace your job interview. All the best
for your interview!

Apart from this SQL Interview Questions Blog, if you want to get trained from
professionals on SQL, you can opt for a structured training from edureka! Click
below to know more.

Check out this MySQL DBA Certification Training by Edureka, a trusted online
learning company with a network of more than 250,000 satisfied learners
spread across the globe. This course trains you on the core concepts &
advanced tools and techniques to manage data and administer the MySQL
Database. It includes hands-on learning on concepts like MySQL Workbench,
MySQL Server, Data Modeling, MySQL Connector, Database Design, MySQL
Command line, MySQL Functions etc. End of the training you will be able to
create and administer your own MySQL Database and manage data.

Got a question for us? Please mention it in the comments section of this “SQL
Interview Questions” blog and we will get back to you as soon as possible.
Hello friends! in this post, we will see some of the most common SQL
queries asked in interviews. Whether you are a DBA, developer, tester,
or data analyst, these SQL query interview questions and
answers are going to help you.

In fact, I have been asked most of these questions during interviews in


the different phases of my career.

If you want to skip the basic questions and start with some tricky SQL
queries then you can directly move to our SQL queries interview
questions for the experienced section.
Consider the below two tables for reference while trying to solve
the SQL queries for practice.
Table – EmployeeDetails
ManagerI DateOfJoinin
EmpId FullName City
d g
121 John Snow 321 01/31/2014 Toronto
321 Walter White 986 01/30/2015 California
Kuldeep
421 876 27/11/2016 New Delhi
Rana

Table – EmployeeSalary
Projec Salar
EmpId Variable
t y
121 P1 8000 500
321 P2 10000 1000
421 P1 12000 0

For your convenience, I have compiled the top 10 questions for you.
You can try solving these questions and click on the links to go to their
respective answers.
1.SQL Query to fetch records that are present in one table but not in
another table.
2.SQL query to fetch all the employees who are not working on any
project.
3.SQL query to fetch all the Employees from EmployeeDetails who
joined in the Year 2020.
4.Fetch all employees from EmployeeDetails who have a salary record
in EmployeeSalary.
5.Write an SQL query to fetch project-wise count of employees.
6.Fetch employee names and salary even if the salary value is not
present for the employee.
7.Write an SQL query to fetch all the Employees who are also
managers.
8.Write an SQL query to fetch duplicate records from EmployeeDetails.
9.Write an SQL query to fetch only odd rows from the table.
10.Write a query to find the 3rd highest salary from a table without top
or limit keyword.
Or, you can also jump to our below two sections on interview
questions for freshers and experienced professionals.
Content
• SQL Query Interview Questions for Freshers

• SQL Query Interview Questions for Experienced

SQL Query Interview Questions for


Freshers

Here is a list of top SQL query interview questions and answers for
fresher candidates that will help them in their interviews. In these
queries, we will focus on the basic SQL commands only.
Ques.1. Write an SQL query to fetch the EmpId and FullName
of all the employees working under Manager with id – ‘986’.
Ans. We can use the EmployeeDetails table to fetch the employee
details with a where clause for the manager-
SELECT EmpId, FullName
FROM EmployeeDetails
WHERE ManagerId = 986;
Ques.2. Write an SQL query to fetch the different projects
available from the EmployeeSalary table.
Ans. While referring to the EmployeeSalary table, we can see that this
table contains project values corresponding to each employee, or we
can say that we will have duplicate project values while selecting
Project values from this table.

So, we will use the distinct clause to get the unique values of the
Project.
SELECT DISTINCT(Project)
FROM EmployeeSalary;

Ques.3. Write an SQL query to fetch the count of employees


working in project ‘P1’.
Ans. Here, we would be using aggregate function count() with the
SQL where clause-
SELECT COUNT(*)
FROM EmployeeSalary
WHERE Project = 'P1';

Ques.4. Write an SQL query to find the maximum, minimum,


and average salary of the employees.
Ans. We can use the aggregate function of SQL to fetch the max, min,
and average values-
SELECT Max(Salary),
Min(Salary),
AVG(Salary)
FROM EmployeeSalary;

Ques.5. Write an SQL query to find the employee id whose


salary lies in the range of 9000 and 15000.
Ans. Here, we can use the ‘Between’ operator with a where clause.
SELECT EmpId, Salary
FROM EmployeeSalary
WHERE Salary BETWEEN 9000 AND 15000;
Ques.6. Write an SQL query to fetch those employees who live
in Toronto and work under manager with ManagerId – 321.
Ans. Since we have to satisfy both the conditions – employees living in
‘Toronto’ and working in Project ‘P2’. So, we will use AND operator
here-
SELECT EmpId, City, ManagerId
FROM EmployeeDetails
WHERE City='Toronto' AND ManagerId='321';

Ques.7. Write an SQL query to fetch all the employees who


either live in California or work under a manager with
ManagerId – 321.
Ans. This interview question requires us to satisfy either of the
conditions – employees living in ‘California’ and working under
Manager with ManagerId ‘321’. So, we will use the OR operator here-
SELECT EmpId, City, ManagerId
FROM EmployeeDetails
WHERE City='California' OR ManagerId='321';

Ques.8. Write an SQL query to fetch all those employees who


work on Project other than P1.
Ans. Here, we can use the NOT operator to fetch the rows which are
not satisfying the given condition.
SELECT EmpId
FROM EmployeeSalary
WHERE NOT Project='P1';

Or using the not equal to operator-


SELECT EmpId
FROM EmployeeSalary
WHERE Project <> 'P1';
For the difference between NOT and <> SQL operators, check this link
– Difference between the NOT and != operators.

Ques.9. Write an SQL query to display the total salary of each


employee adding the Salary with Variable value.
Ans. Here, we can simply use the ‘+’ operator in SQL.
SELECT EmpId,
Salary+Variable as TotalSalary
FROM EmployeeSalary;

Ques.10. Write an SQL query to fetch the employees whose


name begins with any two characters, followed by a text “hn”
and ending with any sequence of characters.
Ans. For this question, we can create an SQL query using like operator
with ‘_’ and ‘%’ wild card characters, where ‘_’ matches a single
character and ‘%’ matches ‘0 or multiple characters’.
SELECT FullName
FROM EmployeeDetails
WHERE FullName LIKE ‘__hn%’;

Ques.11. Write an SQL query to fetch all the EmpIds which are
present in either of the tables – ‘EmployeeDetails’ and
‘EmployeeSalary’.
Ans. In order to get unique employee ids from both the tables, we can
use Union clause which can combine the results of the two SQL
queries and return unique rows.
SELECT EmpId FROM EmployeeDetails
UNION
SELECT EmpId FROM EmployeeSalary;

Ques.12. Write an SQL query to fetch common records


between two tables.
Ans. SQL Server – Using INTERSECT operator-
SELECT * FROM EmployeeSalary
INTERSECT
SELECT * FROM ManagerSalary;

MySQL – Since MySQL doesn’t have INTERSECT operator so we can


use the sub query-
SELECT *
FROM EmployeeSalary
WHERE EmpId IN
(SELECT EmpId from ManagerSalary);
Ques.13. Write an SQL query to fetch records that are present
in one table but not in another table.
Ans. SQL Server – Using MINUS- operator-
SELECT * FROM EmployeeSalary
MINUS
SELECT * FROM ManagerSalary;

MySQL – Since MySQL doesn’t have MINUS operator so we can use


LEFT join-
SELECT EmployeeSalary.*
FROM EmployeeSalary
LEFT JOIN
ManagerSalary USING (EmpId)
WHERE ManagerSalary.EmpId IS NULL;

Ques.14. Write an SQL query to fetch the EmpIds that are


present in both the tables – ‘EmployeeDetails’ and
‘EmployeeSalary.
Ans. Using sub query-
SELECT EmpId FROM
EmployeeDetails
where EmpId IN
(SELECT EmpId FROM EmployeeSalary);

Ques.15. Write an SQL query to fetch the EmpIds that are


present in EmployeeDetails but not in EmployeeSalary.
Ans. Using sub query-
SELECT EmpId FROM
EmployeeDetails
where EmpId Not IN
(SELECT EmpId FROM EmployeeSalary);

Ques.16. Write an SQL query to fetch the employee full names


and replace the space with ‘-’.
Ans. Using ‘Replace’ function-
SELECT REPLACE(FullName, ' ', '-')
FROM EmployeeDetails;
Ques.17. Write an SQL query to fetch the position of a given
character(s) in a field.
Ans. Using ‘Instr’ function-
SELECT INSTR(FullName, 'Snow')
FROM EmployeeDetails;

Ques.18. Write an SQL query to display both the EmpId and


ManagerId together.
Ans. Here we can use the CONCAT command.
SELECT CONCAT(EmpId, ManagerId) as NewId
FROM EmployeeDetails;

Ques.19. Write a query to fetch only the first name(string


before space) from the FullName column of the
EmployeeDetails table.
Ans. In this question, we are required to first fetch the location of the
space character in the FullName field and then extract the first name
out of the FullName field.

For finding the location we will use the LOCATE method in MySQL and
CHARINDEX in SQL SERVER and for fetching the string before space,
we will use the SUBSTRING OR MID method.

MySQL – using MID


SELECT MID(FullName, 1, LOCATE(' ',FullName))
FROM EmployeeDetails;

SQL Server – using SUBSTRING


SELECT SUBSTRING(FullName, 1, CHARINDEX(' ',FullName))
FROM EmployeeDetails;

Ques.20. Write an SQL query to upper case the name of the


employee and lower case the city values.
Ans. We can use SQL Upper and Lower functions to achieve the
intended results.
SELECT UPPER(FullName), LOWER(City)
FROM EmployeeDetails;

Ques.21. Write an SQL query to find the count of the total


occurrences of a particular character – ‘n’ in the FullName
field.
Ans. Here, we can use the ‘Length’ function. We can subtract the total
length of the FullName field with a length of the FullName after
replacing the character – ‘n’.
SELECT FullName,
LENGTH(FullName) - LENGTH(REPLACE(FullName, 'n', ''))
FROM EmployeeDetails;

Ques.22. Write an SQL query to update the employee names


by removing leading and trailing spaces.
Ans. Using the ‘Update’ command with the ‘LTRIM’ and ‘RTRIM’
function.
UPDATE EmployeeDetails
SET FullName = LTRIM(RTRIM(FullName));

Ques.23. Fetch all the employees who are not working on any
project.
Ans. This is one of the very basic interview questions in which the
interviewer wants to see if the person knows about the commonly
used – Is NULL operator.
SELECT EmpId
FROM EmployeeSalary
WHERE Project IS NULL;

Ques.24. Write an SQL query to fetch employee names having


a salary greater than or equal to 5000 and less than or equal
to 10000.
Ans. Here, we will use BETWEEN in the ‘where’ clause to return the
EmpId of the employees with salary satisfying the required criteria and
then use it as subquery to find the fullName of the employee from
EmployeeDetails table.
SELECT FullName
FROM EmployeeDetails
WHERE EmpId IN
(SELECT EmpId FROM EmployeeSalary
WHERE Salary BETWEEN 5000 AND 10000);

Ques.25. Write an SQL query to find the current date-time.


Ans. MySQL-
SELECT NOW();

SQL Server-
SELECT getdate();

Oracle-
SELECT SYSDATE FROM DUAL;

Ques.26. Write an SQL query to fetch all the Employees details


from EmployeeDetails table who joined in the Year 2020.
Ans. Using BETWEEN for the date range ’01-01-2020′ AND ’31-12-
2020′-
SELECT * FROM EmployeeDetails
WHERE DateOfJoining BETWEEN '2020/01/01'
AND '2020/12/31';

Also, we can extract year part from the joining date (using YEAR in
mySQL)-
SELECT * FROM EmployeeDetails
WHERE YEAR(DateOfJoining) = '2020';

Ques.27. Write an SQL query to fetch all employee records


from EmployeeDetails table who have a salary record in
EmployeeSalary table.
Ans. Using ‘Exists’-
SELECT * FROM EmployeeDetails E
WHERE EXISTS
(SELECT * FROM EmployeeSalary S
WHERE E.EmpId = S.EmpId);

Ques.28. Write an SQL query to fetch project-wise count of


employees sorted by project’s count in descending order.
Ans. The query has two requirements – first to fetch the project-wise
count and then to sort the result by that count.

For project-wise count, we will be using the GROUP BY clause and for
sorting, we will use the ORDER BY clause on the alias of the project-
count.
SELECT Project, count(EmpId) EmpProjectCount
FROM EmployeeSalary
GROUP BY Project
ORDER BY EmpProjectCount DESC;

Ques.29. Write a query to fetch employee names and salary


records. Display the employee details even if the salary record
is not present for the employee.
Ans. This is again one of the very common interview questions in
which the interviewer just wants to check the basic knowledge of SQL
JOINS.

Here, we can use left join with EmployeeDetail table on the left side of
the EmployeeSalary table.
SELECT E.FullName, S.Salary
FROM EmployeeDetails E
LEFT JOIN
EmployeeSalary S
ON E.EmpId = S.EmpId;

Ques.30. Write an SQL query to join 3 tables.


Ans. Considering 3 tables TableA, TableB, and TableC, we can use 2
joins clauses like below-

SELECT column1, column2


FROM TableA
JOIN TableB ON TableA.Column3 = TableB.Column3
JOIN TableC ON TableA.Column4 = TableC.Column4;
For more questions on SQL Joins, you can also check
our top SQL Joins Interview Questions.
SQL Query Interview Questions for
Experienced

Here is the list of some of the most frequently asked SQL query
interview questions for experienced professionals. These questions
cover SQL queries on advanced SQL JOIN concepts, fetching duplicate
rows, odd and even rows, nth highest salary, etc.
Ques. 31. Write an SQL query to fetch all the Employees who
are also managers from the EmployeeDetails table.
Ans. Here, we have to use Self-Join as the requirement wants us to
analyze the EmployeeDetails table as two tables. We will use different
aliases ‘E’ and ‘M’ for the same EmployeeDetails table.
SELECT DISTINCT E.FullName
FROM EmployeeDetails E
INNER JOIN EmployeeDetails M
ON E.EmpID = M.ManagerID;

To learn more about Self Join along with some more queries, you can
watch the below video that explains the self join concept in a very
simple way.

Ques.32. Write an SQL query to fetch duplicate records from


EmployeeDetails (without considering the primary key –
EmpId).
Ans. In order to find duplicate records from the table, we can use
GROUP BY on all the fields and then use the HAVING clause to return
only those fields whose count is greater than 1 i.e. the rows having
duplicate records.
SELECT FullName, ManagerId, DateOfJoining, City, COUNT(*)
FROM EmployeeDetails
GROUP BY FullName, ManagerId, DateOfJoining, City
HAVING COUNT(*) > 1;

Ques.33. Write an SQL query to remove duplicates from a


table without using a temporary table.
Ans. Here, we can use delete with alias and inner join. We will check
for the equality of all the matching records and them remove the row
with higher EmpId.
DELETE E1 FROM EmployeeDetails E1
INNER JOIN EmployeeDetails E2
WHERE E1.EmpId > E2.EmpId
AND E1.FullName = E2.FullName
AND E1.ManagerId = E2.ManagerId
AND E1.DateOfJoining = E2.DateOfJoining
AND E1.City = E2.City;

Ques.34. Write an SQL query to fetch only odd rows from the
table.
Ans. In case we have an auto-increment field e.g. EmpId then we can
simply use the below query-
SELECT * FROM EmployeeDetails
WHERE MOD (EmpId, 2) <> 0;

In case we don’t have such a field then we can use the below queries.

Using Row_number in SQL server and checking that the remainder


when divided by 2 is 1-
SELECT E.EmpId, E.Project, E.Salary
FROM (
SELECT *, Row_Number() OVER(ORDER BY EmpId) AS RowNumber
FROM EmployeeSalary
)E
WHERE E.RowNumber % 2 = 1;

Using a user defined variable in MySQL-


SELECT *
FROM (
SELECT *, @rowNumber := @rowNumber+ 1 rn
FROM EmployeeSalary
JOIN (SELECT @rowNumber:= 0) r
)t
WHERE rn % 2 = 1;

Ques.35. Write an SQL query to fetch only even rows from the
table.
Ans. In case we have an auto-increment field e.g. EmpId then we can
simply use the below query-
SELECT * FROM EmployeeDetails
WHERE MOD (EmpId, 2) = 0;

In case we don’t have such a field then we can use the below queries.

Using Row_number in SQL server and checking that the remainder


when divided by 2 is 1-
SELECT E.EmpId, E.Project, E.Salary
FROM (
SELECT *, Row_Number() OVER(ORDER BY EmpId) AS RowNumber
FROM EmployeeSalary
)E
WHERE E.RowNumber % 2 = 0;

Using a user defined variable in MySQL-


SELECT *
FROM (
SELECT *, @rowNumber := @rowNumber+ 1 rn
FROM EmployeeSalary
JOIN (SELECT @rowNumber:= 0) r
)t
WHERE rn % 2 = 0;

Ques.36. Write an SQL query to create a new table with data


and structure copied from another table.
Ans.
CREATE TABLE NewTable
SELECT * FROM EmployeeSalary;

Ques.37. Write an SQL query to create an empty table with the


same structure as some other table.
Ans. Here, we can use the same query as above with False ‘WHERE’
condition-
CREATE TABLE NewTable
SELECT * FROM EmployeeSalary where 1=0;

Ques.38. Write an SQL query to fetch top n records?


Ans. In MySQL using LIMIT-
SELECT *
FROM EmployeeSalary
ORDER BY Salary DESC LIMIT N;

In SQL server using TOP command-


SELECT TOP N *
FROM EmployeeSalary
ORDER BY Salary DESC;

Ques.39. Write an SQL query to find the nth highest salary


from table.
Ans, Using Top keyword (SQL Server)-
SELECT TOP 1 Salary
FROM (
SELECT DISTINCT TOP N Salary
FROM Employee
ORDER BY Salary DESC
)
ORDER BY Salary ASC;

Using limit clause(MySQL)-


SELECT Salary
FROM Employee
ORDER BY Salary DESC LIMIT N-1,1;

Ques.40. Write SQL query to find the 3rd highest salary from a
table without using the TOP/limit keyword.
Ans. This is one of the most commonly asked interview questions. For
this, we will use a correlated subquery.

In order to find the 3rd highest salary, we will find the salary value
until the inner query returns a count of 2 rows having the salary
greater than other distinct salaries.
SELECT Salary
FROM EmployeeSalary Emp1
WHERE 2 = (
SELECT COUNT( DISTINCT ( Emp2.Salary ) )
FROM EmployeeSalary Emp2
WHERE Emp2.Salary > Emp1.Salary
)

For nth highest salary-


SELECT Salary
FROM EmployeeSalary Emp1
WHERE N-1 = (
SELECT COUNT( DISTINCT ( Emp2.Salary ) )
FROM EmployeeSalary Emp2
WHERE Emp2.Salary > Emp1.Salary
)

This concludes our post on frequently asked SQL query interview


questions and answers. I hope you practice these questions and
ace your database interviews.

If you feel, we have missed any of the common interview questions


on SQL then do let us know in the comments and we will add those
questions to our list.
Do check our article on – RDBM Interview
Questions, focussing on the theoretical interview
questions based on the DBMS and SQL concepts.
Complex SQL Queries Examples(90%
ASKED IN Interviews)

SQL Interview Book DOWNLOAD FOR FREE


1.Query to find Second Highest Salary of Employee?(click for explaination)
Answer:
Select distinct Salary from Employee e1 where 2=Select
count(distinct Salary) from Employee e2 where
e1.salary<=e2.salary;
Alternative Solution : Suggested by Ankit Srivastava

select min(salary)from(select distinct salary from emp order


by salary desc)where rownum<=2;
2.Query to find duplicate rows in table?(click here for explaination )
Answer :
Select * from Employee a where rowid <>( select max(rowid)
from Employee b where a.Employee_num=b.Employee_num);

3.How to fetch monthly Salary of Employee if annual salary is given?(click


here for Explaination)

Object 2

Answer:
Select Employee_name,Salary/12 as ‘Monthly Salary’ from
employee;

Click here to get information on ROW_ID


4.What is the Query to fetch first record from Employee table? (90% asked
Complex SQL Queries Examples)
Answer:
Select * from Employee where Rownum =1;
Select * from Employee where Rowid= select min(Rowid) from
Employee;

Click here to get What is Rownum?


5.What is the Query to fetch last record from the table?
Answer:
Select * from Employee where Rowid= select max(Rowid) from
Employee;

Click here to get 20 interview questions on Perforance Tuning..


6.What is Query to display first 5 Records from Employee table?(90% asked
Complex SQL Queries Examples)
Answer:
Select * from Employee where Rownum <= 5;

CLICK HERE TO GET INFORMATION ON NORMALIZATION


6.What is Query to display last 5 Records from Employee table?(90% asked
Complex SQL Queries Examples)
Answer:
Select * from Employee e where rownum <=5

union

select * from (Select * from Employee e order by rowid desc) where


rownum <=5;

Click Here to get What is Union?


7.What is Query to display Nth Record from Employee table?
Answer :
select * from ( select a.*, rownum rnum from
( YOUR_QUERY_GOES_HERE — including the order by ) a where
rownum <= N_ROWS ) where rnum >= N_ROWS

8.How to get 3 Highest salaries records from Employee table?


Answer:
select distinct salary from employee a where 3 >= (select
count(distinct salary) from employee b where a.salary <= b.salary)
order by a.salary desc;

Alternative Solution: Suggested by Ankit Srivastava

select min(salary)from(select distinct salary from emp order by salary


desc)where rownum<=3;

9.How to Display Odd rows in Employee table?(90% asked Complex SQL


Queries Examples)
Answer:
Select * from(Select rownum as rno,E.* from Employee E) where
Mod(rno,2)=1;

10.How to Display Even rows in Employee table?


Answer:
Select * from(Select rownum as rno,E.* from Employee) where
Mod(rno,2)=0;

Learn SQL Server Course here: SQL Server


Training
11.How to fetch 3rd highest salary using Rank Function?
Answer:
select * from (Select Dense_Rank() over ( order by salary desc) as
Rnk,E.* from Employee E) where Rnk=3;

Click Here to Get Information on Rank and Dense_Rank


12.How Can i create table with same structure of Employee table?(90%
asked Complex SQL Queries Examples)
Answer:
Create table Employee_1 as Select * from Employee where 1=2;

13.Display first 50% records from Employee table?


Answer:
select rownum, e.* from emp e where rownum<=(select count(*)/2
from emp);

14.Display last 50% records from Employee table?


Answer:
Select rownum,E.* from Employee E

minus

Select rownum,E.* from Employee E where rownum<=(Select


count(*)/2) from Employee);

15.How Can i create table with same structure with data of Employee
table?
Answer:
Create table Employee1 as select * from Employee;

16.How do i fetch only common records between 2 tables.


Answer:
Select * from Employee;

Intersect

Select * from Employee1;

CLICK HERE TO GET INFORMATION ABOUT INTERSECT OPERATOR


17.Find Query to get information of Employee where Employee is not
assigned to the department
Answer:
Select * from Employee where Dept_no Not in(Select Department_no
from Department);

18.How to get distinct records from the table without using distinct
keyword.
Answer:
select * from Employee a where rowid = (select max(rowid) from
Employee b where a.Employee_no=b.Employee_no);
19.Select all records from Employee table whose name is ‘Amit’ and
‘Pradnya’
Answer:
Select * from Employee where Name in(‘Amit’,’Pradnya’);

20.Select all records from Employee table where name not in ‘Amit’ and
‘Pradnya’
Answer:
select * from Employee where name Not in (‘Amit’,’Pradnya’);

Click Here to get 20 Interview Questions for Tech Mahindra….


21.how to write sql query for the below scenario
I/p:ORACLE
O/p:
O
R
A
C
L
E
i.e, splitting into multiple columns a string using sql.
Answer:
Select Substr(‘ORACLE’,Level,1) From Dual
Connect By Level<= Length(‘ORACLE’);

22.How to fetch all the records from Employee whose joining year is 2017?
Answer:
Oracle:

select * from Employee where To_char(Joining_date,’YYYY’)=’2017′;

MS SQL:

select * from Employee where


substr(convert(varchar,Joining_date,103),7,4)=’2017′;

23.What is SQL Query to find maximum salary of each department?


Answer:
Select Dept_id,max(salary) from Employee group by Dept_id;

24.How Do you find all Employees with its managers?(Consider there is


manager id also in Employee table)
Answer:
Select e.employee_name,m.employee name from Employee
e,Employee m where e.Employee_id=m.Manager_id;
25.Display the name of employees who have joined in 2016 and salary is
greater than 10000?
Answer:
Select name from Employee where Hire_Date like ‘2016%’ and
salary>10000;

26.How to display following using query?


*
**
***
Answer:
We cannot use dual table to display output given above. To display output use any table. I am
using Student table.

SELECT lpad (‘*’, ROWNUM,’*’) FROM Student WHERE ROWNUM <4;

27.How to add the email validation using only one query?


Answer :
User needs to use REGEXP_LIKE function for email validation.
SELECT
Email
FROM
Employee
where NOT REGEXP_LIKE(Email, ‘[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]
{2,4}’, ‘i’);

28.How to display 1 to 100 Numbers with query?


Answer:
Select level from dual connect by level <=100;

Tip: User needs to know the concept of Hierarchical queries. Click here to get concept of
hierarchical queries
29.How to remove duplicate rows from table?(100% asked in Complex SQL
Queries for Interviews)
Answer:
First Step: Selecting Duplicate rows from table
Tip: Use concept of max (rowid) of table. Click here to get concept of rowid.
Select rollno FROM Student WHERE ROWID <>

(Select max (rowid) from Student b where rollno=b.rollno);

Step 2: Delete duplicate rows


Delete FROM Student WHERE ROWID <>
(Select max (rowid) from Student b where rollno=b.rollno);

30.How to find count of duplicate rows? (95% asked in SQL queries for
Interviews )
Answer:
Select rollno, count (rollno) from Student

Group by rollno

Having count (rollno)>1

Order by count (rollno) desc;

31.How to Find the Joining date of Employee in YYYY-DAY-Date format.


Select FIRST_NAME, to_char(joining_date,’YYYY’) JoinYear ,
to_char(joining_date,’Mon’), to_char(joining_date,’dd’) from
EMPLOYEES;

Hope This article named Complex SQL queries examples is useful to all the programmers. This
article gives you the idea about Complex SQL Queries examples and will be useful to all the
programmers.

Question 32 : How to convert the System time in to seconds in oracle?


Answer :
To_char function is used to convert time to character and ssss will used to convert the time in to
seconds.

Following query is useful.

SQL> select
2 to_char(sysdate,'hh24:mi:ss') As "SystemTime",
3 to_char(sysdate,'sssss') "Seconds"
4 from dual;

SystemTime Seconds
-------- -----
11:34:50 41750
SQL Queries Interview Questions and Answers

SQL is the most popular data management query language. In addition, it


supports relational data, which helps to manage huge amount of data with
required relations.
The given below SQL interview questions requires some data for explanation of
SQL queries. You can refer the following data tables for examples.
Table – StudentDetails

StudI EnrollmentN
Name DateOfJoining
d o

Nick
11 1234567 01/02/2019
Panchal

Yash
21 2468101 15/03/2017
Panchal

Gyan
31 3689245 27/05/2018
Rathod
Table – StudentStipend

StudI Projec
Stipend
d t

11 P1 80000

21 P2 10000

31 P1 120000

Write an SQL query to insert a new student detail in


StudentDetails table.
Ans. We can use the INSERT query to insert data into SQL database table.
?
INSERT INTO StudentDetails(StudId,Name,EnrollmentNo,DateOfJoining) Values('51','Ashish
Patel','2468653','09/03/2019');
Write an SQL query to select a specific student detail in
StudentDetails table.
Ans. We can use the SELECT query to select data from the SQL database
table.
?
SELECT * FROM StudentDetails WHERE Studid = '31';

Write an SQL query to update a project detail in


StudentStipend table.
Ans. We can use the UPDATE query to update data into the SQL database
table.
?
UPDATE StudentStipend SET Project = 'P3' WHERE Studid = '31';

Write an SQL query to drop a StudentStipend table with its


structure.
Ans. We can use the DROP query to drop the SQL database table.
?
DROP TABLE StudentStipend;

Write an SQL query to delete only StudentDetails table


data.
Ans. We can use the TRUNCATE query to delete data from the SQL database
table.
?
TRUNCATE TABLE StudentDetails;

Write an SQL query to fetch student names having stipend


greater than or equal to 50000 and less than or equal
100000.
Ans. Here, we can use BETWEEN in the ‘where’ clause to return the StudId of
the student with stipend satisfying the required criteria and then use it as
subquery to find the Name of the student form StudentDetails table.
?
SELECT Name
FROM StudentDetails
WHERE StudId IN
(SELECT StudId FROM StudentStipend
WHERE Stipain BETWEEN 50000 AND 100000);

Write a query to fetch student names and stipend records.


Return student details even if the stipend record is not
present for the student.
Ans. Here, we can use left join with StudentDetail table on the left side.
?
SELECT St.Name, S.Stipend
FROM StudentDetails as St LEFT JOIN StudentStipend as S
ON St.StudId = S.StudId;

Write an SQL query to fetch all student records from


StudentDetails table who have a stipend record in
StudentStipend table.
Ans. We can do the required operation using EXISTS clause in the SQL query.
?
SELECT * FROM StudentDetails as St
WHERE EXISTS
(SELECT * FROM StudentStipend as S WHERE St.StudId = S.StudId);

Write an SQL query to fetch the number of students working


in project ‘P1’.
Ans. Here, we can use the aggregate function count() with the
SQL WHERE clause.
?
SELECT COUNT(*) FROM StudentStipend WHERE Project = 'P1';

Write an SQL query for fetching duplicate records from a


table.
Ans. To find duplicate records from the table, we can use GROUP BY clause on
all the fields and then we have to use HAVING clause to return only those
fields whose count is greater than one, i.e. the rows having duplicate records.
?
SELECT StudId, Project, Stipend, COUNT() FROM StudentStipend GROUP BY StudId, Project,
Stipend HAVING COUNT() > 1;

Write an SQL query for removing duplicates from a table


without using a temporary table.
Method 1: Using Group By and Having clause
?
DELETE FROM StudentStipend
WHERE StudId IN (
SELECT StudId
FROM StudentStipend
GROUP BY Project, Stipend
HAVING COUNT(*) > 1));

Method 2: Using rowId in Oracle


?
DELETE FROM StudentStipend
WHERE rowid NOT IN
(SELECT MAX(rowid) FROM StudentStipend GROUP BY StudId);

Write an SQL query for fetching all the Students who also
have enrollment No from StudentDetails table.
Ans. Here, we can use Self-Join as the requirement wants us to analyze the
StudentDetails table as two different tables, each for Student and enrollment
records.
?
SELECT DISTINCT S.Name
FROM StudentDetails S
INNER JOIN StudentDetails E
ON S.StudId = E.EnrollmentNo;

Write an SQL query for creating a new table with data and
structure copied from another table.
Ans. We can perform the required operation using the SELECT INTO query.
?
SELECT * INTO newTable FROM StudentDetails;
Write an SQL query to fetch a joint record between two
tables using intersect.
Ans. We can fetch a joint record between two tables using INTERSECT clause
as mentioned below.
?
SELECT * FROM StudentStipend
INTERSECT
SELECT * FROM EnrollmentDetails

Write an SQL query for fetching records that are present in


one table but not in another table using Minus.
Ans. We can add the MINUS clause to exclude some rows from the resultant
rows as mentioned below.
?
SELECT * FROM StudentStipend
MINUS
SELECT * FROM EnrollmentDetail

Write an SQL query to fetch count of students project-wise


sorted by project’s count in descending order.
Ans. In the mentioned below query first, we fetch the project-wise count and
then sort the result by count. For project-wise count, we use GROUP BY clause,
and then we use ORDER BY clause for sorting operation, on the alias of the
project-count.
?
SELECT Project, count(StudId) StudProjectCount
FROM StudentStipend
GROUP BY Project
ORDER BY StudProjectCount DESC;

Write an SQL query for creating an empty table with the


same structure as some other table.
Ans. We can use MySQL LIKE clause with CREATE statement.
?
CREATE TABLE newTable LIKE StudentDetails;
Write an SQL query for finding current date-time.
Ans. SQL queries for various Databases are as described below.
SQL Query In Oracle
?
SELECT SYSDATE FROM DUAL;

SQL Query In SQL Server


?
SELECT getdate();

SQL Query In MySQL


?
SELECT NOW();

Write an SQL query for fetching only even rows from the
table.
Ans. We can achieve this using Row_number in SQL server.
?
SELECT St.StudId, St.Project, St.Stipend
FROM (
SELECT *, Row_Number() OVER(ORDER BY StudId) AS RowNumber
FROM StudentStipend
) St
WHERE St.RowNumber % 2 = 0

Write an SQL query for fetching all the Students details


from StudentDetails table who joined in the Year 2018.
Ans. We can perform the required operation using BETWEEN for the date
range ’01-01-2018′ AND ’31-12-2018′.
?
SELECT * FROM StudentDetails WHERE DateOfJoining BETWEEN '01-01-2018' AND date '31-12-
2018';

Also, we can extract the year part from the joining date (using YEAR in MySQL).
?
SELECT * FROM StudentDetails WHERE YEAR(DateOfJoining) = '2018';

Write the SQL query to find the nth highest stipend from the
table.
Ans. SQL queries to find the nth highest stipend form the table for various
Databases are as described below.
Using Top keyword (SQL Server)
?
SELECT TOP 1 Stipend
FROM (
SELECT DISTINCT TOP N Stipend
FROM StudentStipend
ORDER BY Stipend DESC
)
ORDER BY Stipend ASC

Using limit clause(MySQL)


?
SELECT Stipend FROM StudentStipend ORDER BY Stipend DESC LIMIT N-1,1;

Write SQL query for fetching top n records using LIMIT?


Ans. SQL queries for fetching top n records using LIMIT for various Databases
are as described below.
In MySQL
?
SELECT * FROM StudentStipend ORDER BY Stipend DESC LIMIT N;

In SQL server using the TOP command


?
SELECT TOP N * FROM StudentStipend ORDER BY Stipend DESC

In Oracle using ROWNUM


?
SELECT * FROM (SELECT * FROM StudentStipend ORDER BY Stipend DESC)
WHERE ROWNUM <= 3;
Write a query for fetching only the first name(string before
space) from the Name column of StudentDetails table.
Ans. Here, we have to first fetch the location of the space character in the
Name field, and then we can extract the first name out of the Name field using
LOCATE method in MySQL, CHARINDEX in SQL SERVER, and for fetching the
string before space, we will use SUBSTRING OR MID method.
MySQL- Using MID
?
SELECT MID(Name, 0, LOCATE(' ',Name)) FROM StudentDetails;

SQL Server-Using SUBSTRING


?
SELECT SUBSTRING(Name, 0, CHARINDEX(' ',Name)) FROM StudentDetails;

We can also use LEFT which returns the left part of a string till specified number
of characters.
?
SELECT LEFT(Name, CHARINDEX(' ',Name) - 1) FROM StudentDetails;

Write an SQL query for fetching only odd rows from the
table.
Ans. We can achieve this using Row_number in SQL server.
?
SELECT St.StudId, St.Project, St.Stipend
FROM (
SELECT *, Row_Number() OVER(ORDER BY StudId) AS RowNumber
FROM StudentStipend
) St
WHERE St.RowNumber % 2 = 1

Write SQL query for finding the 3rd highest stipend from the
table without using TOP/limit keyword.
Ans. We have to use of correlated subquery for finding the 3rd highest stipend
the inner query will return us the count of till we find that there are two rows
that stipend higher than other distinct stipends.
?
SELECT Stipend
FROM StudentStipend Stud1
WHERE 2 = (
SELECT COUNT( DISTINCT ( Stud2.Stipend ) )
FROM StudentStipend Stud2
WHERE Stud2.Stipend > Stud1.Stipend
)

For nth highest stipend


?
SELECT Stipend
FROM StudentStipend Stud1
WHERE N-1 = (
SELECT COUNT( DISTINCT ( Stud2.Stipend ) )
FROM StudentStipend Stud2
WHERE Stud2.Stipend > Stud1.Stipend
)
SQL Window Functions
Starting here? This lesson is part of a full-length tutorial in using SQL for Data
Analysis. Check out the beginning.

In this lesson we'll cover:

• Intro to window functions

• Basic windowing syntax

• The usual suspects: SUM, COUNT, and AVG

• ROW_NUMBER()

• RANK() and DENSE_RANK()

• NTILE
• LAG and LEAD

• Defining a window alias

• Advanced windowing techniques

This lesson uses data from Washington DC's Capital Bikeshare Program,
which publishes detailed trip-level historical data on their website. The data
was downloaded in February, 2014, but is limited to data collected during the
first quarter of 2012. Each row represents one ride. Most fields are self-
explanatory, except rider_type: "Registered" indicates a monthly membership to
the rideshare program, "Casual" incidates that the rider bought a 3-day pass.
The start_time and end_time fields were cleaned up from their original forms to
suit SQL date formatting—they are stored in this table as timestamps.

Intro to window functions

PostgreSQL's documentation does an excellent job of introducing the


concept of Window Functions:

A window function performs a calculation across a set of table rows


that are somehow related to the current row. This is comparable to
the type of calculation that can be done with an aggregate function.
But unlike regular aggregate functions, use of a window function does
not cause rows to become grouped into a single output row — the
rows retain their separate identities. Behind the scenes, the window
function is able to access more than just the current row of the query
result.

The most practical example of this is a running total:

SELECT duration_seconds,
SUM(duration_seconds) OVER (ORDER BY start_time) AS running_total
FROM tutorial.dc_bikeshare_q1_2012

You can see that the above query creates an aggregation (running_total) without
using GROUP BY. Let's break down the syntax and see how it works.

Basic windowing syntax

The first part of the above aggregation, SUM(duration_seconds), looks a lot like
any other aggregation. Adding OVER designates it as a window function. You
could read the above aggregation as "take the sum of duration_seconds over the
entire result set, in order by start_time."
If you'd like to narrow the window from the entire dataset to individual groups
within the dataset, you can use PARTITION BY to do so:
SELECT start_terminal,
duration_seconds,
SUM(duration_seconds) OVER
(PARTITION BY start_terminal ORDER BY start_time)
AS running_total
FROM tutorial.dc_bikeshare_q1_2012
WHERE start_time < '2012-01-08'

The above query groups and orders the query by start_terminal. Within each
value of start_terminal, it is ordered by start_time, and the running total sums
across the current row and all previous rows of duration_seconds. Scroll down
until the start_terminal value changes and you will notice that running_total starts
over. That's what happens when you group using PARTITION BY. In case you're
still stumped by ORDER BY, it simply orders by the designated column(s) the
same way the ORDER BY clause would, except that it treats every partition as
separate. It also creates the running total—without ORDER BY, each value will
simply be a sum of all the duration_seconds values in its respective start_terminal.
Try running the above query without ORDER BY to get an idea:
SELECT start_terminal,
duration_seconds,
SUM(duration_seconds) OVER
(PARTITION BY start_terminal) AS start_terminal_total
FROM tutorial.dc_bikeshare_q1_2012
WHERE start_time < '2012-01-08'

The ORDER and PARTITION define what is referred to as the "window"—the


ordered subset of data over which calculations are made.
Note: You can't use window functions and standard aggregations in the same
query. More specifically, you can't include window functions in a GROUP
BY clause.

Practice Problem
Write a query modification of the above example query that shows the duration
of each ride as a percentage of the total time accrued by riders from each
start_terminal

Try it out See the answer

The usual suspects: SUM, COUNT, and AVG

When using window functions, you can apply the same aggregates that you
would under normal circumstances—SUM, COUNT, and AVG. The easiest way to
understand these is to re-run the previous example with some additional
functions. Make
SELECT start_terminal,
duration_seconds,
SUM(duration_seconds) OVER
(PARTITION BY start_terminal) AS running_total,
COUNT(duration_seconds) OVER
(PARTITION BY start_terminal) AS running_count,
AVG(duration_seconds) OVER
(PARTITION BY start_terminal) AS running_avg
FROM tutorial.dc_bikeshare_q1_2012
WHERE start_time < '2012-01-08'

Alternatively, the same functions with ORDER BY:


SELECT start_terminal,
duration_seconds,
SUM(duration_seconds) OVER
(PARTITION BY start_terminal ORDER BY start_time)
AS running_total,
COUNT(duration_seconds) OVER
(PARTITION BY start_terminal ORDER BY start_time)
AS running_count,
AVG(duration_seconds) OVER
(PARTITION BY start_terminal ORDER BY start_time)
AS running_avg
FROM tutorial.dc_bikeshare_q1_2012
WHERE start_time < '2012-01-08'

Make sure you plug those previous two queries into Mode and run them. This
next practice problem is very similar to the examples, so try modifying the
above code rather than starting from scratch.

Practice Problem
Write a query that shows a running total of the duration of bike rides (similar to
the last example), but grouped by end_terminal, and with ride duration sorted in
descending order.

Try it out See the answer

ROW_NUMBER()

ROW_NUMBER() does just what it sounds like—displays the number of a given


row. It starts are 1 and numbers the rows according to the ORDER BY part of the
window statement. ROW_NUMBER() does not require you to specify a variable
within the parentheses:
SELECT start_terminal,
start_time,
duration_seconds,
ROW_NUMBER() OVER (ORDER BY start_time)
AS row_number
FROM tutorial.dc_bikeshare_q1_2012
WHERE start_time < '2012-01-08'

Using the PARTITION BY clause will allow you to begin counting 1 again in each
partition. The following query starts the count over again for each terminal:
SELECT start_terminal,
start_time,
duration_seconds,
ROW_NUMBER() OVER (PARTITION BY start_terminal
ORDER BY start_time)
AS row_number
FROM tutorial.dc_bikeshare_q1_2012
WHERE start_time < '2012-01-08'

RANK() and DENSE_RANK()

RANK() is slightly different from ROW_NUMBER(). If you order by start_time, for


example, it might be the case that some terminals have rides with two identical
start times. In this case, they are given the same rank,
whereas ROW_NUMBER() gives them different numbers. In the following query,
you notice the 4th and 5th observations for start_terminal 31000—they are both
given a rank of 4, and the following result receives a rank of 6:
SELECT start_terminal,
duration_seconds,
RANK() OVER (PARTITION BY start_terminal
ORDER BY start_time)
AS rank
FROM tutorial.dc_bikeshare_q1_2012
WHERE start_time < '2012-01-08'

You can also use DENSE_RANK() instead of RANK() depending on your application.
Imagine a situation in which three entries have the same value. Using either
command, they will all get the same rank. For the sake of this example, let's
say it's "2." Here's how the two commands would evaluate the next results
differently:
• RANK() would give the identical rows a rank of 2, then skip ranks 3 and 4,
so the next result would be 5
• DENSE_RANK() would still give all the identical rows a rank of 2, but the
following row would be 3—no ranks would be skipped.
Practice Problem
Write a query that shows the 5 longest rides from each starting terminal,
ordered by terminal, and longest to shortest rides within each terminal. Limit to
rides that occurred before Jan. 8, 2012.

Try it out See the answer

NTILE

You can use window functions to identify what percentile (or quartile, or any
other subdivision) a given row falls into. The syntax is NTILE(*# of buckets*). In
this case, ORDER BY determines which column to use to determine the quartiles
(or whatever number of 'tiles you specify). For example:
SELECT start_terminal,
duration_seconds,
NTILE(4) OVER
(PARTITION BY start_terminal ORDER BY duration_seconds)
AS quartile,
NTILE(5) OVER
(PARTITION BY start_terminal ORDER BY duration_seconds)
AS quintile,
NTILE(100) OVER
(PARTITION BY start_terminal ORDER BY duration_seconds)
AS percentile
FROM tutorial.dc_bikeshare_q1_2012
WHERE start_time < '2012-01-08'
ORDER BY start_terminal, duration_seconds

Looking at the results from the query above, you can see that
the percentile column doesn't calculate exactly as you might expect. If you only
had two records and you were measuring percentiles, you'd expect one record
to define the 1st percentile, and the other record to define the 100th
percentile. Using the NTILE function, what you'd actually see is one record in the
1st percentile, and one in the 2nd percentile. You can see this in the results
for start_terminal 31000—the percentile column just looks like a numerical
ranking. If you scroll down to start_terminal 31007, you can see that it properly
calculates percentiles because there are more than 100 records for
that start_terminal. If you're working with very small windows, keep this in mind
and consider using quartiles or similarly small bands.
Practice Problem
Write a query that shows only the duration of the trip and the percentile into
which that duration falls (across the entire dataset—not partitioned by
terminal).

Try it out See the answer

LAG and LEAD

It can often be useful to compare rows to preceding or following rows,


especially if you've got the data in an order that makes sense. You can
use LAG or LEAD to create columns that pull values from other rows—all you
need to do is enter which column to pull from and how many rows away you'd
like to do the pull. LAG pulls from previous rows and LEAD pulls from following
rows:
SELECT start_terminal,
duration_seconds,
LAG(duration_seconds, 1) OVER
(PARTITION BY start_terminal ORDER BY duration_seconds) AS lag,
LEAD(duration_seconds, 1) OVER
(PARTITION BY start_terminal ORDER BY duration_seconds) AS lead
FROM tutorial.dc_bikeshare_q1_2012
WHERE start_time < '2012-01-08'
ORDER BY start_terminal, duration_seconds

This is especially useful if you want to calculate differences between rows:

SELECT start_terminal,
duration_seconds,
duration_seconds -LAG(duration_seconds, 1) OVER
(PARTITION BY start_terminal ORDER BY duration_seconds)
AS difference
FROM tutorial.dc_bikeshare_q1_2012
WHERE start_time < '2012-01-08'
ORDER BY start_terminal, duration_seconds

The first row of the difference column is null because there is no previous row
from which to pull. Similarly, using LEAD will create nulls at the end of the
dataset. If you'd like to make the results a bit cleaner, you can wrap it in an
outer query to remove nulls:
SELECT *
FROM (
SELECT start_terminal,
duration_seconds,
duration_seconds -LAG(duration_seconds, 1) OVER
(PARTITION BY start_terminal ORDER BY duration_seconds)
AS difference
FROM tutorial.dc_bikeshare_q1_2012
WHERE start_time < '2012-01-08'
ORDER BY start_terminal, duration_seconds
) sub
WHERE sub.difference IS NOT NULL

Defining a window alias

If you're planning to write several window functions in to the same query, using
the same window, you can create an alias. Take the NTILE example above:
SELECT start_terminal,
duration_seconds,
NTILE(4) OVER
(PARTITION BY start_terminal ORDER BY duration_seconds)
AS quartile,
NTILE(5) OVER
(PARTITION BY start_terminal ORDER BY duration_seconds)
AS quintile,
NTILE(100) OVER
(PARTITION BY start_terminal ORDER BY duration_seconds)
AS percentile
FROM tutorial.dc_bikeshare_q1_2012
WHERE start_time < '2012-01-08'
ORDER BY start_terminal, duration_seconds

This can be rewritten as:


SELECT start_terminal,
duration_seconds,
NTILE(4) OVER ntile_window AS quartile,
NTILE(5) OVER ntile_window AS quintile,
NTILE(100) OVER ntile_window AS percentile
FROM tutorial.dc_bikeshare_q1_2012
WHERE start_time < '2012-01-08'
WINDOW ntile_window AS
(PARTITION BY start_terminal ORDER BY duration_seconds)
ORDER BY start_terminal, duration_seconds

The WINDOW clause, if included, should always come after the WHERE clause.

Advanced windowing techniques

You can check out a complete list of window functions in Postgres (the syntax
Mode uses) in the Postgres documentation. If you're using window functions
on a connected database, you should look at the appropriate syntax guide
for your system.
Top 50 SQL Interview Questions and
Answers for Experienced & Freshers
(2021 Update)
ByRichard PetersonUpdated

SQL stands for Structured


Query Language is a domain
specific programming language
for managing the data in
Database Management
Systems. SQL programming
skills are highly desirable and
required in the market, as there
is a massive use of Database
Management Systems (DBMS)
in almost every software
application. In order to get a
Object 4

job, candidates need to crack the interview in which they are asked
various SQL interview questions.
Following is a curated list of SQL questions for interview with answers,
which are likely to be asked during the SQL interview. Candidates are
likely to be asked SQL basic interview questions to advance level SQL
interview questions for 3 years experience professionals, depending
on their experience and various other factors. The below list covers all
the SQL technical interview questions for freshers as well as SQL
server interview questions for experienced level candidates and some
SQL query interview questions.

Free PDF Download: SQL Interview Questions


Frequently Asked SQL Interview Questions
and Answers for Freshers and Experienced
1. What is DBMS?
A Database Management System (DBMS) is a program that controls
creation, maintenance and use of a database. DBMS can be termed as
File Manager that manages data in a database rather than saving it in
file systems.

2. What is RDBMS?
RDBMS stands for Relational Database Management System. RDBMS
store the data into the collection of tables, which is related by
common fields between the columns of the table. It also provides
relational operators to manipulate the data stored into the tables.
Example: SQL Server.

3. What is SQL?
SQL stands for Structured Query Language , and it is used to
communicate with the Database. This is a standard language used to
perform tasks such as retrieval, updation, insertion and deletion of
data from a database.
Standard SQL Commands are Select.

Object 5
10 Most Common Interview Questions and Answers ????

4. What is a Database?
Database is nothing but an organized form of data for easy access,
storing, retrieval and managing of data. This is also known as
structured form of data which can be accessed in many ways.
Example: School Management Database, Bank Management
Database.

5. What are tables and Fields?


A table is a set of data that are organized in a model with Columns
Object 6

and Rows. Columns can be categorized as vertical, and Rows are


horizontal. A table has specified number of column called fields but
can have any number of rows which is called record.
Example:.
Table: Employee.
Field: Emp ID, Emp Name, Date of Birth.
Data: 201456, David, 11/15/1960.

6. What is a primary key?


A primary key is a combination of fields which uniquely specify a row.
This is a special kind of unique key, and it has implicit NOT NULL
constraint. It means, Primary key values cannot be NULL.

7. What is a unique key?


A Unique key constraint uniquely identified each record in the
database. This provides uniqueness for the column or set of columns.
A Primary key constraint has automatic unique constraint defined on
it. But not, in the case of Unique Key.
There can be many unique constraint defined per table, but only one
Primary key constraint defined per table.

8. What is a foreign key?


A foreign key is one table which can be related to the primary key of
another table. Relationship needs to be created between two tables by
referencing foreign key with the primary key of another table.

9. What is a join?
This is a keyword used to query data from more tables based on the
relationship between the fields of the tables. Keys play a major role
when JOINs are used.

Object 7

10. What are the types of join and explain each?


There are various types of join which can be used to retrieve data and
it depends on the relationship between tables.
• Inner Join.

Inner join return rows when there is at least one match of rows
between the tables.
• Right Join.

Right join return rows which are common between the tables and all
rows of Right hand side table. Simply, it returns all the rows from the
right hand side table even though there are no matches in the left
hand side table.
• Left Join.

Left join return rows which are common between the tables and all
rows of Left hand side table. Simply, it returns all the rows from Left
hand side table even though there are no matches in the Right hand
side table.
• Full Join.

Full join return rows when there are matching rows in any one of the
tables. This means, it returns all the rows from the left hand side table
and all the rows from the right hand side table.

11. What is normalization?


Normalization is the process of minimizing redundancy and
dependency by organizing fields and table of a database. The main
aim of Normalization is to add, delete or modify field that can be made
in a single table.

12. What is Denormalization?


DeNormalization is a technique used to access the data from higher to
lower normal forms of database. It is also process of introducing
redundancy into a table by incorporating data from the related tables.

13. What are all the different normalizations?


The normal forms can be divided into 5 forms, and they are explained
below -.
• First Normal Form (1NF):.

This should remove all the duplicate columns from the table. Creation
of tables for the related data and identification of unique columns.
• Second Normal Form (2NF):.

Meeting all requirements of the first normal form. Placing the subsets
of data in separate tables and Creation of relationships between the
tables using primary keys.
• Third Normal Form (3NF):.

This should meet all requirements of 2NF. Removing the columns


which are not dependent on primary key constraints.
• Fourth Normal Form (4NF):.

Meeting all the requirements of third normal form and it should not
have multi- valued dependencies.

14. What is a View?


A view is a virtual table which consists of a subset of data contained in
a table. Views are not virtually present, and it takes less space to
store. View can have data of one or more tables combined, and it is
depending on the relationship.

15. What is an Index?


An index is performance tuning method of allowing faster retrieval of
records from the table. An index creates an entry for each value and it
will be faster to retrieve data.

Object 8

16. What are all the different types of indexes?


There are three types of indexes -.
• Unique Index.

This indexing does not allow the field to have duplicate values if the
column is unique indexed. Unique index can be applied automatically
when primary key is defined.
• Clustered Index.
This type of index reorders the physical order of the table and search
based on the key values. Each table can have only one clustered
index.
• NonClustered Index.

NonClustered Index does not alter the physical order of the table and
maintains logical order of data. Each table can have 999 nonclustered
indexes.

17. What is a Cursor?


A database Cursor is a control which enables traversal over the rows
or records in the table. This can be viewed as a pointer to one row in a
set of rows. Cursor is very much useful for traversing such as retrieval,
addition and removal of database records.

18. What is a relationship and what are they?


Database Relationship is defined as the connection between the tables
in a database. There are various data basing relationships, and they
are as follows:.
• One to One Relationship.

• One to Many Relationship.

• Many to One Relationship.

• Self-Referencing Relationship.

19. What is a query?


A DB query is a code written in order to get the information back from
the database. Query can be designed in such a way that it matched
with our expectation of the result set. Simply, a question to the
Database.

20. What is subquery?


A subquery is a query within another query. The outer query is called
as main query, and inner query is called subquery. SubQuery is always
executed first, and the result of subquery is passed on to the main
query.

21. What are the types of subquery?


There are two types of subquery – Correlated and Non-Correlated.
A correlated subquery cannot be considered as independent query,
but it can refer the column in a table listed in the FROM the list of the
main query.
A Non-Correlated sub query can be considered as independent query
and the output of subquery are substituted in the main query.

Object 9

22. What is a stored procedure?


Stored Procedure is a function consists of many SQL statement to
access the database system. Several SQL statements are consolidated
into a stored procedure and execute them whenever and wherever
required.

23. What is a trigger?


A DB trigger is a code or programs that automatically execute with
response to some event on a table or view in a database. Mainly,
trigger helps to maintain the integrity of the database.
Example: When a new student is added to the student database, new
records should be created in the related tables like Exam, Score and
Attendance tables.

24. What is the difference between DELETE and


TRUNCATE commands?
DELETE command is used to remove rows from the table, and WHERE
clause can be used for conditional set of parameters. Commit and
Rollback can be performed after delete statement.
TRUNCATE removes all rows from the table. Truncate operation cannot
be rolled back.

25. What are local and global variables and their


differences?
Local variables are the variables which can be used or exist inside the
function. They are not known to the other functions and those
variables cannot be referred or used. Variables can be created
whenever that function is called.
Global variables are the variables which can be used or exist
throughout the program. Same variable declared in global cannot be
used in functions. Global variables cannot be created whenever that
function is called.

26. What is a constraint?


Constraint can be used to specify the limit on the data type of table.
Constraint can be specified while creating or altering the table
statement. Sample of constraint are.
• NOT NULL.

• CHECK.

• DEFAULT.

• UNIQUE.

• PRIMARY KEY.

• FOREIGN KEY.
27. What is data Integrity?
Data Integrity defines the accuracy and consistency of data stored in a
database. It can also define integrity constraints to enforce business
rules on the data when it is entered into the application or database.

28. What is Auto Increment?


Auto increment keyword allows the user to create a unique number to
be generated when a new record is inserted into the table. AUTO
INCREMENT keyword can be used in Oracle and IDENTITY keyword can
be used in SQL SERVER.
Mostly this keyword can be used whenever PRIMARY KEY is used.

29. What is the difference between Cluster and


Non-Cluster Index?
Clustered index is used for easy retrieval of data from the database by
altering the way that the records are stored. Database sorts out rows
by the column which is set to be clustered index.
A nonclustered index does not alter the way it was stored but creates
a complete separate object within the table. It point back to the
original table rows after searching.

30. What is Datawarehouse?


Datawarehouse is a central repository of data from multiple sources of
information. Those data are consolidated, transformed and made
available for the mining and online processing. Warehouse data have a
subset of data called Data Marts.

31. What is Self-Join?


Self-join is set to be query used to compare to itself. This is used to
compare values in a column with other values in the same column in
the same table. ALIAS ES can be used for the same table comparison.
Object 10

32. What is Cross-Join?


Cross join defines as Cartesian product where number of rows in the
first table multiplied by number of rows in the second table. If
suppose, WHERE clause is used in cross join then the query will work
like an INNER JOIN.

33. What is user defined functions?


User defined functions are the functions written to use that logic
whenever required. It is not necessary to write the same logic several
times. Instead, function can be called or executed whenever needed.

34. What are all types of user defined functions?


Three types of user defined functions are.
• Scalar Functions.

• Inline Table valued functions.

• Multi statement valued functions.


Scalar returns unit, variant defined the return clause. Other two types
return table as a return.

35. What is collation?


Collation is defined as set of rules that determine how character data
can be sorted and compared. This can be used to compare A and,
other language characters and also depends on the width of the
characters.
ASCII value can be used to compare these character data.

36. What are all different types of collation


sensitivity?
Following are different types of collation sensitivity -.
• Case Sensitivity – A and a and B and b.

• Accent Sensitivity.

• Kana Sensitivity – Japanese Kana characters.

• Width Sensitivity – Single byte character and double byte


character.

37. Advantages and Disadvantages of Stored


Procedure?
Stored procedure can be used as a modular programming – means
create once, store and call for several times whenever required. This
supports faster execution instead of executing multiple queries. This
reduces network traffic and provides better security to the data.
Disadvantage is that it can be executed only in the Database and
utilizes more memory in the database server.

38. What is Online Transaction Processing (OLTP)?


Online Transaction Processing (OLTP) manages transaction based
applications which can be used for data entry, data retrieval and data
processing. OLTP makes data management simple and efficient. Unlike
OLAP systems goal of OLTP systems is serving real-time transactions.
Example – Bank Transactions on a daily basis.

39. What is CLAUSE?


SQL clause is defined to limit the result set by providing condition to
the query. This usually filters some rows from the whole set of records.
Example – Query that has WHERE condition
Query that has HAVING condition.

40. What is recursive stored procedure?


A stored procedure which calls by itself until it reaches some boundary
condition. This recursive function or procedure helps programmers to
use the same set of code any number of times.

41. What is Union, minus and Interact commands?


UNION operator is used to combine the results of two tables, and it
eliminates duplicate rows from the tables.
MINUS operator is used to return rows from the first query but not
from the second query. Matching records of first and second query and
other rows from the first query will be displayed as a result set.
INTERSECT operator is used to return rows returned by both the
queries.

42. What is an ALIAS command?


ALIAS name can be given to a table or column. This alias name can be
referred in WHERE clause to identify the table or column.
Example-.
Select st.StudentID, Ex.Result from student st, Exam as Ex 
where st.studentID = Ex. StudentID

Here, st refers to alias name for student table and Ex refers to alias
name for exam table.

43. What is the difference between TRUNCATE and


DROP statements?
TRUNCATE removes all the rows from the table, and it cannot be rolled
back. DROP command removes a table from the database and
operation cannot be rolled back.

44. What are aggregate and scalar functions?


Aggregate functions are used to evaluate mathematical calculation
and return single values. This can be calculated from the columns in a
table. Scalar functions return a single value based on the input value.
Example -.
Aggregate – max(), count – Calculated with respect to numeric.
Scalar – UCASE(), NOW() – Calculated with respect to strings.

45. How can you create an empty table from an


existing table?
Example will be -.
Select * into studentcopy from student where 1=2

Here, we are copying student table to another table with the same
structure with no rows copied.

46. How to fetch common records from two tables?


Common records result set can be achieved by -.
Select studentID from student INTERSECT Select StudentID 
from Exam

47. How to fetch alternate records from a table?


Records can be fetched for both Odd and Even row numbers -.
To display even numbers-.
Select studentId from (Select rowno, studentId from 
student) where mod(rowno,2)=0

To display odd numbers-.


Select studentId from (Select rowno, studentId from 
student) where mod(rowno,2)=1

from (Select rowno, studentId from student) where mod(rowno,2)=1.


[/sql]

48. How to select unique records from a table?


Select unique records from a table by using DISTINCT keyword.
Select DISTINCT StudentID, StudentName from Student.

49. What is the command used to fetch first 5


characters of the string?
There are many ways to fetch first 5 characters of the string -.
Select SUBSTRING(StudentName,1,5) as studentname from 
student
Select LEFT(Studentname,5) as studentname from student

50. Which operator is used in query for pattern


matching?
LIKE operator is used for pattern matching, and it can be used as -.
1.% – Matches zero or more characters.
2._(Underscore) – Matching exactly one character.
Example -.
Select * from Student where studentname like 'a%'

Select * from Student where studentname like 'ami_'
Advanced SQL Interview Questions
• Difficulty Level : Medium
• Last Updated : 18 Sep, 2019
Different companies have a different approach to their interviewing
process. Some would be concentrating on work experience and
knowledge; others might focus on personality, while the rest fall
somewhere in between.

Therefore, finding and learning from different interview questions and


answers can help see different perspectives of what might be most
important in different marketplaces. So, here’s a list of advanced SQL
interview questions by blockchain-based eLearning platform.

Attention reader! Don’t stop learning now. Learn SQL for interviews
using SQL Course by GeeksforGeeks.
• Que-1: Explain the meaning of ‘index’.
Explanation:
Indexes help retrieve information from the database faster and with
higher efficiency. In other words, it’s a method that enhances
performance and there are 3 types of indexes:
• Clustered – reorders the table and searches for information with the

use of key values


• Non-clustered – maintains the order of the table

• Unique – forbids fields to have duplicated values

Moreover, a table can have multiple non-cluster indexes, but


only 1 single clustered one.

Object 11

• Que-2: You forgot your root password, what do you do ?


Explanation:
• Start the database with the command of “skip-grants-table”.

• After you set the new password, restart the database in normal mode
and enter the new password.

• Que-3: Are NULL values equal to a zero ?

Explanation:
No, because a “zero” has a numerical manner and NULL represent the
absence of a character. This happens when the character is unknown or
unavailable. Additionally, NULL shouldn’t be confused with blank
space because data record without any value assigned is not the same
as a plain blank space, with no data records attached.

• Que-4: Data disk gets overloaded, what do you do ?

Explanation:
You should apply a soft link: these links create a location where you are
able to store your .frm and .idb files. This will resolve the overload
problem.

• Que-5: Explain what‘auto increment’ is?

Explanation:
This command allows you to generate a unique number when a new
record is written to a table. When you want to the primary key field
value to be generated automatically each time you insert a new record,
this is when this function comes in handy.
Another thing worth noting is that the command can be used on various
platforms. For SQL Servers the “auto increment” command is “identity”.

Object 12
• Que-6: What are the most basic MySQL architecture components ?
Explanation:
There are three main components:
• Query optimizer;
• Connection manager;
• Pluggable engine.

• Que-7: Using an existing table, make an empty one.


Explanation:
Select * into employeecopy from employee where 1=2

• Que-8: How would you check your current SQL version ?


Explanation:
You can get the most current SQL version by issuing this command:
SELECT VERSION()

• Que-9: Get alternative odd records from the table.


Explanation:
This can be achieved using the command:
Select employeeId from (Select rowno, employeetId from employee) where
mod(rowno, 2)=1

• Que-10: What command would select a unique record from the table ?

Explanation:
The “distinct” command. Here’s an example:
Object 13

Select DISTINCT employeeID from Employee

• Que-11: What are variables of SQL ?


Explanation:
In SQL, there are two different variables:
• Local – these variables can only exist in one single function

• Global – are the opposite of local, which means they can be located

through ought the entire program.

• Que-12: What is a ‘datawarehouse’ and what it does ?

Explanation:
A “datawarehouse” is a system used for data analysis and reporting.
Basically, it’s a warehouse of data. Data in DWs can be stored from
various areas and sources and thus makes them central repositories of
integrated data that is ready for usage.

• Que-13: For what ‘recursive stored procedure’ is mainly used ?

Explanation:
A recursive stored procedure is a procedure that will make the code
calls itself until specific boundary condition is reached. This is a
productivity type of thing, that allows programmers to use the same
code a number of times.

• Que-14: Retrieve the first 3 characters from a character string.


Explanation:
There are a few ways to do this. Nevertheless, the command presented
below can be treated as a more popular and easier one:
Select SUBSTRING(EmployeeSurname, 1, 5) as employeesurname from
employee

• Que-15: How would you retrieve common records from two tables ?
Explanation:
By performing the task below:
Select employeeID from employee. INTERSECT Select EmployeeID from
WorkShift

You might also like