Skip to main content

Top SQL Queries asked in Interviews,SQL Interview Questions for Placement and be a Master in Sql(Structured query Language)


 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.
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 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.
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 (3NF):.
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.
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.

Hello friends! in this post we will see some of the most commonly asked SQL queries in interviews. The questions will start from very basic questions and then move to more complex problems. Consider the below two tables for most of the questions asked here.

Table - EmployeeDetails
EmpIdFullNameManagerIdDateOfJoining
121John Snow32101/31/2014
321Walter White98601/30/2015
421Kuldeep Rana87627/11/2016
Table - EmployeeSalary
EmpIdProjectSalary
121P18000
321P21000
421P112000

SQL Query Interview Questions with Answers


Ques.1. Write a 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.2. Write a SQL query to fetch employee names having salary greater than or equal to 5000 and less than or equal 10000.
Ans. Here, we will use BETWEEN in the 'where' clause to return the empId of the employees with salary satifying the required criteria and then use it as subquery to find the fullName of the employee form EmployeeDetails table.
SELECT FullName 
FROM EmployeeDetails 
WHERE EmpId IN 
(SELECT EmpId FROM EmpolyeeSalary 
WHERE Salary BETWEEN 5000 AND 10000);

Ques.3. Write a 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 GROUPBY clause and for sorting, we will use 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.4. Write a query to fetch only the first name(string before space) from the FullName column of 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 LOCATE method in mySQL and CHARINDEX in SQL SERVER and for fetching the string before space, we will use SUBSTRING OR MID method.
mySQL- Using MID
SELECT MID(FullName, 0, LOCATE(' ',FullName)) FROM EmployeeDetails;

SQL Server-Using SUBSTRING
SELECT SUBSTRING(FullName, 0, CHARINDEX(' ',FullName)) FROM EmployeeDetails;

Also, we can use LEFT which returns the left part of a string till specified number of characters.
SELECT LEFT(FullName, CHARINDEX(' ',FullName) - 1) FROM EmployeeDetails;

Ques.5. Write a query to fetch employee names and salary records. Return employee details even if the salary record is not present for the employee.
Ans. Here, we can use left join with EmployeeDetail table on the left side.
SELECT E.FullName, S.Salary  
FROM EmployeeDetails E LEFT JOIN EmployeeSalary S
ON E.EmpId = S.EmpId;

Ques.6. Write a SQL query to fetch all the Employees who are also managers from EmployeeDetails table.
Ans. Here, we have to use Self-Join as the requirement wants us to analyze the EmployeeDetails table as two different tables, each for Employee and manager records.
SELECT DISTINCT E.FullName
FROM EmpDetails E
INNER JOIN EmpDetails M
ON E.EmpID = M.ManagerID;

Ques.7. Write a 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.8. Write a SQL query to fetch duplicate records from a table.
Ans. In order to find duplicate records from table we can use GROUP BY on all the fields and then use HAVING clause to return only those fields whose count is greater than 1 i.e. the rows having duplicate records.
SELECT EmpId, Project, Salary, COUNT(*)
FROM EmployeeSalary
GROUP BY EmpId, Project, Salary
HAVING COUNT(*) > 1;

Ques.9. Write a SQL query to remove duplicates from a table without using temporary table.
Ans. Using Group By and Having clause-
DELETE FROM EmployeeSalary  
WHERE EmpId IN (
SELECT EmpId 
FROM EmployeeSalary       
GROUP BY Project, Salary
HAVING COUNT(*) > 1));

Using rowId in Oracle-
DELETE FROM EmployeeSalary
WHERE rowid NOT IN
(SELECT MAX(rowid) FROM EmployeeSalary GROUP BY EmpId);

Ques.10. Write a SQL query to fetch only odd rows from table.
Ans. This can be achieved by using Row_number in SQL server-
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



Ques.11. Write a SQL query to fetch only even rows from table. Ans. Using the same Row_Number() and checking that the remainder when divided by 2 is 0-
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
Ques.12. Write a SQL query to create a new table with data and structure copied from another table. Ans. Using SELECT INTO command-
SELECT * INTO newTable FROM EmployeeDetails;
Ques.13. Write a SQL query to create an empty table with same structure as some other table. Ans. Using SELECT INTO command with False 'WHERE' condition-
SELECT * INTO newTable FROM EmployeeDetails WHERE 1 = 0;
This can also done using mySQL 'Like' command with CREATE statement-
CREATE TABLE newTable LIKE EmployeeDetails; 
Ques.14. Write a SQL query to fetch common records between two tables. Ans. Using INTERSECT-
SELECT * FROM EmployeeSalary
INTERSECT
SELECT * FROM ManagerSalary
Ques.15. Write a SQL query to fetch records that are present in one table but not in another table. Ans. Using MINUS-
SELECT * FROM EmployeeSalary
MINUS
SELECT * FROM ManagerSalary
Ques.16. Write a SQL query to find current date-time. Ans. mySQL-
SELECT NOW();
SQL Server-
SELECT getdate();
Oracle-
SELECT SYSDATE FROM DUAL;
Ques.17. Write a SQL query to fetch all the Employees details from EmployeeDetails table who joined in Year 2016. Ans. Using BETWEEN for the date range '01-01-2016' AND '31-12-2016'-
SELECT * FROM EmployeeDetails
WHERE DateOfJoining BETWEEN '01-01-2016' AND date '31-12-2016';
Also, we can extract year part from the joining date (using YEAR in mySQL)-
SELECT * FROM EmployeeDetails
WHERE YEAR(DateOfJoining) = '2016';
Ques.18. Write a 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
In Oracle using ROWNUM-
SELECT * FROM (SELECT * FROM EmployeeSalary ORDER BY Salary DESC)
WHERE ROWNUM <= 3;
Ques.19. Write 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.20. Write SQL query to find the 3rd highest salary from table without using TOP/limit keyword. Ans. The below SQL query make use of correlated subquery wherein in order to find the 3rd highest salary the inner query will return the count of till we find that there are two rows that 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
            )

