SQL Interview Questions 1685537248
SQL Interview Questions 1685537248
Questions
IMPORTANT QUESTIONS IN SQL ?
1. What is the difference between SQL and MySQL?
2. What are the different subsets of SQL?
3. What do you mean by DBMS? What are its different types?
4. What do you mean by table and field in SQL?
5. What are joins in SQL?
6. What is the difference between CHAR and VARCHAR2
datatype in SQL?
7. What is the Primary key?
8. What are Constraints?
9. What is the difference between DELETE and TRUNCATE statements?
10. What is a Unique key?
SQL vs MySQL
SQL MySQL
SQL is the core of the relational database which is MySQL is an RDMS (Relational Database
used for accessing and managing database Management System) such as SQL Server,
Informix etc.
Q2. What are the different subsets of SQL?
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,
Revoke access permissions.
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
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.
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.
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.
ATUL KUMAR (LINKEDIN) 3
Q10. List the different types of relationships in SQL.
There are different types of relations in the database:
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
sides.
Self-Referencing Relationships – When a table has to declare a connection with itself, this is the
method to employ.
Q14. How to create empty tables with the same structure as another table?
To create empty tables:
Using the INTO operator to fetch the records of one table into a new table while setting a WHERE
clause to false for all entries, it is possible to create empty tables with the same structure. As a
result, SQL creates a new table with a duplicate structure to accept the fetched entries, but
nothing is stored into the new table since the WHERE clause is active.
This function is used in Oracle, not in SQL and MySQL. Instead of NVL() function, MySQL have
IFNULL() and SQL Server have ISNULL() function.
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
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 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.
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 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.
SELECT
INSERT
UPDATE
DELETE
CREATE DATABASE
ALTER DATABASE
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.
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 good.
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 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.
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.
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’s suffix is.MYD (MYData). The index file’s
extension is.MYI (MYIndex). If you lose your index file, you may always restore it by recreating
indexes.
employee_name salary
A 24000
C 34000
D 55000
E 75000
F 21000
G 40000
H 50000
SELECT * FROM(
WHERE r=&n;
Table: StudentInformation
Field: Stu Id, Stu Name, Stu Marks
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 characters 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.
NOT NULL
CHECK
DEFAULT
UNIQUE
PRIMARY KEY
FOREIGN KEY
DELETE vs TRUNCATE
DELETE TRUNCATE
Delete command is used to delete a row in a table. Truncate is used to delete all the rows from a table.
You can rollback data after using delete statement. You cannot rollback data.
Apart from this SQL Interview Questions blog, if you want to get trained from professionals on this
technology, you can opt for structured training from edureka!
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.
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 index.
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).
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.
Apart from this SQL Interview Questions Blog, if you want to get trained from professionals on this
technology, you can opt for structured training from edureka!
Normal Forms are used in database tables to remove or decrease duplication. The following are
the many forms:
A relation is in 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.
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.
Q64. How to create empty tables with the same structure as another table?
Using the INTO operator to fetch the records of one table into a new table while setting a WHERE
clause to false for all entries, it is possible to create empty tables with the same structure. As a
result, SQL creates a new table with a duplicate structure to accept the fetched entries, but
nothing is stored into the new table since the WHERE clause is active.
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 */.
Q67. 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.
ATUL KUMAR (LINKEDIN) 17
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.
SQL injection is a sort of flaw in website and web app code that allows attackers to take control of
back-end processes and access, retrieve, and delete sensitive data stored in databases. In this
approach, malicious SQL statements are entered into a database entry field, and the database
becomes exposed to an attacker once they are executed. By utilising data-driven apps, this
strategy is widely utilised to get access to sensitive data and execute administrative tasks on
databases. SQLi attack is another name for it.
Getting access to secret data in order to change a SQL query to acquire the desired results.
UNION attacks are designed to steal data from several database tables.
Examine the database to get information about the database’s version and structure
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:
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.
ATUL KUMAR (LINKEDIN) 18
The syntax of COALESCE function is COALESCE (exp1, exp2, …. expn)
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.
Want to upskill yourself to get ahead in your career? Check out this video in this SQL Interview Questions
Q74. What do you mean by “Trigger” in SQL?
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 from professionals on this
technology, you can opt for structured training from edureka!
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.
Correlated subquery: These are queries which 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 the
column in a table.
Apart from this SQL Interview Questions Blog, if you want to get trained from professionals on this
technology, you can opt for structured training from edureka!
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?
1 SELECT TOP 1 salary
2 FROM(
3 SELECT TOP 3 salary
4 FROM employee_table
Q85. How can you insert NULL values in a column while inserting the data?
NULL values in SQL can be inserted in the following ways:
Example of BETWEEN:
SELECT * FROM Students where ROLL_NO BETWEEN 10 AND 50;
Example of IN:
Apart from this SQL Interview Questions Blog, if you want to get trained from professionals on this
technology, you can opt for a structured training from edureka! Click below to know more.
Q91. What is the difference between ‘HAVING’ CLAUSE and a ‘WHERE’ CLAUSE?
HAVING clause can 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.
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 from professionals on this
technology, you can opt for a structured training from edureka! Click below to know more.
For example-
Scalar functions return a single value based on the input value. For example – UCASE(), NOW()
are calculated with respect to string.
Select studentId from (Select rowno, studentId from student) where mod(rowno,2)=0
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.
Apart from this SQL Interview Questions Blog, if you want to get trained from professionals on this
technology, you can opt for structured training from edureka!
Global variables:
These variables are the variables which can be accessed throughout the program. Global variables
cannot be created whenever that function is called.
AUTO INCREMENT keyword can be used in Oracle and IDENTITY keyword can be used in SQL
SERVER.
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 below steps 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.
REPLACE function: This function is used to replace the existing characters of all the occurrences. Syntax:
https://www.linkedin.com/in/atul3