SQL All
SQL All
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
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.
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)
);
• LEFT (OUTER) JOIN: Retrieves all the records/rows from the left and the
matched records/rows from the right table.
SELECT *
FROM Table_A A
LEFT JOIN Table_B B
ON A.col = B.col;
• RIGHT (OUTER) JOIN: Retrieves all the records/rows from the right and the
matched records/rows from the left table.
SELECT *
FROM Table_A A
RIGHT JOIN Table_B B
ON A.col = B.col;
• FULL (OUTER) JOIN: Retrieves all the records where there is a match in either
the left or right table.
SELECT *
FROM Table_A A
FULL JOIN Table_B B
ON A.col = B.col;
Write a SQL statement to CROSS JOIN 'table_1' with 'table_2' and fetch 'col_1'
from table_1 & 'col_2' from table_2 respectively. Do not use alias.
Write a SQL statement to perform SELF JOIN for 'Table_X' with alias 'Table_1'
and 'Table_2', on columns 'Col_1' and 'Col_2' respectively.
There are different types of indexes that can be created for different purposes:
• 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".
Write a SQL query to select the field "app_id" in table "applications" where
"app_id" less than 1000.
Write a SQL query to fetch the field "app_name" from "apps" where "apps.id" is
equal to the above collection of "app_id".
20. What are some common clauses used with SELECT query in SQL?
Some common SQL clauses used in conjuction with a SELECT query are as
follows:
• WHERE clause in SQL is used to filter records that are necessary, based on
specific conditions.
• ORDER BY clause in SQL is used to sort the records based on some field(s) in
ascending (ASC) or descending order (DESC).
SELECT *
FROM myDB.students
WHERE graduation_year = 2019
ORDER BY studentID DESC;
• GROUP BY clause in SQL is used to group records with identical data and can
be used in conjunction with some aggregation functions to produce
summarized results from the database.
• HAVING clause in SQL is used to filter records in combination with the GROUP
BY clause. It is different from WHERE, since the WHERE clause cannot filter
aggregated records.
SELECT COUNT(studentId), country
FROM myDB.students
WHERE country != "INDIA"
GROUP BY country
HAVING COUNT(studentID) > 5;
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".
Write an SQL statement to select all from table "Limited" with alias "Ltd".
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 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.
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;
46. How can we start, restart and stop the PostgreSQL server?
• To start the PostgreSQL server, we run:
Starting PostgreSQL: ok
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');
If the database has been deleted successfully, then the following message
would be shown:
DROP DATABASE
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
Want to Upskill yourself to get ahead in your career? Check out the Top
Trending Technologies.
Let’s get started!
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.
Table: StudentInformation
Field: Stu Id, Stu Name, Stu Marks
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.
• NOT NULL
• CHECK
• DEFAULT
• UNIQUE
• PRIMARY KEY
• FOREIGN KEY
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!
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.
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.
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!
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!
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.
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:
• 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:
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);
• Using EXEC.
• Using sp_executesql.
Q44. How can you fetch common records from two tables?
You can fetch common records from two tables using INTERSECT. For example:
Databases Training
5(8565)
MYSQL DBA CERTIFICATION TRAINING
MySQL DBA Certification Training
Reviews
5(5182)
4(15708)
5(12541)
5(2665)
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:
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.
Some of the available set operators are – Union, Intersect or Minus operators.
For example-
Scalar functions return a single value based on the input value. For example –
UCASE(), NOW() are calculated with respect to string.
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!
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.
• Scalar Functions
• Inline Table-valued functions
Scalar returns the unit, variant defined the return clause. Other two types of
defined functions return table.
• 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!
AUTO INCREMENT keyword can be used in Oracle and IDENTITY keyword can be
used in SQL SERVER.
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.
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.
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
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.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;
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.
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;
SQL Server-
SELECT getdate();
Oracle-
SELECT SYSDATE FROM DUAL;
Also, we can extract year part from the joining date (using YEAR in
mySQL)-
SELECT * FROM EmployeeDetails
WHERE YEAR(DateOfJoining) = '2020';
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;
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;
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.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.
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.
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
)
Object 2
Answer:
Select Employee_name,Salary/12 as ‘Monthly Salary’ from
employee;
union
minus
15.How Can i create table with same structure with data of Employee
table?
Answer:
Create table Employee1 as select * from Employee;
Intersect
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’);
22.How to fetch all the records from Employee whose joining year is 2017?
Answer:
Oracle:
MS SQL:
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 <>
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
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.
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
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 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 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
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
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
)
• ROW_NUMBER()
• NTILE
• LAG and LEAD
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.
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.
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'
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
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'
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.
ROW_NUMBER()
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'
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.
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).
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
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
The WINDOW clause, if included, should always come after the WHERE clause.
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
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.
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.
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
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.
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):.
Meeting all the requirements of third normal form and it should not
have multi- valued dependencies.
Object 8
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.
• Self-Referencing Relationship.
Object 9
• 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.
• Accent Sensitivity.
Here, st refers to alias name for student table and Ex refers to alias
name for exam table.
Here, we are copying student table to another table with the same
structure with no rows copied.
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.
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
Object 11
• After you set the new password, restart the database in normal mode
and enter the new password.
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.
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.
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-10: What command would select a unique record from the table ?
Explanation:
The “distinct” command. Here’s an example:
Object 13
• Global – are the opposite of local, which means they can be located
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.
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-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