Search

02 October, 2017

SQL Queries


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
EmpId FullName ManagerId DateOfJoining
121 John Snow 321 01/31/2014
321 Abc Xyz 986 01/30/2015
421 Kuldeep Rana 876 27/11/2016
Table - EmployeeSalary
EmpId Project Salary
121 P1 8000
321 P2 1000
421 P1 12000

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 of 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 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, LOCATE(' ',FullName)) FROM EmployeeDetails;

Also, we can use LEFT which returns the left part of a string till specified number of characters.
SELECT LEFT(FullName,LOCATE(' ',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 from EmployeeDetails table who joined in Year 2016.
Ans. Using BETWEEN for the date range '01-01-2016' AND '31-12-2016'-
SELECT * FROM EmployeeSalary
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 EmployeeSalary
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
            )







Top 50 SQL Interview Questions & Answers



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.
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.
 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.
 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.
 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 or OLTP manages transaction based applications which can be used for data entry and easy retrieval processing of data. This processing makes like easier on simplicity and efficiency. It is faster, more accurate results and expenses with respect to OTLP.
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-.

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

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

47. How to fetch alternate records from a table?
Records can be fetched for both Odd and Even row numbers -.
To display even numbers-.

To display odd numbers-.

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.

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

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











80 Most Popular SQL Interview Questions And Answers | Software Testing Material

Most Important SQL Interview Questions And Answers:

SQL knowledge is must for any tester. In this post, we will present most important SQL Interview Questions and Answers before you.
I have segregated this post into two types.
1. General SQL Interview Questions
2. Practical SQL Interview Questions.
Let’s get started with “General SQL Interview Questions”.
General SQL Interview Questions:
1. What is a Database?
A database is a collection of information in organized form for faster and better access, storage and manipulation. It can also be defined as collection of tables, schema, views and other database objects.
2. What is Database Testing?
It is AKA back-end testing or data testing.
Database testing involves in verifying the integrity of data in the front end with the data present in the back end. It validates the schema, database tables, columns, indexes, stored procedures, triggers, data duplication, orphan records, junk records. It involves in updating records in database and verifying the same in the front end.
3. What is the difference between GUI Testing and Database Testing?
  • GUI Testing is AKA User Interface Testing or Front end testing
    Database Testing is AKA back-end testing or data testing.
  • GUI Testing deals with all the testable items that are open to the user to interaction such as Menus, Forms etc.
    Database Testing deals with all the testable items that are generally hidden from the user.
  • The tester who is performing GUI Testing doesn’t need to know Structured Query Language
    The tester who is performing Database Testing needs to know Structured Query Language
  • GUI Testing includes in validating the text boxes, check boxes, buttons, drop-downs, forms etc., majorly the look and feel of the overall application
    Database Testing involves in verifying the integrity of data in the front end with the data present in the back end. It validates the schema, database tables, columns, indexes, stored procedures, triggers, data duplication, orphan records, junk records. It involves in updating records in database and verifying the same in the front end.
4. What is a Table in a Database?
Table is a database object used to store records in a field in the form of columns and rows that holds data.
5. What is a Field in a Database?
Field in a Database table is a space allocated to store a particular record with in a table.
6. What is a Record in a Database?
A record (also called a row of data) is an ordered set of related data in a table.
7. What is a column in a Table?
A column is a vertical entity in a table that contains all information associated with a specific field in a table.
8. What is DBMS?
Database Management System is a collection of programs that enables user to store, retrieve, update and delete information from a database.
9. What is RDBMS?
RDBMS stands for Relational Database Management System. RDBMS is a database management system (DBMS) that is based on the relational model. Data from relational database can be accessed using Structured Query Language (SQL)
10. What are the popular Database Management Systems in the IT Industry?
Oracle, MySQL, Microsoft SQL Server, PostgreSQL, SyBase, MongoDB, DB2, and Microsoft Access etc.,
11. What is SQL?
SQL Overview: SQL stands for Structured Query Language. It is an American National Standard Institute (ANSI) standard. It is a standard language for accessing and manipulating databases. Using SQL, some of the action we could do are to create databases, tables, stored procedures (SP’s), execute queries, retrieve, insert, update, delete data against a database.
12. What are the different types of SQL commands?
SQL commands are segregated into following types:
  • DDL – Data Definition Language
  • DML – Data Manipulation Language
  • DQL – Data Query Language
  • DCL – Data Control Language
  • TCL – Transaction Control Language
13. What are the different DDL commands in SQL?
DDL commands are used to define or alter the structure of the database.
  • CREATE: To create databases and database objects
  • ALTER: To alter existing database objects
  • DROP: To drop databases and databases objects
  • TRUNCATE: To remove all records from a table but not its database structure
  • RENAME: To rename database objects
14. What are the different DML commands in SQL?
DML commands are used for managing data present in the database.
  • SELECT: To select specific data from a database
  • INSERT: To insert new records in a table
  • UPDATE: To update existing records
  • DELETE: To delete existing records from a table
15. What are the different DCL commands in SQL?
DCL commands are used to create roles, grant permission and control access to the database objects.
  • GRANT: To provide user access
  • DENY: To deny permissions to users
  • REVOKE: To remove user access
16. What are the different TCL commands in SQL?
TCL commands are used to manage the changes made by DML statements.
  • COMMIT: To write and store the changes to the database
  • ROLLBACK: To restore the database since a last commit
17. What is an Index?
An index is used to speed up the performance of queries. It makes faster retrieval of data from the table. Index can be created on a one column or a group of columns.
18. What is a View?
View is like a subset of table which are stored logically in a database. A view is a virtual table. It contains rows and columns similar to a real table. The fields in the view are fields from one or more real tables. Views do not contain data of their own. They are used to restrict access to the database or to hide data complexity.

19. What are the advantages of Views?
Some of the advantages of Views are
  1. Views occupy no space
  2. Views are used to simply retrieve the results of complicated queries that need to be executed often.
  3. Views are used to restrict access to the database or to hide data complexity.
20. What is a Subquery ?
A Subquery is a SQL query within another query. It is a subset of a Select statement whose return values are used in filtering the conditions of the main query.

21. What is a temp table?
Ans. A temp table is a temporary storage structure to store the data temporarily.
22. How to avoid duplicating records in a query?
SQL SELECT DISTINCT query is used to return only unique values. It eliminates all the duplicated vales.
View Detailed Post
23. What is the difference between Rename and Alias?
‘Rename’ is a permanent name given to a table or column
‘Alias’ is a temporary name given to a table or column.
24. What is a Join?
Join is a query, which retrieves related columns or rows from multiple tables.
25. What are the different types of joins?
Types of Joins are as follows:
  • INNER JOIN
  • LEFT JOIN
  • RIGHT JOIN
  • OUTER JOIN
26. What is the difference between an inner and outer join?
Inner Join returns rows when there is at least some matching data between two (or more) tables that are being compared.
Outer join returns rows from both tables that include the records that are unmatched from one or both the tables.
27. What are SQL constraints?
SQL constraints are the set of rules that enforced some restriction while inserting, deleting or updating of data in the databases.
28. What are the constraints available in SQL?
Some of constraints in SQL are – Primary Key, Foreign Key, Unique Key, Not Null, Default, Check and Index constraint.
29. What is an Unique constraint?
Unique constraint is used to ensure that there are no duplication values in the field/column.
30. What is a Primary Key?
A PRIMARY KEY constraint uniquely identifies each record in a database table. All columns participating in a primary key constraint must not contain NULL values.
31. Can a table contains multiple PRIMARY KEY’s?
The short answer is no, a table is not allowed to contain multiple primary keys but it allows to have one composite primary key consisting of two or more columns.
32. What is a Composite PRIMARY KEY?
Composite PRIMARY KEY is a primary key created on more than one column (combination of multiple fields) in a table.
33. What is a FOREIGN KEY?
A FOREIGN KEY is a key used to link two tables together. A FOREIGN KEY in a table is linked with the PRIMARY KEY of another table.
34. Can a table contains multiple FOREIGN KEY’s?
A table can have many FOREIGN KEY’s.
35. What is the difference between UNIQUE and PRIMARY KEY constraints?
There should be only one PRIMARY KEY in a table where as there can be any number of UNIQUE Keys.
PRIMARY KEY doesn’t allow NULL values whereas Unique key allows NULL values.
36. What is a NULL value?
A field with a NULL value is a field with no value. A NULL value is different from a zero value or a field that contains spaces. A field with a NULL value is one that has been left blank during record creation. Assume, there is a field in a table is optional and it is possible to insert a record without adding a value to the optional field then the field will be saved with a NULL value.
37. How to Test for NULL Values?
A field with a NULL value is a field with no value. NULL value cannot be compared with another NULL values. Hence, It is not possible to test for NULL values with comparison operators, such as =, <, or <>. For this, we have to use the IS NULL and IS NOT NULL operators.


38. What is a NOT NULL constraint?
NOT NULL constraint is used to ensure that the value in the filed cannot be a NULL

39. What is a CHECK constraint?
CHECK constraint is used to limit the value that are accepted by one or more columns.
E.g. ‘Age’ field should contains only the value greater than 18.

40. What is a DEFAULT constraint?
DEFAULT constraint is used to include a default value in a column when no value is supplied at the time of inserting a record.
41. What is Normalization?
Normalization is the process of table design to minimize the data redundancy. There are different types of Noramalization forms in SQL.
  • First Normal Form
  • Second Normal Form
  • Third Normal Form
  • Boyce and Codd Normal Form
42. What is Stored procedure?
A Stored Procedure is a collection of of SQL statements that has been created and stored in the database to perform a particular task. The stored procedure accepts input parameters and processes them and returns a single values such as a number or text value or a result set (set of rows).
43. What is a Trigger?
A Trigger is a SQL procedure that initiates an action in response to an event (Insert, Delete or Update) occurs. When a new Employee is added in a Employee_Details table, new records will be created in the relevant tables such as Employee_Payroll, Employee_Time_Sheet etc.,
44. Explain SQL Data Types?
In SQL Server, each column in a database table has a name and a data type. We need to decide what type of data to store inside each and every column of a table while creating a SQL table.
View Detailed Post
45. What are the possible values that can be stored in a BOOLEAN data field.
TRUE and FALSE
46. What is the largest value that can be stored in a BYTE data field?
The largest number that can be represented in a single byte is 11111111 or 255. The number of possible values is 256 (i.e. 255 (the largest possible value) plus 1 (zero), or 28).
47. What are Operators available in SQL?
This is one of the most important SQL Interview Questions. SQL Operator is a reserved word used primarily in an SQL statement’s WHERE clause to perform operations, such as arithmetic operations and comparisons. These are used to specify conditions in an SQL statement.
There are are three types of Operators.
  1. Arithmetic Operators
  2. Comparison Operators
  3. Logical Operators
View Detailed Post
48. Which TCP/IP port does SQL Server run?
By default its 1433
49. Describe SQL comments?
Single Line Comments: Single line comments start with two consecutive hyphens (–) and ended by the end of the line
Multi Line Comments: Multi-line comments start with /* and end with */. Any text between /* and */ will be ignored.
50. List out the ACID properties and explain? 
Following are the four properties of ACID. These guarantees that the database transactions are processed reliably.

  • Atomicity
  • Consistency
  • Isolation
  • Durability
51. Define the SELECT INTO statement.
The SELECT INTO statement copies data from one table into a new table. The new table will be created with the column-names and types as defined in the old table. You can create new column names using the AS clause.

52. What is the difference between Delete, Truncate and Drop command?
The difference between the Delete, Truncate and Drop command are
  • Delete command is a DML command, it is used to delete rows from table. It can be rolled back.
  • Truncate is a DDL command, it is used to delete all the rows from the table and free the space containing the table. It cant be rolled back.
  • Drop is a DDL command, it removes the complete data along with the table structure(unlike truncate command that removes only the rows). All the tables’ rows, indexes and privileges will also be removed.
53. What is the difference between Delete and Truncate?
This is one of the most important SQL Interview Questions. The difference between the Delete, Truncate and Drop command are

  • Delete statement is used to delete rows from table. It can be rolled back.
    Truncate statement is used to delete all the rows from the table and free the space containing the table. It cant be rolled back.
  • We can use WHERE condition in DELETE statement and can delete required rows
    We cant use WHERE condition in TRUNCATE statement. So we cant delete required rows alone
  • We can delete specific rows using DELETE
    We can only delete all the rows at a time using TRUNCATE
  • Delete is a DML command
    Truncate is a DDL command
  • Delete maintains log and performance is slower than Truncate
    Truncate maintains minimal log and performance wise faster
  • We need DELETE permission on Table to use DELETE command
    We need at least ALTER permission on the table to use TRUNCATE command
54. What is the difference between Union and Union All command?
This is one of the most important SQL Interview Questions
Union: It omits duplicate records and returns only distinct result set of two or more select statements.
Union All: It returns all the rows including duplicates in the result set of different select statements.
55. What is the difference between Having and Where clause?
Where clause is used to fetch data from database that specifies a particular criteria where as a Having clause is used along with ‘GROUP BY’ to fetch data that meets a particular criteria specified by the Aggregate functions. Where cluase cannot be used with Aggregate functions, but the Having clause can.
56. What are aggregate functions in SQL?
SQL aggregate functions return a single value, calculated from values in a column. Some of the aggregate functions in SQL are as follows
  • AVG() – This functions returns the average value
  • COUNT() – This functions returns the number of rows
  • MAX() – This functions returns the largest value
  • MIN() – This functions returns the smallest value
  • ROUND() – This functions rounds a numeric field to the number of decimals specified
  • SUM() – This functions returns the sum
View Detailed Post
57. What are string functions in SQL?
SQL string functions are used primarily for string manipulation. Some of the widely used SQL string functions are
  • LEN() – It returns the length of the value in a text field
  • LOWER() – It converts character data to lower case
  • UPPER() – It converts character data to upper case
  • SUBSTRING() – It extracts characters from a text field
  • LTRIM() – It is to remove all white space from the beginning of the string
  • RTRIM() – It is to remove all white space at the end of the string
  • CONCAT() – Concatenate function combines multiple character strings together
  • REPLACE() –  To update the content of a string.
View Detailed Post
Now, we see “Practical SQL Interview Questions”.
Practical SQL Interview Questions:
58. How to add a new Employee details in a Employee_Details table with the following details
Employee_Name: John, Salary: 5500, Age: 29?

View Detailed Post
59. How to add a column ‘Salary’ to a table Employee_Details?

View Detailed Post
60. How to change value of the field ‘Salary’ as 7500 for an Employee_Name ‘John’ in a table Employee_Details?

View Detailed Post
61. How to select all records from the table?

View Detailed Post
62. How To Get List of All Tables From A DataBase?
To view the tables available on a particular DataBase

63. Define SQL Delete statement.
The SQL Delete statement is used to delete records from a table.

View Detailed Post
64. Write the command to remove all Players named Sachin from the Players table.

65. How to fetch values from TestTable1 that are not in TestTable2 without using NOT keyword?


By using the except keyword

66. How to get each name only once from a employee table?
By using DISTINCT keyword, we could get each name only once.

67. How to rename a column in the output of SQL query?
By using SQL AS keyword

68. What is the order of SQL SELECT ?
Order of SQL SELECT statement is as follows
SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY.
69. How to display the current date in SQL.
By using below query

70. Write an SQL Query to find an Employee_Name whose Salary is equal or greater than 5000 from the below table Employee_Details.



Syntax:


Output:

71. Write an SQL Query to find list of Employee_Name start with ‘E’ from the below table

Syntax:

Output:

72. Write SQL SELECT query that returns the FirstName and LastName from Employee_Details table. 

73. How to rename a Table?

To rename Table Name & Column Name

74. How to select all the even number records from a table? 
To select all the even number records from a table:

75. How to select all the odd number records from a table? 
To select all the odd number records from a table:

76. What is the SQL CASE statement?
SQL Case statement allows to embed an if-else like clause in the SELECT statement.
77. Can you display the result from the below table TestTable based on the criteria M,m as M and F,f as F and Null as N and g,k,I as U



By using the below syntax we could achieve the output as required.

78. What will be the result of the query below? 

This query will returns “MySQL”. In the above question we could see null = null is no the proper way to compare a null value.
79. What will be the result of the query below? 

This query will returns “SQLServer”.
80. Can you display F as M and M as F from the below table TestTable. 

By using the below syntax we could achieve the output as required.