SQL Interview Questions and Answers for Fresher as well as Experienced Database Developers, Database Testers, and Database Administrators.
Selenium Online Training with Project (by G C Reddy)
SQL Syllabus – DDL (Data Definition Language), DML (Data Manipulation Language), and DCL (Data Control Language).
SQL Interview Questions and Answers on Relational Database Management System Fundamentals, SQL Language Fundamentals, and SQL Queries & Subqueries.
SQL Interview Questions and Answers for Freshers & Experienced
1. What is SQL?
SQL – Structured Query Language, an ANSI (American National Standards Institute) Standard language for accessing databases and It was initially developed at IBM in the 1970s.
SQL is the standard language to communicate with relational database management systems like Oracle, MS Access, MS SQL Server, MySQL, DB2, Sybase Etc…
SQL is used to Create New Databases, New Tables in a Database, Insert records in a Database, Update records in a Database, and Delete records in a Database.
SQL is used to retrieve data from a Database, Execute queries against a Database, Create stored procedures in a Database, Create views in a Database, Set permissions on tables, procedures, and views.
2. When did SQL launch?
Structured Query Language was first launched by IBM in 1974 and it is Free Software(anybody can use with free of cost).
3. Who should learn SQL?
• Database Developers
• Database Testers
• Database Administrators
4. What are the Uses of SQL?
• Creating new databases
• Creating new tables in a database
• Inserting records in a database
• Updating records in a database
• Deleting records from a database
• Retrieving data from a database
• Executing queries against a database
• Creating stored procedures in a database
• Creating views in a database
• Setting permissions on tables, procedures, and views
5. What is SQL Process?
When we are executing an SQL command for any RDBMS, the system determines the best way to carry out our request, and the SQL engine figures out how to interpret the task.
There are various components included in the process. These components are Query Dispatcher, Optimization engines, Classic Query Engine and SQL query engine, etc. Classic query engine handles all non-SQL queries but SQL query engine won’t handle logical files.
6. Is SQL support programming?
Basically, SQL is a programming language (Structured Query Language) but no control flow statements in SQL, it is a command-based programming language.
7. What is the difference between SQL, SQL Server, and MySQL?
SQL – Structured Query Language used to manage the relational databases like Oracle, MS SQL Server, MySQL, Sybase, etc,
SQL Server and MySQL are relational database management systems used to store, retrieve, modify and administer a database using SQL.
MS SQL Server is a commercial Database Management System whereas MYSQL is an Open Source software.
8. What are the different subsets of SQL?
The important subsets of SQL are:
i. DDL – Data Definition Language – It allows you to perform various operations on the database such as CREATE, ALTER, and DELETE objects.
ii. DML – Data Manipulation Language – It allows you to access and manipulate data. It helps you to insert, update, delete and retrieve data from the database.
iii. DCL – Data Control Language – It allows you to control access to the database. Example – Grant, Revoke access permissions.
9. 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 DBMS allows a user to interact with the database. The data stored in the database can be modified, retrieved and deleted and can be of any type like strings, numbers, images, etc.
There are two types of DBMS:
Relational Database Management System/SQL Database: The data is stored in relations (tables). Example – Oracle
Non-Relational Database Management System/NoSQL Database: There is no concept of relations. Example – MongoDB
10. What is Database Engine?
Software that stores and retrieves data in a database. It may be a self-contained program or the part of DBMS that performs the storage and retrieval operations.
11. What is the difference between DELETE and TRUNCATE statements?
Delete – Delete is a DML (Data Manipulation Language) command, it is used to delete a row in a table, we can roll back data after using delete statement, and It is slower than truncate statement.
Truncate – Truncate is a DDL (Data Definition Language) command, it is used to delete all the rows from a table, we cannot roll back data, and It is faster.
12. What do you mean by the table, field, and record in SQL?
A table refers to a collection of data in an organized manner in form of rows and columns where the rows are known as records and the columns are known as fields.
13. What are the important SQL language elements?
The important SQL Language elements are:
Names of Database Objects such as Tables, Views, Columns, etc,
2. Data Types:
Define the type of data that is contained by a Column
Symbols that represent specific data types
Perform Arithmetic, Comparison, and Logical Operations
5. Functions: Built-in Functions to perform specific operations
Constituent components of statements and queries.
Produce scalar values, or tables containing columns and rows of data.
Retrieve the data based on specific criteria, this an important element of SQL.
9. Statements Etc…
14. What is Database Server?
Database Management Systems provide Database server functionality, database server provides database services to other computer programs or computers.
15. What is the difference between CHAR and VARCHAR data types in SQL?
Both Char and Varchar are used for characters datatype but varchar is used for character strings of variable length whereas Char is used for strings of fixed length.
It is a datatype in SQL which is used to store character strings of the fixed length specified. If the length of the string is less than set or fixed-length then it is padded with extra blank spaces so that its length became equal to the set length.
It is a datatype in SQL which is used to store character strings of variable length but a maximum of the set length specified. If the length of the string is less than set or fixed-length then it will store as it is without padded with extra blank spaces.
16. What is an Index in SQL? What are the different types of indexes in SQL?
In most SQL projects the data is in millions and billions. Because of the huge volume of the data performance of SQL statements degrades. So there are a lot of different ways to improve the performance of the application, the performance of reports, or the performance of SQL queries.
Definition Of Index:
An index refers to a performance tuning method of allowing faster retrieval of records from the table. An index creates an entry for each value and hence it will be faster to retrieve data.
There are different types of Indexes in SQL:
1. Clustered Index
2. Non-Clustered Index
3. Unique Index
4. Filtered Index
5. Columnstore Index
6. Hash Index
17. What do you mean by data integrity?
Data Integrity defines the accuracy as well as the consistency of the data stored in a database. It also defines integrity constraints to enforce business rules on the data when it is entered into an application or a database.
18. What is a Query in SQL? What are the parameters of SQL Queries?
A query is a question or inquiry about a set of data. We use Structured Query Language (SQL) to retrieve meaningful and relevant information from databases. When building a structure, we pull data from tables and fields.
An SQL query typically includes Query parameter, Column list, Sort list, Options, and Format.
SQL > Select * from employee where department_id=10 and salary>3500
19. What is key in SQL? What are the different types of Keys in SQL?
A Key in DBMS is an attribute or set of attributes that helps you to identify a row(tuple) in a relation(table). They allow you to find the relation between two tables.
different types of Keys in SQL:
1. Super Key – A super key is a group of single or multiple keys which identifies rows in a table.
2. Primary Key – is a column or group of columns in a table that uniquely identifies every row in that table.
3. Candidate Key – is a set of attributes that uniquely identify tuples in a table. Candidate Key is a super key with no repeated attributes.
4. Alternate Key – is a column or group of columns in a table that uniquely identifies every row in that table.
5. Foreign Key – is a column that creates a relationship between two tables. The purpose of Foreign keys is to maintain data integrity and allow navigation between two different instances of an entity.
6. Compound Key – has two or more attributes that allow you to uniquely recognize a specific record. It is possible that each column may not be unique by itself within the database.
7. Composite Key – is a combination of two or more columns that uniquely identify rows in a table. The combination of columns guarantees uniqueness, though individual uniqueness is not guaranteed.
8. Surrogate Key – An artificial key that aims to uniquely identify each record is called a surrogate key. These kinds of keys are unique because they are created when you don’t have any natural primary keys.
20. What is the difference between DROP and TRUNCATE commands?
‘DROP’ command removes a table and it cannot be rolled back from the database whereas the ‘TRUNCATE’ command removes all the rows from the table.
21. What is Normalization and what are the advantages of it?
Normalization in SQL is the process of organizing data to avoid duplication and redundancy. Some of the advantages of Normalization are:
• Better Database organization
• More Tables with smaller rows
• Efficient data access
• Greater Flexibility for Queries
• Quickly find the information
• Easier to implement Security
• Allows easy modification
• Reduction of redundant and duplicate data
• More Compact Database
• Ensure Consistent data after modification
22. What is the ACID property in a database?
ACID stands for Atomicity, Consistency, Isolation, Durability. It is used to ensure that the data transactions are processed reliably in a database system.
Atomicity: Atomicity refers to the transactions that are completely done or failed where transaction refers to a single logical operation of data. It means if one part of any transaction fails, the entire transaction fails and the database state is left unchanged.
Consistency: Consistency ensures that the data must meet all the validation rules. In simple words, you can say that your transaction never leaves the database without completing its state.
Isolation: The main goal of isolation is concurrency control.
Durability: Durability means that if a transaction has been committed, it will occur whatever may come in between such as power loss, crash, or any sort of error.
23. What are Entities and Relationships?
Entities: A person, place, or thing in the real world about which data can be stored in a database. Tables store data that represents one type of entity.
For example – A bank database has a customer table to store customer information. The customer table stores this information as a set of attributes (columns within the table) for each customer.
Relationships: Relation or links between entities that have something to do with each other.
For example – The customer name is related to the customer account number and contact information, which might be in the same table. There can also be relationships between separate tables (for example, customer to accounts).
24. What are joins in SQL?
A JOIN clause is used to combine rows from two or more tables, based on a related column between them. It is used to merge two tables or retrieve data from there.
There are 4 types of joins,
Inner join: Inner Join in SQL is the most common type of join. It is used to return all the rows from multiple tables where the join condition is satisfied.
Left Join: Left Join in SQL is used to return all the rows from the left table but only the matching rows from the right table where the join condition is fulfilled.
Right Join: Right Join in SQL is used to return all the rows from the right table but only the matching rows from the left table where the join condition is fulfilled.
Full Join: Full join returns all the records when there is a match in any of the tables. Therefore, it returns all the rows from the left-hand side table and all the rows from the right-hand side table.
25. What do you mean by “Trigger” in SQL?
Trigger in SQL is a special type of stored procedure that is defined to execute automatically in place or after data modifications. It allows you to execute a batch of code when an insert, update, or any other query is executed against a specific table.
26. Are NULL values the same as that of zero or a blank space?
A NULL value is not at all same as that of zero or a blank space. The NULL value represents a value that is unavailable, unknown, assigned, or not applicable whereas zero is a number and blank space is a character.
27. What is a subquery in SQL?
A subquery is a query inside another query where a query is defined to retrieve data or information back from the database.
In a subquery, the outer query is called as the main query whereas the inner query is called subquery.
Subqueries are always executed first and the result of the subquery is passed on to the main query. It can be nested inside a SELECT, UPDATE or any other query.
A subquery can also use any comparison operators such as >,< or =.
There are two types of subquery namely, Correlated and Non-Correlated.
Correlated subquery: These are queries that 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 to the column in a table.
Non-Correlated subquery: This query is an independent query where the output of the subquery is substituted in the main query.
28. What is the SELECT statement?
SELECT is a SQL command that is used for selecting data from a database. The data which is returned is saved in a result table, called the result-set.
SELECT EMP_ID FROM EMPLOYEE;
Note: In the above SQL statement, ‘EMP_ID’ is a column and ‘EMPLOYEE’ is a Table.
29. What is a relationship and what are they?
Solution:- Relationship in DBMS is the interconnection of the tables within the database. There are various relationships, and they are as follows:
One to One Relationship.
One to Many Relationship.
Many to One Relationship.
30. What is a stored procedure?
A stored procedure is a prepared SQL code that you can save, so the code can be reused over and over again. Stored Procedure is a function that consists of many SQL statements to access the database system.
Stored procedure supports faster execution instead of executing multiple queries. This reduces network traffic and provides better security to the data.
The disadvantage is that it can be executed only in the Database and uses more memory for storage.
31. What is CLAUSE in SQL?
SQL clause helps to limit the result set by providing a condition to the query. A clause helps to filter the rows from the entire set of records.
For example – WHERE, HAVING clause.
32. What is a View? What are Views used for?
A view is a virtual table that consists of a subset of data contained in a table. Since views are not present, it takes less space to store. The view can have data of one or more tables combined and it depends on the relationship.
A view refers to a logical snapshot based on a table or another view.
It is used for the following reasons:
• Restricting access to data.
• Making complex queries simple.
• Ensuring data independence.
• Providing different views of the same data.
33. What is MS Access?
MS Access was launched in 1992 by Microsoft Corporation as part of MS Office.
Microsoft Access is an entry-level database management software. It is not only inexpensive but also a powerful database for small-scale projects.
MS Access uses the Jet database engine which utilizes a specific SQL language dialect (sometimes referred to as Jet SQL).
MS Access comes with the professional edition of MS Office package. MS Access is user-friendly database management system.
34. What is Oracle?
Oracle is a relational database management system developed by ‘Oracle Corporation and launched in 1977.
Oracle supports all major Operating systems including MS Windows. NetWare, UnixWare, OS/2, and most UNIX flavors.
35. What is MS SQL Server?
MS SQL Server is a Relational Database Management System developed by Microsoft Inc. Its primary query languages are T-SQL and ANSI SQL.
36. What is Sybase?
Sybase is a computer software company, their primary product is Sybase DBMS, which is a relational database management system based upon structured query language.
37. What is MySQL?
MySQL is an open-source Database Management System, developed by Swedish company MySQL AB.
MySQL Supports many different platforms including Microsoft Windows, the major Linux distributions, UNIX, and Mac OS X.
MySQL has free and paid versions, depending on its usage (non-commercial/commercial) and features. MySQL comes with a very fast, multi-threaded, multi-user, and robust SQL database server.
38. What is DB2?
DB2 is the short name used for DATABASE 2. It is a relational database product developed by IBM. in 1983
39. What is DB/400?
It is one of the flavors of IBM DB2
40. What are the categories of operators available in SQL?
• Arithmetic operators
• Comparison operators
• Logical operators
41. What are Arithmetic operators in SQL?
|+ (Addition )||Adds values|
|– (Subtraction)||Subtracts Right side value from Left side value|
|* (Multiplication)||Multiplies values on either side of the operator|
|/ (Division)||Divides left hand operand by right hand operand|
|% (Modulus)||Divides left hand operand by right hand operand and returns remainder|
42. What are Comparison operators in SQL?
For example x = 1, y= 2
= (x = y) is False
!= (x != y) is True.
<> (x <> y) is true.
> (x > y) is False
< (x < y) is True
>= (x >= y) is False
<= (x <= y) is True
!< (x !< y) is False
!> (x !> y) is True.Note: Comparison Operators return Logical Results
43. What are Logical operators in SQL?
NOT Returns TRUE if the following condition is FALSE. Returns FALSE if it is TRUE.
AND Returns TRUE if both component conditions are TRUE. Returns FALSE if either is FALSE
OR Returns TRUE if either component condition is TRUE. Returns FALSE if both are FALSE.
44. What is a Data Relationship and What are they?
Database Relationship is the connection between the tables in a database. There are 4 types of relationships, and they are:
• One to One Relationship
• One to Many Relationship
• Many to One Relationship
• Many to Many Relationship
45. What are Important Data Types in SQL?
Note: I used MS SQL Server to practice these DDL Commands.
46. What are the Data Definition Language Commands and Operations?
Important Data Definition Language Commands
Important Data Definition Language Operations
1) Create a Database
2) Use Database
3) Rename a Database
4) Drop Database
5) Create a Table
6) Rename Table
7) Add a Column to exiting Table
8) Add multiple columns to existing Table
9) Modify an existing column
10) Rename a Column
11) Drop a Column
12) Truncate a Table
13) Drop a Table
Note: Download and Install MS SQL Server Express Edition (It is Free Edition) and practice SQL Commands and Operations.
SQL Interview Questions and Answers for Beginners
47. How to Create a Database?
Create Database databaseName;
Create Database gcreddyDB;
48. How to Select a Database?
49. How to Rename a Database?
Alter Database databaseName Modify Name = newdatabseName;
Alter Database gcreddyDB Modify Name = hyderabad
Alter Database gcreddyDB
Modify Name = hyderabad
50. How to Drop a Database?
Drop Database databaseName;
Drop Database gcreddyDB;
51. How to Create a Table?
Create Table tableName
Create Table Students
View Table info
Select * from Students
View Table Schema
Select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = ‘Students’;
52. How to Rename a Table?
EXEC sp_rename ‘old_tablename’, ‘new_tablename’;
EXEC sp_rename ‘Students’, ‘newStudents’;
53. How to Add a Column to an Existing Table?
Alter Table table_name add column_name dataType(size);
Alter Table newStudents add City char(50);
Q. How to Add multiple columns to an Existing Table?
Alter Table table_name add column1_name dataType(size), column2_name dataType(size);
Alter Table table_name add
Alter Table newStudents add add1 char(100), add2 char(70);
Alter Table newStudents add
add5 char (100),
54. How to Modify an existing column?
Alter Table table_name Alter Column column_name dataType(size);
Alter Table newStudents Alter Column add1 varchar(150);
55. How to Rename a Column?
EXEC sp_rename ‘table_name.old_column_name’, ‘new_colum_name’;
ExEC sp_rename ‘newStudents.phone’, ‘mobile’
56. How to Drop a Column?
Alter Table table_name Drop Column column_name;
Alter Table newStudents Drop Column City;
57. How to Truncate a Table?
Truncate Table command is used to delete complete data from an existing table
Truncate Table table_name;
Truncate Table newStudents;
58. How to Drop a Table?
Drop Table command is used to delete complete Table (Data and Table Structure) from the Database.
Drop Table table_name;
Drop Table newStudents;
59. How to add a new record into a Table?
Using INSERT INTO statement, we can insert new rows
INSERT INTO TABLE_NAME (column1, column2, column3,…columnN)
VALUES (value1, value2, value3,…valueN)
60. How to fetch data from a Database Table?
Using SELECT Statement, we can fetch data from a Database Table
SELECT column1, column2, columnN FROM table_name;
SELECT * FROM table_name;
61. Explain about IN Operator?
The IN operator implements comparison to a list of values, that is, it tests whether a value matches any value in a list of values. IN comparisons have the following general format:
value-1 [NOT] IN ( value-2 [, value-3] … )
This comparison tests if value-1 matches value-2 or matches value-3, and so on. It is equivalent to the following logical predicate:
value-1 = value-2 [ OR value-1 = value-3 ] …
62. Explain about FROM Clause in SQL?
The FROM clause always follows the SELECT clause. It lists the tables accessed by the query. For example,
SELECT * FROM s
When the From List contains multiple tables, commas separate the table names. For example,
SELECT sp.*, city
FROM sp, s
When the From List has multiple tables, they must be joined together.
63. What is the parameter substitution symbol used with the INSERT INTO command?
The parameter substitution symbol used with the INSERT INTO command is &.
64. What are the various uses of database triggers?
Database triggers can be used to enforce business rules, maintain derived values, and perform value-based auditing.
65. What is an event handler in SQL?
An event handler is a routine that is written to respond to a particular event.
66. What are the two methods of retrieving SQL?
The two methods of retrieving SQL are
67. What is a synonym? How is it used?
A synonym is used to reference a table or view by another name. The other name can then be written in the application code pointing to test tables in the development stage and to production entities when the code is migrated. The synonym is linked to the AUTHID that created it.
68. What is referential integrity?
Referential integrity refers to the consistency that must be maintained between primary and foreign keys, i.e. every foreign key value must have a corresponding primary key value.
69. Explain the EXPLAIN statement?
The ‘explain‘ statement provides information about the optimizer’s choice of access path of the SQL.
70. How is the SUBSTR keyword used in SQL?
SUBSTR is used for string manipulation with column name, first position and string length used as arguments. E.g. SUBSTR (NAME, 1 3) refers to the first three characters in the column NAME.
71. What is the difference between group by and order by?
Group by controls the presentation of the rows, order by controls the presentation of the columns for the results of the SELECT statement.
72. What is a subselect? Is it different from a nested select?
A subselect is a select that works in conjunction with another select. A nested select is a kind of subselect where the inner select passes to the where criteria for the outer select.
73. What is the use of CASCADE CONSTRAINTS?
When this clause is used with the DROP command, a parent table can be dropped even when a child table exists.
74. How do you prevent output from coming to the screen?
The SET option TERMOUT controls output to the screen. Setting TERMOUT OFF turns off screen output. This option can be shortened to TERM.
75. Can the Primary key be a Foreign Key on the same table?
Yes, the Primary key is a Foreign Key on the same table.
76. How do you execute a host operating system command from within SQL?
By use of the exclamation point “!” (in UNIX and some other OS) or the HOST (HO) command.
77. What is a Cartesian product?
A Cartesian product is the result of an unrestricted join of two or more tables. The result set of a three-table Cartesian product will have x * y * z number of rows where x, y, z correspond to the number of rows in each table involved in the join.
78. How can variables be passed to a SQL routine?
By use of the & symbol. For passing in variables the numbers 1-8 can be used (&1, &2,…,&8) to pass the values after the command into the SQL PLUS session. To be prompted for a specific variable, place the ampersand variable in the code itself: “select * from dba_tables where owner=&owner_name;” . Use of double ampersands tells SQLPLUS to resubstitute the value for each subsequent use of the variable, a single ampersand will cause a reprompt for the value unless an ACCEPT statement is used to get the value from the user.
79. What command is used to get back the privileges offered by the GRANT command?
Revoke command is used to get back the privileges offered by the GRANT command.
80. What are the advantages of procedures?
Advantages of procedures:
• Loaded once and used many times.
• Performance better coz all SQL statements are sent in one go from the application to the database.
• Security (no object privileges are given directly).
• Invoker’s rights are possible.
• Data integrity, productivity.
81. What is Parsing?
Parsing checks syntax checks privileges and allocating Private SQL Area.
82. What is Cursor?
Name or handle to a private SQL area where Oracle parses and fetches query results.
83. What is Datawarehouse?
Datawarehouse is a central repository of data from multiple sources of information. Those data are consolidated, transformed, and made available for mining and online processing. Warehouse data have a subset of data called Data Marts.
84. In what sequence SQL statements are processed?
The clauses of the select are processed in the following sequence
GROUP BY clause
ORDER BY clause
85. Write down the general syntax for a SELECT statement covering all the options.
Here’s the basic syntax: (Also checkout SELECT in books online for advanced syntax)
[GROUP BY group_by__expression]
[ORDER BY order__expression [ASC | DESC] ]
86. What is a correlated subquery?
When a subquery is tied to the outer query. Mostly used in self joins.
87. How to fetch common records from two tables?
Common records result set can be achieved by -.
Select studentID from student INTERSECT Select StudentID from Exam
88. How to select unique records from a table?
Select unique records from a table by using DISTINCT keyword.
Select DISTINCT StudentID, StudentName from Student.
89. Which operator is used in query for pattern matching?
LIKE operator is used for pattern matching, and it can be used as -.
% – Matches zero or more characters.
_(Underscore) – Matching exactly one character.
Select * from Student where studentname like ‘a%’
Select * from Student where studentname like ‘ami_’
90. What are the types of subquery?
There are two types of subquery – Correlated and Non-Correlated.
A correlated subquery cannot be considered as an independent query, but it can refer to the column in a table listed in the FROM the list of the main query.
A Non-Correlated subquery can be considered as an independent query and the output of the subquery is substituted in the main query.
SQL Step by Step Video Tutorial – Full Course