SQL stands for Structured Query Language. It is used as a programming language for querying Relational Database Management Systems.
In this tutorial, we shall go through the basic and yet most frequently asked SQL Interview Questions.
Examples are provided for the interview questions whenever appropriate and necessary.
SQL Interview Questions
What do you mean by Data, DataBase and DataBase Management Systems?
Data:Any raw entity that represents any facts or details.
DataBase: A DataBase is an organized collection of data.
Database Management Systems: A DBMS is a set of programs that allow the user to create the database and also allow to access, modify, delete the data from a database.
Example: ORACLE SQL SERVER
What is the difference between SQL and SQL server?
SQL: SQL is a Structured Query Language used to communicate with the database.
SQL Server: SQL Server is a Relational Database Management System developed by Microsoft. Its primary function is to store and retrieve data.
What is the difference between DBMS and RDBMS?
DBMS: A DataBase Management System is a program that controls the 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.
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.
What is a key and what are different types of keys?
A key is a single or combination of multiple fields. Its purpose is to access or retrieve data rows from a table according to the requirement. They are also used to create links between different tables.
Types of Keys
- Primary Key: The attribute or combination of attributes that uniquely identifies a row or record in a relation.
- Candidate Key: A relation can have only one primary key. It may contain many fields or combination of fields that can be used as a primary key. One field or combination of fields is used as a primary key. The fields or combination of fields that are not used as primary key are known as candidate key or alternate key.
- Composite key or concatenate key: A primary key that consists of two or more attributes is known as a composite key.
- control key: A field or combination of fields that are used to physically sequence the stored data called sort key. It is also knowns control key.
- superkey: is a combination of attributes that can be uniquely used to identify a database record. A table might have many superkeys. Candidate keys are a special subset of superkeys that do not have any extraneous information in them.
- Foreign Key: A foreign key is an attribute or the combination of an attribute in a relation whose value matches a primary key in another relation. The table in which foreign key is created is called the dependent table. The table to which foreign key is referred is known as parent table.
What is the basic difference between DELETE, DROP and TRUNCATE commands?
DELETE: It is used to remove rows in a table based on WHERE clause. However, the table remains in the database.
DELETE FROM student WHERE name=” brown”;
DROP: DROP command deletes the whole table along with records.
DROP table student;
TRUNCATE: TRUNCATE command is used to remove all rows from the table and free the space for the table but the table structure will be there in the database.
TRUNCATE table student;
Here, student is a table name.
Which query is used to rename a column in a particular table?
RENAME clause is used to rename a column in a table.
Query:
ALTER TABLE student RENAME column pin to pincode;
Here,
pin is the old name of the column in the table student.
pincode is the new name of the column in the table student.
What are the specifying attribute constraints and attribute defaults in SQL?
NOT NULL: This constraint specifies that NULL is not permitted for that particular attribute.
DEFAULT: It is to define a default value for an attribute
CHECK: It is used to restrict the domain of that particular attribute.
Example
CREATE TABLE student(
name varchar(20) not null,
branch char(3) default ‘CSE’,
marks number(3) check (mark>0 AND mark<100));
Here, the name attribute will not take the NULL value as input and the default branch will be CSE and finally, the marks should be in the range 0 to 100.
What is the built-in-function to count the total number of record in the table?
count(*) command is used to get the count of the total number of records in the table.
Count(fieldname) is used to get the count of the total number of records in that perticula field.
Example
SELECT count(*) from student;
SELECT count(name) from student;
Which query is used to display the current date(today’s) date in the system?
SELECT SYSDATE FROM DUAL;
SYSDATE
is the current date on the system.
DUAL
is a predefined table.
What are set operations in SQL?
Set operations:
- UNION
- INTERSECT
- UNION ALL
- MINUS
What is a join clause and what are the types of joins in SQL?
A join clause is used to combine rows from two or more tables, based on a related column between them. There are four types of joins.
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.
What do we need PL/SQL even though we haveSQL?
In SQL, there are no user-defined functions and there is no support for looping and branching statements. So, PL/SQL is introduced.
PL/SQL will enhance the performance by optimizing compiler that can rearrange code for better performance.
What is a cursor?
A cursor is more like a pointer that will point to the context area (i.e the temporary buffer allocated for query execution) which contains active data set. The cursor is useful in traversing such as adding, deleting and retrieving records in a table.
What are cursor attributes?
Cursor attributes are used for cursor manipulations. The cursor attributes are:
- %not found
- %found
- %isopen
- %rowcount
What do you mean by triggers?
Triggers are the predefined procedures that are automatically executed or triggered when an event occurs in the database server. These triggers fire when any valid event is fired, regardless of whether or not any table rows are affected.
Informally, triggers are the specialized form of constraints.
What is normalization and what are different normal forms?
Database Normalization is a technique of organizing the data in the database. By using database normalization, larger tables can be decomposed to smaller tables by eliminating data redundancy(repetition) and insert, update and delete anomalies.
The basic functions of normalization:
- Eliminating data redundancy
- Eliminating insert, update and delete anomalies.
Types of normal forms:
- First Normal Form
- Second Normal Form
- Third Normal Form
- BCNF
- Fourth Normal Form
When do we call a table is in first normal form?
For a table to be in the First Normal Form, it should follow the following rules:
- It should only have a single(atomic) valued attributes/columns.
- Values stored in a column should be of the same domain
- All the columns in a table should have unique names.
- The order in which data is stored does not matter.
When do we call a table is in second normal form?
For a table to be in the Second Normal Form,
- It should be in the First Normal form.
- It should not have Partial Dependency.
Partial dependency: Partial Dependency occurs when a non-prime attribute is functionally dependent on part of a candidate key.
When do we call a table is in third normal form?
For a table to be in the Third Normal Form,
- It is in the Second Normal form.
- It doesn’t have Transitive Dependency.
Transitive dependency: When an indirect relationship causes functional dependency it is called Transitive Dependency.
If A -> B and B -> C is true, then A-> C is a transitive dependency.
When do we calla table is in Boyce and Codd Normal Form (BCNF)?
Boyce and Codd’s Normal Form is a higher version of the Third Normal form. This form deals with a certain type of anomaly that is not handled by 3NF. A 3NF table which does not have multiple overlapping candidate keys is said to be in BCNF. For a table to be in BCNF, the following conditions must be satisfied:
- It must be in 3rd Normal Form
- and, for each functional dependency ( A ? B ), A should be a super Key.
When do we call a table is in Fourth Normal Form (4NF)?
A table is said to be in the Fourth Normal Form when,
- It is in the Boyce-Codd Normal Form.
- And, it doesn’t have Multi-Valued Dependency.
Multivalued-valued dependency: When the existence of one or more rows in a table implies one or more other rows in the same table, then the Multi-valued dependencies occur.
Why do we need indexing?
Indexing optimizes the performance of a database by minimizing the number of disk accesses required when a query is processed.
A database index is a data structure which is used to quickly locate and access the data in a database table.
Through indexing, we can search for data in the database easily.
What is a relationship and what are they?
Database Relationship is defined as the connection between the tables in a database. There are various database relationships, and they are as follows:
- One to One Relationship.
- One to Many Relationship.
- Many to One Relationship.
- Self-Referencing Relationship.
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. a Unique index can be applied automatically when a primary key is defined.
Clustered Index:
This indexing reorders the physical order of the table and searches 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 the logical order of data. Each table can have 999 nonclustered indexes.
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. So, if you have an SQL query to execute again and again, then you save it as a stored procedure, and then just call it to execute.
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.
What are aggregate and scalar functions?
- Aggregate functions are used to evaluate mathematical calculation and return single values and 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.
How do you create an empty table from an existing table?
Example:
SELECT * INTO studentcpy FROM students where 1=2;
Here, we are copying the students table to studentcpy table with no rows copied.
How to select unique records from a table?
DISTINCT keyword is used to select unique records from a table.
Example:
SELECT DISTINCT regno FROM students;
Here, the above query will select the unique records(i.e unique regno) from the table students.
Which operator is used in the 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.
What do you mean by DDL, DML, and DCL in SQL?
- DDL stands for Data Definition Language. SQL queries like CREATE, ALTER, DROP and RENAME come under this.
- DML stands for Data Manipulation Language. SQL queries like SELECT, INSERT and UPDATE come under this.
- DCL stands for Data Control Language. SQL queries like GRANT and REVOKE come under this.
Explain set operations in SQL?
- UNION: This operator is used to combine the results of two tables without duplicate rows.
- UNION ALL: This operator is used to combine the results of two tables with duplicate rows.
- MINUS: This operator is used to return rows from the first table but not from the second query. Matching records of first and second tables and other rows from the first table will be displayed as a result set.
- INTERSECT: This operator is used to return rows returned by both the queries.
What is Collation?
Collation is defined as a 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.
Explain the working of SQL Privileges?
SQL GRANT and REVOKE commands are used to implement privileges in SQL multiple user environments. The administrator of the database can grant or revoke privileges to or from users of database object like SELECT, INSERT, UPDATE, DELETE, ALL etc.
GRANT Command: This command is used to provide database access to user apart from an administrator.
Syntax
GRANT privilege_name
ON object_name
TO {user_name|PUBLIC|role_name}
[WITH GRANT OPTION];
In above syntax WITH GRANT, OPTIONS indicates that the user can grant the access to another user too.
REVOKE Command: This command is used to provide a database to remove access to database objects.
Syntax
REVOKE privilege_name
ON object_name
FROM {user_name|PUBLIC|role_name};
What are Nested Triggers?
Triggers implement data modification logic by using INSERT, UPDATE, and DELETE statement. The triggers that contain data modification logic and find other triggers for data modification are called Nested Triggers.
What is the difference between UNIQUE and PRIMARY KEY constraints?
- A table can have only one PRIMARY KEY whereas there can be any number of UNIQUE keys.
- The primary key cannot contain Null values whereas the Unique key can contain Null values.
What do you mean by SQL Injection?
SQL Injection is a type of database attack technique. In this technique, the entry field of the database will be corrupted by inserting the malicious SQL statements. So, once it is executed then the database will be opened for an attacker. This technique is usually used for attacking Data-Driven Applications to have an access to sensitive data and perform administrative tasks on databases.
Example
SELECT name FROM student WHERE name=”nawab”;
Write an SQL Query to find the name of students whose name Start with ‘M’?
Query:
SELECT * FROM students WHERE studname LIKE ‘M%’;
If we want to find the name of students whose name ends with ‘M’.the query will be
SELECT * FROM students WHERE studname LIKE ‘%M’;
Write an SQL Query to display the current data?
Query:
SELECT GetDate();
What is the difference between the WHERE and HAVING clause?
When GROUP BY is not used, the WHERE and HAVING clauses are essentially equivalent.
However, when GROUP BY is used:
- The WHERE clause is used to filter records from a result. The filtering occurs before any groupings are made.
- The HAVING clause is used to filter values from a group.
Write a query to find a duplicate record in one field and also find the duplicate record with more than one field?
Duplicate records with one field:
SELECT name,COUNT(regno)
FROM students
GROUP BY regno
HAVING COUNT(regno)>1;
Duplicate records with more than one field:
SELECT name,regno,COUNT(*)
FROM students
GROUP BY name, regno
HAVING COUNT(*)>1;
How do we use DISTINCT statement? What is its use?
If the records contain duplicate values then DISTINCT is used to select different values among duplicate records. The DISTINCT statement is used with the SELECT statement.
Query:
SELECT DISTINCT name
FROM students;
What is the difference between nested subqueries and correlated nested subqueries?
Nested subqueries:
A subquery is nested when you are having a subquery in the where or having a clause of another subquery. The innermost subquery will be executed first and then based on its result the next subquery will be executed and based on that result the outer query will be executed.
Query:
SELECT *
FROM result
WHERE regno IN (SELECT regno
FROM students
WHERE courseid = (SELECT courseid
FROM students
WHERE regno = 20));
Correlated Subquery:
A Correlated Subquery is one that is executed after the outer query is executed. So correlated subqueries take an approach opposite to that of normal subqueries.
Query:
SELECT name
FROM studentS
WHERE 5 < (SELECT COUNT (*)
FROM result b
WHERE b.regno = a.regno);
How can you save all changes made by DML statements?
The COMMIT command is the transactional command used to save changes invoked by a transaction to the database. Using COMMIT statement, you can save all changes made by DML statements.
Query:
DELETE FROM students WHERE regno=2;
COMMIT;
How can you undo the transactions that have not already been saved to the database?
The ROLLBACK command is the transactional command used to undo transactions that have not already been saved to the database. This command can only be used to undo transactions since the last COMMIT or ROLLBACK command was issued.
Query:
ROLLBACK;
Is NULL value same as blank space or zero?
A NULL value is not the same as zero or a blank space. A NULL value is a value which is ‘unavailable, unassigned, unknown or not applicable’. Whereas, zero is a number and blank space is a character.
What is the difference between IN and BETWEEN operator in SQL?
IN:
The IN operator allows you to specify multiple values.
Syntax:
SELECT * FROM students
WHERE marks IN (92,85);
Here, we will get the records of the students with marks 92 and 85.
BETWEEN:
The BETWEEN operator selects a range of data between two values.The values may be text or numbers etc.
Syntax:
SELECT * FROM students
WHERE marks BETWEEN 85 AND 92;
Here, we will get records of the students with marks between 85 and 92.
Do the views have data in the table?
No. The views does not contain any data in the table. A view just contains rows and columns, just like a real table but it a virtual table.
What is the difference between GROUP BY and ORDER BY statements?
GROUP BY:
The GROUP BY statement is often used with aggregate functions (COUNT, MAX, MIN, SUM, AVG) to group the result-set by one or more columns.
Query:
SELECT * FROM students
GROUP BY school;
ORDER BY:
The ORDER BY statements is used to sort the result-set in descending or ascending order. The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword explicitly.
Query:
SELECT * FROM students
ORDER BY regno, name;
How will you find the name of the student with the third largest mark in a class?
SELECT name, MAX(mark) AS mark
FROM students
WHERE mark < (SELECT MAX(mark)
FROM students
WHERE mark < (SELECT MAX(mark)
FROM students));
What is the difference between primary key and unique constraints?
A Primary key cannot have a NULL value, the unique constraints can have NULL values. There is only one primary key in a table, but there can be multiple unique constraints.
What are the desirable properties of transactions?
ACID properties are the desirable properties of a transaction.
ATOMICITY: All or none property for recovery subsystems
CONSISTENCY: guarantees that a transaction never aborts your database in a half-finished state.
ISOLATION: keeps transactions separated from each other until they’re finished.
DURABILITY: talks about recovery subsystem. It guarantees that the database will keep track of pending changes in such a way that the server can recover from an abnormal termination.
What are clustered and non-clustered Indexes?
Clustered indexes: It is the index according to which data is physically stored on disk. Therefore, only one clustered index can be created on a given database table.
Non-clustered indexes: Non clustered indexes don’t define the physical ordering of data, but logical ordering. Typically, a tree is created whose leaf point to disk records.
When an explicit cursor needed?
If we need to perform the row by row operations for the result set containing more than one row, then we can unambiguously declares a pointer with a name.
They are managed by OPEN, FETCH and CLOSE.
What are the advantages of Views?
Some of the advantages of Views are:
- Views occupy no space
- Views are used to simply retrieve the results of complicated queries that need to be executed often.
- Views are used to restrict access to the database or to hide data complexity(data security).
- Provides customized vie for users
- Easily maintainable
What is AutoIncrement?
Auto increment keyword allows the user to create a unique number to a record whenever the user inserts a new record into the table.
Mostly this keyword can be used whenever the PRIMARY KEY is used.
What are the advantages and disadvantages of a Stored Procedure?
Advantages:
- used as a modular programming – means create once, store and call for several times whenever required.
- supports faster execution instead of executing multiple queries.
- reduces network traffic and provides better security to the data.
Disadvantages:
- It can be executed only in the Database so, it utilizes more memory in the database server
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.
What is the order of SQL SELECT?
Order of SQL SELECT statement is as follows:
SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY.
What is the SQL CASE statement?
SQL Case statement allows the functionality of an if-else like a clause in the SELECT statement.