SQL Interview Questions
SQL Interview Questions
SQL vs MySQL
SQL MySQL
Data Definition Language (DDL) – It allows you to perform various operations on the
database such as CREATE, ALTER, and DELETE objects.
Data Manipulation Language(DML) – It allows you to access and manipulate data. It helps
you to insert, update, delete and retrieve data from the database.
Data Control Language(DCL) – It allows you to control access to the database. Example –
Grant and Revoke access permissions.
Q3. What do you mean by DBMS? What are its different types?
A Database Management System (DBMS) is a software application that interacts with the user,
applications, and the database itself to capture and analyze data. A database is a structured
collection of data.
A DBMS allows a user to interact with the database. The data stored in the database can be
modified, retrieved and deleted and can be of any type like strings, numbers, images, etc.
Relational Database Management System: The data is stored in relations (tables). Example –
MySQL.
Non-Relational Database Management System: There is no concept of relations, tuples and
attributes. Example – MongoDB
A relational database management system (RDBMS) is a set of applications and features that allow IT
professionals and others to develop, edit, administer, and interact with relational databases. Most
commercial relational database management systems use Structured Query Language (SQL) to
access the database, which is stored in the form of tables.
RDBMS is the most widely used database system in businesses all over the world. It offers a stable
means of storing and retrieving massive amounts of data.
Databases, in general, hold collections of data that may be accessed and used in other applications.
The development, administration, and use of database platforms are all supported by a database
management system.
The following are some further distinctions between database management systems and relational
database management systems:
Self-join is a type of join that can be used to connect two tables. As a result, it is a unary relationship.
Each row of the table is attached to itself and all other rows of the same table in a self-join. As a
result, self-joining is mostly used to combine and compare rows from the same database table.
The SELECT command gets zero or more rows from one or more database tables or views. SELECT
the most frequent data manipulation language (DML) command in most applications. SELECT queries
define a result set, but not how to calculate it, because SQL is a declarative programming language.
Q7. What are some common clauses used with SELECT query in SQL?
The following are some frequent SQL clauses used in conjunction with a SELECT query:
WHERE clause: In SQL, the WHERE clause is used to filter records that are required depending on
certain criteria.
ORDER BY clause: The ORDER BY clause in SQL is used to sort data in ascending (ASC) or descending
(DESC) order depending on specified field(s) (DESC).
GROUP BY clause: GROUP BY clause in SQL is used to group entries with identical data and may be
used with aggregation methods to obtain summarised database results.
HAVING clause in SQL is used to filter records in combination with the GROUP BY clause. It is
different from WHERE, since the WHERE clause cannot filter aggregated records.
The UNION operator is used to combine the results of two tables while also removing duplicate
entries.
The MINUS operator is used to return rows from the first query but not from the second query.
The INTERSECT operator is used to combine the results of both queries into a single row.
Before running either of the above SQL statements, certain requirements must be satisfied –
Within the clause, each SELECT query must have the same number of columns.
The data types in the columns must also be comparable.
In each SELECT statement, the columns must be in the same order.
After any variable declaration, DECLARE a cursor. A SELECT Statement must always be coupled with
the cursor definition.
To start the result set, move the cursor over it. Before obtaining rows from the result set, the OPEN
statement must be executed.
To retrieve it and go to the next row in the result set, use the FETCH command.
Finally, use the DEALLOCATE command to remove the cursor definition and free up the resources
connected to it.
One-to-One – This is a connection between two tables in which each record in one table
corresponds to the maximum of one record in the other.
One-to-Many and Many-to-One – This is the most frequent connection, in which a record in one
table is linked to several records in another.
Many-to-Many – This is used when defining a relationship that requires several instances on each
side.
Self-Referencing Relationships – When a table has to declare a connection with itself, this is the
method to employ.
Q12. What is OLTP?
OLTP, or online transactional processing, allows huge groups of people to execute massive amounts
of database transactions in real time, usually via the internet. A database transaction occurs when
data in a database is changed, inserted, deleted, or queried.
OLTP stands for online transaction processing, whereas OLAP stands for online analytical processing.
OLTP is an online database modification system, whereas OLAP is an online database query response
system.
Q14. How do I create empty tables with the same structure as another table?
In 1986, a team lead by Computer Science Professor Michael Stonebraker created PostgreSQL under
the name Postgres. It was created to aid developers in the development of enterprise-level
applications by ensuring data integrity and fault tolerance in systems. PostgreSQL is an enterprise-
level, versatile, resilient, open-source, object-relational database management system that supports
variable workloads and concurrent users. The international developer community has constantly
backed it. PostgreSQL has achieved significant appeal among developers because to its fault-tolerant
characteristics.
It’s a very reliable database management system, with more than two decades of community work
to thank for its high levels of resiliency, integrity, and accuracy. Many online, mobile, geospatial, and
analytics applications utilise PostgreSQL as their primary data storage or data warehouse.
SQL Comments are used to clarify portions of SQL statements and to prevent SQL statements from
being executed. Comments are quite important in many programming languages. The comments are
not supported by a Microsoft Access database. As a result, the Microsoft Access database is used in
the examples in Mozilla Firefox and Microsoft Edge.
Single Line Comments: It starts with two consecutive hyphens (–).
Multi-line Comments: It starts with /* and ends with */.
You may use the NVL function to replace null values with a default value. The function returns the
value of the second parameter if the first parameter is null. If the first parameter is anything other
than null, it is left alone.
This function is used in Oracle, not in SQL and MySQL. Instead of NVL() function, MySQL have
IFNULL() and SQL Server have ISNULL() function.
Change, extract, and edit the character string using character manipulation routines. The function
will do its action on the input strings and return the result when one or more characters and words
are supplied into it.
A) CONCAT (joining two or more values): This function is used to join two or more values together.
The second string is always appended to the end of the first string.
B) SUBSTR: This function returns a segment of a string from a given start point to a given endpoint.
C) LENGTH: This function returns the length of the string in numerical form, including blank spaces.
D) INSTR: This function calculates the precise numeric location of a character or word in a string.
E) LPAD: For right-justified values, it returns the padding of the left-side character value.
F) RPAD: For a left-justified value, it returns the padding of the right-side character value.
G) TRIM: This function removes all defined characters from the beginning, end, or both ends of a
string. It also reduced the amount of wasted space.
H) REPLACE: This function replaces all instances of a word or a section of a string (substring) with the
other string value specified.
Q19. Write the SQL query to get the third maximum salary of an employee from a table named
employees.
Employee table
employee_name salary
A 24000
C 34000
D 55000
E 75000
F 21000
G 40000
H 50000
SELECT * FROM(
WHERE r=&n;
Q20. What is the difference between the RANK() and DENSE_RANK() functions?
The RANK() function in the result set defines the rank of each row within your ordered partition. If
both rows have the same rank, the next number in the ranking will be the previous rank plus a
number of duplicates. If we have three records at rank 4, for example, the next level indicated is 7.
The DENSE_RANK() function assigns a distinct rank to each row within a partition based on the
provided column value, with no gaps. It always indicates a ranking in order of precedence. This
function will assign the same rank to the two rows if they have the same rank, with the next rank
being the next consecutive number. If we have three records at rank 4, for example, the next level
indicated is 5.
A table is a collection of data components organized in rows and columns in a relational database. A
table can also be thought of as a useful representation of relationships. The most basic form of data
storage is the table. An example of an Employee table is shown below.
A Record or Row is a single entry in a table. In a table, a record represents a collection of connected
data. The Employee table, for example, has four records.
A table is made up of numerous records (rows), each of which can be split down into smaller units
called Fields(columns). ID, Name, Department, and Salary are the four fields in the Employee table
above.
Q22. What is a UNIQUE constraint?
The UNIQUE Constraint prevents identical values in a column from appearing in two records. The
UNIQUE constraint guarantees that every value in a column is unique.
Self-join is a type of join that can be used to connect two tables. As a result, it is a unary relationship.
Each row of the table is attached to itself and all other rows of the same table in a self-join. As a
result, a self-join is mostly used to combine and compare rows from the same database table.
A SELECT command gets zero or more rows from one or more database tables or views. SELECT the
most frequent data manipulation language (DML) command is SELECT in most applications. SELECT
queries define a result set, but not how to calculate it, because SQL is a declarative programming
language.
Q25. What are some common clauses used with SELECT query in SQL?
The following are some frequent SQL clauses used in conjunction with a SELECT query:
WHERE clause: In SQL, the WHERE clause is used to filter records that are required depending on
certain criteria.
ORDER BY clause: The ORDER BY clause in SQL is used to sort data in ascending (ASC) or descending
(DESC) order depending on specified field(s) (DESC).
GROUP BY clause: GROUP BY clause in SQL is used to group entries with identical data and may be
used with aggregation methods to obtain summarised database results.
HAVING clause in SQL is used to filter records in combination with the GROUP BY clause. It is
different from WHERE, since the WHERE clause cannot filter aggregated records.
The UNION operator is used to combine the results of two tables while also removing duplicate
entries.
The MINUS operator is used to return rows from the first query but not from the second query.
The INTERSECT operator is used to combine the results of both queries into a single row.
Before running either of the above SQL statements, certain requirements must be satisfied –
Within the clause, each SELECT query must have the same amount of columns.
To start the result set, move the cursor over it. Before obtaining rows from the result set, the OPEN
statement must be executed.
To retrieve and go to the next row in the result set, use the FETCH command.
Finally, use the DEALLOCATE command to remove the cursor definition and free up the resources
connected with it.
SQL is a database query language that allows you to edit, remove, and request data from databases.
The following statements are a few examples of SQL statements:
SELECT
INSERT
UPDATE
DELETE
CREATE DATABASE
ALTER DATABASE
SQL skills aid data analysts in the creation, maintenance, and retrieval of data from relational
databases, which divide data into columns and rows. It also enables users to efficiently retrieve,
update, manipulate, insert, and alter data.
The most fundamental abilities that a SQL expert should possess are:
1. Database Management
2. Structuring a Database
3. Creating SQL clauses and statements
4. SQL System SKills like MYSQL, PostgreSQL
5. PHP expertise is useful.
6. Analyze SQL data
7. Using WAMP with SQL to create a database
8. OLAP Skills
A schema is a visual representation of the database that is logical. It builds and specifies the
relationships among the database’s numerous entities. It refers to the several kinds of constraints
that may be applied to a database. It also describes the various data kinds. It may also be used on
Tables and Views.
Schemas come in a variety of shapes and sizes. Star schema and Snowflake schema are two of the
most popular. The entities in a star schema are represented in a star form, whereas those in a
snowflake schema are shown in a snowflake shape.
Any database architecture is built on the foundation of schemas.
Temporary tables are created in TempDB and are erased automatically after the last connection is
closed. We may use Temporary Tables to store and process interim results. When we need to store
temporary data, temporary tables come in handy.
Step 1: Click on SSMS, which will take you to the SQL Server Management Studio page.
Step 2: Moreover, click on the SQL Server Management Studio link and tap on Save File.
Step 3: Save this file to your local drive and go to the folder.
Step 4: The setup window will appear, and here you can choose the location where you want to save
the file.
Step 5: Click on Install.
Step 6: Close the window after the installation is complete.
Step 7: Furthermore, go back to your Start Menu and search for SQL server management studio.
Step 8: Furthermore, double-click on it, and the login page will appear once it shows up.
Step 9: You should be able to see your server name. However, if that’s not visible, click on the drop-
down arrow on the server and tap on Browse.
After that, the SQL server will connect, and Windows 11 will run well.
Q34. What is the case when in SQL Server?
The CASE statement is used to construct logic in which one column’s value is determined by the
values of other columns.
At least one set of WHEN and THEN commands makes up the SQL Server CASE Statement. The
condition to be tested is specified by the WHEN statement. If the WHEN the condition returns TRUE,
the THEN sentence explains what to do.
When none of the WHEN conditions return true, the ELSE statement is executed. The END keyword
brings the CASE statement to a close.
1 CASE
5 ELSE results
6 END;
In summary, the following are the five major distinctions between SQL and NoSQL:
SQL databases have a specified schema and employ structured query language. For unstructured
data, NoSQL databases use dynamic schemas.
NoSQL databases are document, key-value, graph, or wide-column stores, whereas SQL databases
are table-based.
SQL databases excel in multi-row transactions, while NoSQL excels at unstructured data such as
documents and JSON.
BLOB stands for Binary Huge Objects and can be used to store binary data, whereas TEXT may be
used to store a large number of strings. BLOB may be used to store binary data, which includes
images, movies, audio, and applications.
BLOB values function similarly to byte strings, and they lack a character set. As a result, bytes’
numeric values are completely dependent on comparison and sorting.
TEXT values behave similarly to a character string or a non-binary string. The comparison/sorting
of TEXT is completely dependent on the character set collection.
If the SQL table has duplicate rows, the duplicate rows must be removed.
ID Name Age
1 A 21
2 B 23
2 B 23
4 D 22
5 E 25
6 G 26
5 E 25
The following SQL query removes the duplicate ids from the table:
A stored procedure is a piece of prepared SQL code that you can save and reuse again and over.
So, if you have a SQL query that you create frequently, save it as a stored procedure and then call it
to run it.
You may also supply parameters to a stored procedure so that it can act based on the value(s) of the
parameter(s) given.
AS
sql_statement
GO;
EXEC procedure_name;
Black Box Testing is a software testing approach that involves testing the functions of software
applications without knowing the internal code structure, implementation details, or internal routes.
Black Box Testing is a type of software testing that focuses on the input and output of software
applications and is totally driven by software requirements and specifications. Behavioral testing is
another name for it.
SQL Sandbox is a secure environment within SQL Server where untrusted programmes can be run.
There are three different types of SQL sandboxes:
Safe Access Sandbox: In this environment, a user may execute SQL activities like as building stored
procedures, triggers, and so on, but they can’t access the memory or create files.
Sandbox for External Access: Users can access files without having the ability to alter memory
allocation.
Unsafe Access Sandbox: This contains untrustworthy code that allows a user to access memory.
Prior to the introduction of MySQL 5.5 in December 2009, MyISAM was the default storage engine
for MySQL relational database management system versions. It’s based on the older ISAM code, but
it comes with a lot of extra features. Each MyISAM table is split into three files on disc (if it is not
partitioned). The file names start with the table name and end with an extension that indicates the
file type. The table definition is stored in a.frm file, however this file is not part of the MyISAM
engine; instead, it is part of the server. The data file suffix is.MYD (MYData). The index file extension
is.MYI (MYIndex). If you lose your index file, you may always restore it by recreating indexes.
Q43. How to find the nth highest salary in SQL?
The most typical interview question is to find the Nth highest pay in a table. This work can be
accomplished using the dense rank() function.
Employee table
employee_name salary
A 24000
C 34000
D 55000
E 75000
F 21000
G 40000
H 50000
SELECT * FROM(
WHERE r=&n;
A table refers to a collection of data in an organised manner in form of rows and columns. A field
refers to the number of columns in a table. For example:
Table:StudentInformation
Field: Stu Id, Stu Name, Stu Marks
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, as you
can refer to below:
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.
Q46. What is the difference between CHAR and VARCHAR2 datatype in SQL?
Both Char and Varchar2 are used for character datatype but varchar2 is used for character strings of
variable length whereas Char is used for strings of fixed length. For example, char(10) can only store
10 characters and will not be able to store a string of any other length whereas varchar2(10) can
store any length i.e 6,8,2 in this variable.
Constraints in SQL are used to specify the limit on the data type of the table. It can be specified while
creating or altering the table statement. The sample of constraints are:
NOT NULL
CHECK
DEFAULT
UNIQUE
PRIMARY KEY
FOREIGN KEY
DELETE vs TRUNCATE
DELETE TRUNCATE
Delete command is used to delete a row in a Truncate is used to delete all the rows from a
table. table.
You can rollback data after using delete
You cannot rollback data.
statement.
Foreign key maintains referential integrity by enforcing a link between the data in two
tables.
The foreign key in the child table references the primary key in the parent table.
The foreign key constraint prevents actions that would destroy links between the child and
parent tables.
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.
Q53. What is the difference between clustered and non-clustered index in SQL?
The differences between the clustered and non clustered index in SQL are :
1. Clustered index is used for easy retrieval of data from the database and its faster whereas
reading from non clustered index is relatively slower.
2. Clustered index alters the way records are stored in a database as it sorts out rows by the
column which is set to be clustered index whereas in a non clustered index, it does not alter
the way it was stored but it creates a separate object within a table which points back to the
original table rows after searching.
3. One table can only have one clustered index whereas it can have many non clustered
indexes.
In SQL, there is a built-in function called GetDate() which helps to return the current
timestamp/date.
The phase that identifies a plan for the evaluation query with the least estimated cost is known as
query optimization.
The advantages of query optimization are as follows:
Denormalization refers to a technique which is used to access data from higher to lower forms of a
database. It helps database managers to increase the performance of the entire infrastructure as it
introduces redundancy into a table. It adds the redundant data into a table by incorporating
database queries that combine data from various tables into a single table.
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’s 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).
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.
Unique Index:
This index does not allow the field to have duplicate values if the column is unique indexed. If a
primary key is defined, a unique index can be applied automatically.
Clustered Index:
This index reorders the physical order of the table and searches based on the basis of key values.
Each table can only have one clustered index.
Non-Clustered Index:
Non-Clustered Index does not alter the physical order of the table and maintains a logical order of
the data. Each table can have many nonclustered indexes.
Q60. 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 are:
DROP command removes a table and it cannot be rolled back from the database whereas TRUNCATE
command removes all the rows from the table.
There are many successive levels of normalization. These are called normal forms. Each consecutive
normal form depends on the previous one.The first three normal forms are usually adequate.
Normal Forms are used in database tables to remove or decrease duplication. The following are the
many forms:
A relationship is in a second normal form if it meets the first normal form’s requirements and does
not contain any partial dependencies. In 2NF, a relation has no partial dependence, which means it
has no non-prime attribute that is dependent on any suitable subset of any table candidate key.
Often, the problem may be solved by setting a single column Primary Key.
SQL aggregate functions provide information about a database’s data. AVG, for example, returns the
average of a database column’s values.
SQL provides seven (7) aggregate functions, which are given below:
AVG(): returns the average value from the specified columns.
COUNT(): returns the number of table rows, including rows with null values.
MAX(): returns the largest value among the group.
MIN(): returns the smallest value among the group.
SUM(): returns the total summed values(non-null) of the specified column.
FIRST(): returns the first value of an expression.
LAST(): returns the last value of an expression.
Q70. What is the default ordering of data using the ORDER BY clause? How could it be changed?
The ORDER BY clause in MySQL can be used without the ASC or DESC modifiers. The sort order is
preset to ASC or ascending order when this attribute is absent from the ORDER BY clause.
The SQL DISTINCT keyword is combined with the SELECT query to remove all duplicate records and
return only unique records. There may be times when a table has several duplicate records.
The DISTINCT clause in SQL is used to eliminate duplicates from a SELECT statement’s result set.
Q72. What are the syntax and use of the COALESCE function?
From a succession of expressions, the COALESCE function returns the first non-NULL value. The
expressions are evaluated in the order that they are supplied, and the function’s result is the first
non-null value. Only if all of the inputs are null does the COALESCE method return NULL.
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 a 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.
Trigger in SQL is are a special type of stored procedures that are 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.
1. Arithmetic Operators
2. Logical Operators
3. Comparison Operators
Apart from this SQL Interview Questions blog, if you want to get trained by professionals on this
technology, you can opt for structured training from Edureka!
Q76. Are NULL values the same as that of zero or a blank space?
A NULL value is not at all the same as that of zero or a blank space. NULL values represent a value
that is unavailable, unknown, assigned or not applicable whereas a zero is a number and a blank
space is a character.
Q77. What is the difference between cross join and natural join?
The cross join produces the cross product or Cartesian product of two tables whereas the natural
join is based on all the columns having the same name and data types in both the tables.
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 =.
Correlated subquery: These are queries which select the data from a table referenced in the outer
query. This is not considered 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 subquery is
substituted in the main query.
To count the number of records in a table in SQL, you can use the below commands:
Q81. Write a SQL query to find the names of employees that begin with ‘A’?
To display name of the employees that begin with ‘A’, type in the below command:
Q82. Write a SQL query to get the third-highest salary of an employee from employee_table?
2 FROM(
4 FROM employee_table
Group functions work on the set of rows and return one result per group. Some of the commonly
used group functions are: AVG, COUNT, MAX, MIN, SUM, VARIANCE.
Relation or links are between entities that have something to do with each other. Relationships are
defined as the connection between the tables in a database. There are various relationships, namely:
Q85. How can you insert NULL values in a column while inserting the data?
Q86. What is the main difference between ‘BETWEEN’ and ‘IN’ condition operators?
BETWEEN operator is used to display rows based on a range of values in a row whereas the IN
condition operator is used to check for values contained in a specific set of values.
Example of BETWEEN:
This statement allows conditional update or insertion of data into a table. It performs an UPDATE if a
row exists, or an INSERT if the row does not exist.
Recursive stored procedure refers to a stored procedure which calls by itself until it reaches some
boundary condition. This recursive function or procedure helps the programmers to use the same
set of code n number of times.
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.
Apart from this SQL Interview Questions Blog, if you want to get trained by professionals on this
technology, you can opt for a structured training from edureka! Click below to learn more.
Q91. What is the difference between ‘HAVING’ CLAUSE and a “where” clause?
HAVING clause can only be used only with SELECT statement. It is usually used in a GROUP BY clause
and whenever GROUP BY is not used, HAVING behaves like a WHERE clause.
Having Clause is only used with the GROUP BY function in a query whereas WHERE Clause is applied
to each row before they are a part of the GROUP BY function in a query.
Constraints are the representation of a column to enforce data entity and consistency. There are two
levels of a constraint, namely:
Q94. How can you fetch common records from two tables?
You can fetch common records from two tables using INTERSECT. For example:
Select studentID from student. <strong>INTERSECT </strong> Select StudentID from Exam
LOWER: This function returns the string in lowercase. It takes a string as an argument and
returns it by converting it into lower case. Syntax:
LOWER(‘string’)
UPPER: This function returns the string in uppercase. It takes a string as an argument and
returns it by converting it into uppercase. Syntax:
UPPER(‘string’)
INITCAP: This function returns the string with the first letter in uppercase and rest of the
letters in lowercase. Syntax:
INITCAP(‘string’)
Apart from this SQL Interview Questions blog, if you want to get trained by professionals on this
technology, you can opt for a structured training from edureka! Click below to learn more.
Some of the available set operators are – Union, Intersect or Minus operators.
ALIAS command in SQL is the name that can be given to any table or a column. The alias name can
be referred in WHERE clause to identify a particular table or column.
For example-
Select emp.empID, dept.Result from employee emp, department as dept where
emp.empID=dept.empID
In the above example, emp refers to alias name for employee table and dept refers to alias name for
department table.
Aggregate functions are used to evaluate mathematical calculation and returns a single value. These
calculations are done from the columns in a table. For example- max(),count() are calculated with
respect to numeric.
Scalar functions return a single value based on the input value. For example – UCASE(), NOW() are
calculated with respect to string.
You can fetch alternate records i.e both odd and even row numbers. For example- To display even
numbers, use the following command:
Select studentId from (Select rowno, studentId from student) where mod(rowno,2)=0
Select studentId from (Select rowno, studentId from student) where mod(rowno,2)=1
Q100. Name the operator which is used in the query for pattern matching?
You can select unique records from a table by using the DISTINCT keyword.
Q102. How can you fetch the first 5 characters of the string?
There are a lot of ways to fetch characters from a string. For example:
SQL is a query language that allows you to issue a single query or execute a single
insert/update/delete whereas PL/SQL is Oracle’s “Procedural Language” SQL, which allows you to
write a full program (loops, variables, etc.) to accomplish multiple operations such as
selects/inserts/updates/deletes.
A view is a virtual table which consists of a subset of data contained in a table. Since views are not
present, it takes less space to store. View can have data from 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:
A Stored Procedure is a function which consists of many SQL statements to access the database
system. Several SQL statements are consolidated into a stored procedure and execute them
whenever and wherever required which saves time and avoids writing code again and again.
Advantages:
A Stored Procedure can be used as a modular programming which means to create once, store and
call several times whenever it is required. This supports faster execution. It also reduces network
traffic and provides better security to the data.
Disadvantage:
The only disadvantage of Stored Procedure is that it can be executed only in the database and
utilizes more memory in the database server.
Scalar Functions
Inline Table-valued functions
Multi-statement valued functions
Scalar returns the unit, variant defined the return clause. Other two types of defined functions
return table.
Collation is defined as a set of rules that determine how data can be sorted as well as compared.
Character data is sorted using the rules that define the correct character sequence along with
options for specifying case-sensitivity, character width etc.
Apart from this SQL Interview Questions Blog, if you want to get trained by professionals on this
technology, you can opt for structured training from Edureka!
Local variables:
These variables can be used or exist only inside the function. These variables are not used or
referred to by any other function.
Global variables:
These variables are the variables which can be accessed throughout the program. Global variables
cannot be created whenever that function is called.
Autoincrement keyword allows the user to create a unique number to get generated whenever a
new record is inserted into the table.
This keyword is usually required whenever PRIMARY KEY in SQL is used.
AUTO INCREMENT keyword can be used in Oracle and IDENTITY keyword can be used in SQL
SERVER.
Datawarehouse refers to a central repository of data where the data is assembled from multiple
sources of information. Those data are consolidated, transformed and made available for mining as
well as online processing. Warehouse data also has a subset of data called Data Marts.
Q114. What are the different authentication modes in SQL Server? How can it be changed?
Windows mode and Mixed Mode – SQL and Windows. You can go to the steps below to change
authentication mode in SQL Server:
Click Start> Programs> Microsoft SQL Server and click SQL Enterprise Manager to run SQL
Enterprise Manager from the Microsoft SQL Server program group.
Then select the server from the Tools menu.
Select SQL Server Configuration Properties and choose the Security page.
STUFF Function: This function is used to overwrite existing character or inserts a string into another
string. Syntax:
STUFF(string_expression,start, length, replacement_characters)
where,
string_expression: it is the string that will have characters substituted
start: This refers to the starting position
length: It refers to the number of characters in the string which are substituted.
replacement_string: They are the new characters which are injected in the string.
REPLACE function: This function is used to replace the existing characters of all the occurrences.
Syntax:
REPLACE (string_expression, search_string, replacement_string)
Here every search_string in the string_expression will be replaced with the replacement_string.
Q116. How do you add email validation using only one query?
You can use a regular expression within a SQL query to validate an email format. For example, in
MySQL, you can do it like this:
SELECT email
FROM your_table_name
This query selects the email column from your_table_name where the email matches the specified
regular expression pattern for a valid email format.
Replace your_table_name with the name of your table and your_primary_key_column with the
primary key column that defines the order of records. The DESC keyword sorts the records in
descending order, and LIMIT 1 ensures you only get the last record.
1. What is Pattern Matching in SQL?
SQL pattern matching provides for pattern search in data if you have no clue as to what that
word should be. This kind of SQL query uses wildcards to match a string pattern, rather than
writing the exact word. The LIKE operator is used in conjunction with SQL Wildcards to fetch
the required information.
The % wildcard matches zero or more characters of any type and can be used to define
wildcards both before and after the pattern. Search a student in your database with first
name beginning with the letter K:
SELECT *
FROM students
WHERE first_name LIKE 'K%'
Use the NOT keyword to select records that don't match the pattern. This query returns all
students whose first name does not begin with K.
SELECT *
FROM students
WHERE first_name NOT LIKE 'K%'
Search for a student in the database where he/she has a K in his/her first name.
SELECT *
FROM students
WHERE first_name LIKE '%Q%'
The _ wildcard matches exactly one character of any type. It can be used in conjunction with
% wildcard. This query fetches all students with letter K at the third position in their first
name.
SELECT *
FROM students
WHERE first_name LIKE '__K%'
2. How to create empty tables with the same structure as another table?
Creating empty tables with the same structure can be done smartly by fetching the records
of one table into a new table using the INTO operator while fixing a WHERE clause to be
false for all records. Hence, SQL prepares the new table with a duplicate structure to accept
the fetched records but since no records get fetched due to the WHERE clause in action,
nothing is inserted into the new table.
A stored procedure that calls itself until a boundary condition is reached, is called a
recursive stored procedure. This recursive function helps the programmers to deploy the
same set of code several times as and when required. Some SQL programming languages
limit the recursion depth to prevent an infinite loop of procedure calls from causing a stack
overflow, which slows down the system and may lead to system crashes.
DELIMITER $$
CREATE PROCEDURE FetchAllStudents()
BEGIN
SELECT * FROM myDB.students;
END $$
DELIMITER ;
Collation refers to a set of rules that determine how data is sorted and compared. Rules
defining the correct character sequence are used to sort the character data. It incorporates
options for specifying case sensitivity, accent marks, kana character types, and character
width. Below are the different types of collation sensitivity:
OLTP stands for Online Transaction Processing, is a class of software applications capable of
supporting transaction-oriented programs. An important attribute of an OLTP system is its
ability to maintain concurrency. OLTP systems often follow a decentralized architecture to
avoid single points of failure. These systems are generally designed for a large audience of
end-users who conduct short transactions. Queries involved in such databases are generally
simple, need fast response times, and return relatively few records. A number of
transactions per second acts as an effective measure for such systems.
OLAP stands
for Online Analytical
Processing, a class of
software programs
that are characterized by the relatively low frequency of online transactions. Queries are
often too complex and involve a bunch of aggregations. For OLAP systems, the effectiveness
measure relies highly on response time. Such systems are widely used for data mining or
maintaining aggregated, historical data, usually in multi-dimensional schemas.
7. What is OLTP?
OLTP stands for Online Transaction Processing, is a class of software applications capable of
supporting transaction-oriented programs. An essential attribute of an OLTP system is its
ability to maintain concurrency. To avoid single points of failure, OLTP systems are often
decentralized. These systems are usually designed for a large number of users who conduct
short transactions. Database queries are usually simple, require sub-second response times,
and return relatively few records. Here is an insight into the working of an OLTP
system [ Note - The
figure is not important for
interviews ] -
The user-defined functions in SQL are like functions in any other programming language that
accept parameters, perform complex calculations, and return a value. They are written to
use the logic repetitively whenever required. There are two types of SQL user-defined
functions:
Scalar Function: As explained earlier, user-defined scalar functions return a single scalar
value.
Table-Valued Functions: User-defined table-valued functions return a table as output.
o Inline: returns a table data type based on a single SELECT statement.
o Multi-statement: returns a tabular result-set but, unlike inline, multiple SELECT statements
can be used inside the function body.
A UNIQUE constraint ensures that all values in a column are different. This provides
uniqueness for the column(s) and helps identify each row uniquely. Unlike primary key,
there can be multiple unique constraints defined per table. The code syntax for UNIQUE is
quite similar to that of PRIMARY KEY and can be used interchangeably.
A query is a request for data or information from a database table or combination of tables.
A database query can be either a select query or an action query.
Data Integrity is the assurance of accuracy and consistency of data over its entire life-cycle
and is a critical aspect of the design, implementation, and usage of any system which stores,
processes, or retrieves data. It also defines integrity constraints to enforce business rules on
the data when it is entered into an application or a database.
As explained above, the differences can be broken down into three small factors -
Clustered index modifies the way records are stored in a database based on the indexed
column. A non-clustered index creates a separate entity within the table which references
the original table.
Clustered index is used for easy and speedy retrieval of data from the database, whereas,
fetching records from the non-clustered index is relatively slower.
In SQL, a table can have a single clustered index whereas it can have multiple non-clustered
indexes.
A database index is a data structure that provides a quick lookup of data in a column or
columns of a table. It enhances the speed of operations accessing data from a database
table at the cost of additional writes and memory to maintain the index data structure.
There are different types of indexes that can be created for different purposes:
Unique indexes are indexes that help maintain data integrity by ensuring that no two rows
of data in a table have identical key values. Once a unique index has been defined for a
table, uniqueness is enforced whenever keys are added or changed within the index.
Non-unique indexes, on the other hand, are not used to enforce constraints on the tables
with which they are associated. Instead, non-unique indexes are used solely to improve
query performance by maintaining a sorted order of data values that are used frequently.
Clustered indexes are indexes whose order of the rows in the database corresponds to the
order of the rows in the index. This is why only one clustered index can exist in a given table,
whereas, multiple non-clustered indexes can exist in the table.
The only difference between clustered and non-clustered indexes is that the database
manager attempts to keep the data in the database in the same order as the corresponding
keys appear in the clustered index.
Clustering indexes can improve the performance of most query operations because they
provide a linear-access path to data stored in the database.
A self JOIN is a case of regular join where a table is joined to itself based on some relation
between its own column(s). Self-join uses the INNER JOIN or LEFT JOIN clause and a table
alias is used to assign different names to the table within the query.
The SQL Join clause is used to combine records (rows) from two or more tables in a SQL
database based on a related column between the two.
(INNER) JOIN: Retrieves records that have matching values in both tables involved in the join. This is
the widely used join for queries.
SELECT *
FROM Table_A
JOIN Table_B;
SELECT *
FROM Table_A
INNER JOIN Table_B;
LEFT (OUTER) JOIN: Retrieves all the records/rows from the left and the matched records/rows from
the right table.
SELECT *
FROM Table_A A
LEFT JOIN Table_B B
ON A.col = B.col;
RIGHT (OUTER) JOIN: Retrieves all the records/rows from the right and the matched records/rows
from the left table.
SELECT *
FROM Table_A A
RIGHT JOIN Table_B B
ON A.col = B.col;
FULL (OUTER) JOIN: Retrieves all the records where there is a match in either the left or right table.
SELECT *
FROM Table_A A
FULL JOIN Table_B B
ON A.col = B.col;
A FOREIGN KEY comprises of single or collection of fields in a table that essentially refers to
the PRIMARY KEY in another table. Foreign key constraint ensures referential integrity in the
relation between two tables.
The table with the foreign key constraint is labeled as the child table, and the table
containing the candidate key is labeled as the referenced or parent table.
A subquery is a query within another query, also known as a nested query or inner query. It
is used to restrict or enhance the data to be queried by the main query, thus restricting or
enhancing the output of the main query respectively. For example, here we fetch the
contact information for students who have enrolled for the maths subject:
The PRIMARY KEY constraint uniquely identifies each row in a table. It must contain UNIQUE
values and has an implicit NOT NULL constraint.
A table in SQL is strictly restricted to have one and only one primary key, which is comprised
of single or multiple fields (columns).
CREATE TABLE Students ( /* Create table with a single field as primary key */
ID INT NOT NULL
Name VARCHAR(255)
PRIMARY KEY (ID)
);
CREATE TABLE Students ( /* Create table with multiple fields as primary key */
ID INT NOT NULL
LastName VARCHAR(255)
FirstName VARCHAR(255) NOT NULL,
CONSTRAINT PK_Student
PRIMARY KEY (ID, FirstName)
);
Constraints are used to specify the rules concerning data in the table. It can be applied for
single or multiple fields in an SQL table during the creation of the table or after creating
using the ALTER TABLE command. The constraints are:
NOT NULL - Restricts NULL value from being inserted into a column.
CHECK - Verifies that all values in a field satisfy a condition.
DEFAULT - Automatically assigns a default value if no value has been specified for the field.
UNIQUE - Ensures unique values to be inserted into the field.
INDEX - Indexes a field providing faster retrieval of records.
PRIMARY KEY - Uniquely identifies each record in a table.
FOREIGN KEY - Ensures referential integrity for a record in another table.
SQL is a standard language for retrieving and manipulating structured databases. On the
contrary, MySQL is a relational database management system, like SQL Server, Oracle or
IBM DB2, that is used to manage SQL databases.
SQL stands for Structured Query Language. It is the standard language for relational
database management systems. It is especially useful in handling organized data comprised
of entities (variables) and relations between different entities of the data.
RDBMS stands for Relational Database Management System. The key difference here,
compared to DBMS, is that RDBMS stores data in the form of a collection of tables, and
relations can be defined between the common fields of these tables. Most modern database
management systems like MySQL, Microsoft SQL Server, Oracle, IBM DB2, and Amazon
Redshift are based on RDBMS.
DBMS stands for Database Management System. DBMS is a system software responsible for
the creation, retrieval, updation, and management of the database. It ensures that our data
is consistent, organized, and is easily accessible by serving as an interface between the
database and its end-users or application software.
A database is an organized collection of data, stored and retrieved digitally from a remote or
local computer system. Databases can be vast and complex, and such databases are
developed using fixed design and modeling approaches.
SELECT operator in SQL is used to select data from a database. The data returned is stored in
a result table, called the result-set.
28. What are some common clauses used with SELECT query in SQL?
Some common SQL clauses used in conjuction with a SELECT query are as follows:
WHERE clause in SQL is used to filter records that are necessary, based on specific conditions.
ORDER BY clause in SQL is used to sort the records based on some field(s) in ascending (ASC) or
descending order (DESC).
SELECT *
FROM myDB.students
WHERE graduation_year = 2019
ORDER BY studentID DESC;
GROUP BY clause in SQL is used to group records with identical data and can be used in conjunction
with some aggregation functions to produce summarized results from the database.
HAVING clause in SQL is used to filter records in combination with the GROUP BY clause. It is
different from WHERE, since the WHERE clause cannot filter aggregated records.
The UNION operator combines and returns the result-set retrieved by two or more SELECT
statements.
The MINUS operator in SQL is used to remove duplicates from the result-set obtained by the
second SELECT query from the result-set obtained by the first SELECT query and then return
the filtered results from the first.
The INTERSECT clause in SQL combines the result-set fetched by the two SELECT statements
where records from one match the other and then returns this intersection of result-sets.
Certain conditions need to be met before executing either of the above statements in SQL -
Each SELECT statement within the clause must have the same number of columns
The columns must also have similar data types
The columns in each SELECT statement should necessarily have the same order
1. DECLARE a cursor after any variable declaration. The cursor declaration must always be
associated with a SELECT Statement.
2. Open cursor to initialize the result set. The OPEN statement must be called before fetching
rows from the result set.
3. FETCH statement to retrieve and move to the next row in the result set.
4. Call the CLOSE statement to deactivate the cursor.
5. Finally use the DEALLOCATE statement to delete the cursor definition and release the
associated resources.
Entity: An entity can be a real-world object, either tangible or intangible, that can be easily
identifiable. For example, in a college database, students, professors, workers,
departments, and projects can be referred to as entities. Each entity has some associated
properties that provide it an identity.
Relationships: Relations or links between entities that have something to do with each
other. For example - The employee's table in a company's database can be associated with
the salary table in the same database.
One-to-One - This can be defined as the relationship between two tables where each record in one
table is associated with the maximum of one record in the other table.
One-to-Many & Many-to-One - This is the most commonly used relationship where a record in a
table is associated with multiple records in the other table.
Many-to-Many - This is used in cases when multiple instances on both sides are needed for defining
a relationship.
Self-Referencing Relationships - This is used when a table needs to define a relationship with itself.
An alias is represented explicitly by the AS keyword but in some cases, the same can be
performed without it as well. Nevertheless, using the AS keyword is always a good practice.
A view in SQL is a virtual table based on the result-set of an SQL statement. A view
contains rows and columns, just like a real table. The fields in a view are fields from one or
more real tables in the database.
Normalization represents the way of organizing structured data in the database efficiently. It
includes the creation of tables, establishing relationships between them, and defining rules
for those relationships. Inconsistency and redundancy can be kept in check based on these
rules, hence, adding flexibility to the database.
Normal Forms are used to eliminate or reduce redundancy in database tables. The different
forms are as follows:
Students Table
Student Address Books Issued Salutation
Amanora Park Town Until the Day I Die (Emily Carpenter), Inception
Sara Ms.
94 (Christopher Nolan)
Ansh 62nd Sector A-10 The Alchemist (Paulo Coelho), Inferno (Dan Brown) Mr.
As we can observe, the Books Issued field has more than one value per record, and to
convert it into 1NF, this has to be resolved into separate individual records for each book
issued. Check the following table in 1NF form -
Sara Amanora Park Town 94 Until the Day I Die (Emily Carpenter) Ms.
Sara 24th Street Park Avenue Beautiful Bad (Annie Ward) Mrs.
A relation is in second normal form if it satisfies the conditions for the first normal form and
does not contain any partial dependency. A relation in 2NF has no partial dependency, i.e.,
it has no non-prime attribute that depends on any proper subset of any candidate key of the
table. Often, specifying a single column Primary Key is the solution to the problem.
Examples -
Example 1 - Consider the above example. As we can observe, the Students Table in the 1NF
form has a candidate key in the form of [Student, Address] that can uniquely identify all
records in the table. The field Books Issued (non-prime attribute) depends partially on the
Student field. Hence, the table is not in 2NF. To convert it into the 2nd Normal Form, we will
partition the tables into two while specifying a new Primary Key attribute to identify the
individual records in the Students table. The Foreign Key constraint will be set on the other
table to ensure referential integrity.
Students Table (2nd Normal Form)
Here, WX is the only candidate key and there is no partial dependency, i.e., any proper
subset of WX doesn’t determine any non-prime attribute in the relation.
A relation is said to be in the third normal form, if it satisfies the conditions for the second
normal form and there is no transitive dependency between the non-prime attributes, i.e.,
all non-prime attributes are determined only by the candidate keys of the relation and not
by any other non-prime attribute.
Example 1 - Consider the Students Table in the above example. As we can observe, the
Students Table in the 2NF form has a single candidate key Student_ID (primary key) that can
uniquely identify all records in the table. The field Salutation (non-prime attribute),
however, depends on the Student Field rather than the candidate key. Hence, the table is
not in 3NF. To convert it into the 3rd Normal Form, we will once again partition the tables
into two while specifying a new Foreign Key constraint to identify the salutations for
individual records in the Students table. The Primary Key constraint for the same will be set
on the Salutations table to identify each record uniquely.
Salutation_ID Salutation
1 Ms.
2 Mr.
3 Mrs.
A relation is in Boyce-Codd Normal Form if satisfies the conditions for third normal form and
for every functional dependency, Left-Hand-Side is super key. In other words, a relation in
BCNF has non-trivial functional dependencies in form X –> Y, such that X is always a super
key. For example - In the above example, Student_ID serves as the sole unique identifier for
the Students Table and Salutation_ID for the Salutations Table, thus these tables exist in
BCNF. The same cannot be said for the Books Table and there can be several books with
common Book Names and the same Student_ID.
TRUNCATE command is used to delete all the rows from the table and free the space
containing the table.
DROP command is used to remove an object from the database. If you drop a table, all the
rows in the table are deleted and the table structure is removed from the database.
If a table is dropped, all things associated with the tables are dropped as well. This includes -
the relationships defined on the table with other tables, the integrity checks and
constraints, access privileges and other grants that the table has. To create and use the
table again in its original form, all these relations, checks, constraints, privileges and
relationships need to be redefined. However, if a table is truncated, none of the above
problems exist and the table retains its original structure.
The TRUNCATE command is used to delete all the rows from the table and free the space
containing the table.
The DELETE command deletes only the rows from the table based on the condition given in
the where clause or deletes all the rows from the table if no condition is specified. But it
does not free the space containing the table.
Note: All aggregate functions described above ignore NULL values except for the COUNT
function.
A scalar function returns a single value based on the input value. Following are the widely
used SQL scalar functions: