SQL Interview Questions for Freshers
SQL Interview Questions for Freshers
1. What is SQL?
SQL means Structured Query Language and is used to communicate with relational databases. It
proposes a standardized way to interact with databases, allowing users to perform various
operations on the data, including retrieval, insertion, updating, and deletion.
It is a unique identifier for each record in a table. It ensures that each row in the table has a distinct
and non-null value in the primary key column. Primary keys enforce data integrity and create
relationships between tables.
It is a field in one table referencing the primary key in another. It establishes a relationship between
the two tables, ensuring data consistency and enabling data retrieval across tables.
The DELETE command is used by professionals to remove particular rows from a table based on a
condition, allowing you to selectively delete records. TRUNCATE, on the other hand, removes all rows
from a table without specifying conditions. TRUNCATE is faster and uses fewer system resources than
DELETE but does not log individual row deletions.
A JOIN operation merges information from two or more tables by utilizing a common column that
links them together. Various types of JOINs exist, like INNER JOIN, LEFT JOIN, RIGHT JOIN, and FULL
JOIN. These JOIN variations dictate the manner in which data from the involved tables is paired and
retrieved.
A NULL value in SQL represents the absence of data in a column. It is not the same as an empty string
or zero; it signifies that the data is missing or unknown. NULL values can be used in columns with
optional data or when the actual data is unavailable.
9. What is a database?
A database is a systematically organized collection of data arranged into tables composed of rows
and columns. The primary purpose of databases is to efficiently store, manage, and retrieve data.
SQL databases are characterized by their use of structured tables and strict adherence to a
predefined schema, making them ideal for managing structured data with a strong focus on data
consistency and transaction support. In contrast, NoSQL databases are non-relational and excel in
handling unstructured or semi-structured data, frequently employed for scalable, distributed, and
adaptable data storage solutions.
In SQL, a table is a structured data collection organized into rows and columns. Each column in a
table is called a field, representing a specific attribute or property of the data.
The SELECT statement serves the purpose of fetching data from one or multiple tables, enabling you
to specify the desired columns to retrieve, apply filters through the WHERE clause, and manage the
result's sorting using the ORDER BY clause.
A constraint in SQL defines rules or restrictions that apply to data in a table, ensuring data integrity.
Common constraints include:
Normalization is the method used to streamline data storage within a database, reducing
redundancy and enhancing data integrity. This approach entails dividing tables into more
manageable, interrelated tables and establishing connections between them.
The WHERE clause within SQL queries serves the purpose of selectively filtering rows according to
specified conditions, thereby enabling you to fetch exclusively those rows that align with the criteria
you define. For example:
Indexes improve the data retrieval operations speed. They provide a quick way to locate specific rows
in a table by creating a sorted data structure based on one or more columns. Indexes are essential
for optimizing query performance.
The GROUP BY clause organizes rows from a table into groups based on the values in one or more
columns. It is commonly employed alongside aggregate functions like SUM, COUNT, AVG, MIN, and
MAX to perform computations on data that has been grouped together.
An SQL alias serves as a transitory label bestowed upon either a table or a column within a query,
with the primary purpose of enhancing the clarity of query outcomes or simplifying the process of
renaming columns for improved referencing. For example:
The ORDER BY clause is used to sort the result set of a query based on one or more columns. You can
specify each column's sorting order (ascending or descending). For example:
The WHERE clause is employed to restrict individual rows before they are grouped, such as when
filtering rows prior to a GROUP BY operation. Conversely, the HAVING clause is utilized to filter
groups of rows after they have been grouped, like filtering groups based on aggregate values.
An SQL view is essentially a virtual table that derives its data from the outcome of a SELECT query.
Views serve multiple purposes, including simplifying intricate queries, enhancing data security
through an added layer, and enabling the presentation of targeted data subsets to users, all while
keeping the underlying table structure hidden.
A SQL stored procedure comprises precompiled SQL statements that can be executed together as a
unified entity. These procedures are commonly used to encapsulate business logic, improve
performance, and ensure consistent data manipulation practices.
An SQL trigger consists of a predefined sequence of actions that are executed automatically when a
particular event occurs, such as when an INSERT or DELETE operation is performed on a table.
Triggers are employed to ensure data consistency, conduct auditing, and streamline various tasks.
Aggregate functions in SQL perform calculations on a set of values and return a single result.
SUM: To calculate the sum of values in a column.
The UPDATE statement serves the purpose of altering pre-existing records within a table. It involves
specifying the target table for the update, the specific columns to be modified, and the desired new
values to be applied. For example:
A self-join is a type of join where a table is joined with itself. It is useful when creating relationships
within the same table, such as finding hierarchical relationships or comparing rows with related data.
INNER JOIN: Gathers rows that have matching values in both tables.
RIGHT JOIN: Gathers all rows from the right table and any matching rows from the left table.
LEFT JOIN: Gathers all rows from the left table and any matching rows from the right table.
FULL JOIN: Gathers all rows when there's a match in either table, including unmatched rows
from both tables.
Example:
FROM employees
A subquery refers to a query that is embedded within another query, serving the purpose of fetching
information that will subsequently be employed as a condition or value within the encompassing
outer query. For example, to find employees with salaries greater than the average salary:
SELECT name
FROM employees
UNION merges the outcomes of two or more SELECT statements, removing duplicate rows, whereas
UNION ALL merges the results without removing duplicates. While UNION ALL is faster, it may
include duplicate rows.
It is a type of subquery that makes reference to columns from the surrounding outer query. This
subquery is executed repeatedly, once for each row being processed by the outer query, and its
execution depends on the outcomes of the outer query.
ACID - Atomicity, Consistency, Isolation, and Durability. They are essential properties that ensure the
reliability and integrity of database transactions:
A transaction in SQL is a sequence of one or more SQL operations treated as a single unit of work.
Transactions ensure that database operations are either completed successfully or rolled back
entirely in case of failure.
Error handling in SQL is typically achieved using try-catch blocks (in SQL Server) or EXCEPTION blocks
(in Oracle). These blocks allow you to handle and log errors gracefully to prevent application crashes.
In SQL, a cursor is a database element employed for the purpose of fetching and controlling data one
row at a time from a result set. Cursors find frequent application within stored procedures or triggers
when it becomes necessary to process data in a sequential manner.
SQL supports various data types, including numeric, character, date/time, and binary types. Common
data types include INT, VARCHAR, DATE, and BLOB, among others. Data types define the kind of
values a column can hold.
Normalization is the method used to streamline data in a database, decreasing redundancy and
enhancing data integrity. This procedure includes dividing large tables into smaller, interconnected
ones to eliminate duplicated data. Conversely, denormalization is the deliberate act of introducing
redundancy to enhance query performance.
A clustered index in SQL determines the physical order of data rows in a table. Each table can have
only one clustered index, which impacts the table's storage structure. Rows in a table are physically
stored in the same order as the clustered index key.
SQL injection represents a security flaw that arises when SQL queries mishandle untrusted data,
posing a risk of unauthorized access or data tampering. To ward off SQL injection, employ techniques
like parameterized queries, prepared statements, input validation, and the enforcement of stringent
access controls.
In SQL, a database schema functions as a conceptual container for housing various database
elements, such as tables, views, indexes, and procedures. Its primary purpose is to facilitate the
organization and segregation of these database elements while specifying their structure and
interconnections.
Data integrity in SQL is ensured through various means, including constraints (e.g., primary keys,
foreign keys, check constraints), normalization, transactions, and referential integrity constraints.
These mechanisms prevent invalid or inconsistent data from being stored in the database.
SQL injection is a cybersecurity attack method that involves the insertion of malicious SQL code into
an application's input fields or parameters. This unauthorized action enables attackers to illicitly
access a database, extract confidential information, or manipulate data.
You use the CREATE PROCEDURE statement to create a stored procedure in SQL. A stored procedure
can contain SQL statements, parameters, and variables. Here's a simple example:
AS
BEGIN
END;
A deadlock in SQL occurs when two or more transactions cannot proceed because they are waiting
for resources held by each other. Deadlocks can be prevented or resolved by using techniques such
as locking hierarchies, timeouts, or deadlock detection and resolution mechanisms.
72. Discuss the concept of NoSQL databases and their interaction with SQL.
NoSQL databases are non-relational databases designed for handling large volumes of unstructured
or semi-structured data. They interact with SQL databases through various integration methods, such
as data pipelines, ETL processes, and API-based data transfers.
A spatial database stores and queries geometric and geographic data, such as maps, GPS
coordinates, and spatial objects. It provides specialized functions and indexing methods to support
spatial queries and analysis.