Comments

Popular posts from this blog

सातवें आसमान पर चलना, चल सितारों के जाल पर चलना (Saatvein aasmaan per chalna | Kumar Vishwas | Jashn e rekhta | Wo shayar Badnaam)

Saatvein aasmaan per chalna | Kumar Vishwas | Jashn e rekhta | Wo shayar Badnaam गीत सुनिए, आज पहली बार गा रहा हूं, आपको अच्छा लगा तो ही पूरी दुनिया में गाऊंगा।  सातवें आसमान पर चलना, चल सितारों के जाल पर चलना दिल बिना देवता की काशी है (काशी में शिव हटा दो तो केवल शव रह जाता है), जिसमें हर घाट पर उदासी है  कुछ है चटका हुआ सा मुझमें भी, तू भी कितने जन्म से प्यासी है मेरे अश्कों के ताल पर चलना, सातवें आसमान पर चलना...  जब किसी के आंगन में पुरुषार्थ, विजय, सत्ता, शक्ति, धन, ऐश्वर्य और सामर्थ्य उतारता है, तो घर में बेटे को भेजता है, और जब त्याग, तपस्या, माया, ममता, प्रेम उतराता है तो बेटियों को उतारता है, सुनिए...  यूं रिवायत की आग में जलकर, बंदिशों वाले गांव में पलकर  तूने अनगिनत सितम उठाए हैं, रस्मों-दुनिया की राह पर चलकर  छोड़ अब दिल की चाल पर चलना, सातवें आसमान पर चलना...  तो जानेमन मैं तेरे नाम ये भोपाल लिखता हूं...

लोग कहते हैं मुझे प्यार सिखाना आये, कुमार विश्वास

लोग कहते हैं मुझे प्यार सिखाना आये, मैं जो गा दूँ तो वही सारा ज़माना गाये, फिर भी एक गीत है जो प्राणों में चुपचाप पड़ा, कई जन्मों से मेरे होंठो पे आना चाहे; आखिरी गीत वही मुझसे गवा दे सावन, इश्क बुझता है इसे कुछ तो हवा दे सावन; उसके पैर की एक पायल … उसके पैर की एक पायल ने ही सबको पागल बना रखा है खुदा का शुक्र है कि उसने दोनों पैरों में पायल नही पहनी उनकी ख़ैरो-ख़बर नहीं मिलती / कुमार विश्वास उनकी ख़ैरो-ख़बर नहीं मिलती हमको ही ख़ासकर नहीं मिलती शायरी को नज़र नहीं मिलती मुझको तू ही अगर नहीं मिलती रूह में, दिल में, जिस्म में दुनिया ढूंढता हूँ मगर नहीं मिलती लोग कहते हैं रूह बिकती है मैं जहाँ हूँ उधर नहीं मिलती " नहीं हम में कोई अनबन नहीं है , बस इतना है कि अब वो मन नही है ! मैं अपने आप को सुलझा रहा हूँ , तुम्हें लेकर कोई उलझन नहीं है...!"

25 Simple and Free SEO Tools to Instantly Improve Your Marketing [Updated for 2019](Digital Marketing)

25 Simple and Free SEO Tools To instantly Improve Your Marketing [Updated for 2019] 1.  Google PageSpeed Insights Check the speed and usability of your site on multiple devices Enter a URL, and this tool will test the loading time and performance for desktop and for mobile, plus identify opportunities to improve (and pat you on the back for what you’re doing well). The mobile results also come with a user experience score, grading areas like tap targets and font sizes. Alternatives:  Pingdom ,  WebPageTest , and  GTmetrix 2.  Moz Local Listing Score See how your local business looks online Moz crunches data from more than 10 different sources—including Google, Yelp, and Facebook—to score your brick-and-mortar business on  how it looks online . Results come complete with actionable fixes for inconsistent or incomplete listings. 3.  Keywordtool.io Hundreds of keyword ideas based on a single keyword Enter a keyword, and the Keyword Tool provides a huge