SQL Interview Questions for Freshers - CodeInQueries
1. What is SQL?
SQL (Structured Query Language) is a programming language used to manipulate
and manage data in relational databases. SQL is used to communicate and connect
with a database to create, modify, retrieve, and delete data.
Some everyday tasks performed using SQL include creating tables and views,
inserting and updating data, selecting specific data from tables, and deleting data
from tables.
2. What is a database?
A database is an organized collection of structured information or data, typically
stored electronically in a computer system. It allows users to store, manage, retrieve,
and update data efficiently through database management systems (DBMS).
3. What is a primary key, and why is it important in a
database?
A primary key is a crucial component of a Database as it serves as a unique
identifier in a table for each record. The primary key enables efficient data retrieval
and manipulation while ensuring data integrity by preventing duplicate entries.
Using a primary key, a database management system can quickly locate and
retrieve data from a table without scanning the entire table. This makes data retrieval
more efficient, especially in large databases with many records. Additionally, primary
keys allow for the easy creation of relationships between tables, simplifying complex
queries and making database maintenance easier.
4. What is a foreign key, and how is it different from a
primary key?
A foreign key is a database constraint that establishes a link between two tables in a
relational database. It is used to maintain referential integrity. It is a field or set of
fields in one table that also refers to the primary key of another table. It differs from a
primary key in that it does not have to be unique and can be used to establish
relationships between tables.
5. What is the difference between a LEFT JOIN and a RIGHT
JOIN in SQL?
In SQL, a LEFT JOIN and a RIGHT JOIN are both types of outer join that can be
used to combine data from two or more tables. The difference between them lies in
which table's data is preserved if there is no matching data in the other table.
In a LEFT JOIN, all the rows from the table on the left-hand side of the JOIN
keyword (the "left table") are included in the result set, even if there is no
matching data in the table on the right-hand side (the "right table").
In the Right JOIN, all the rows from the table on the right-hand side of the JOIN
keyword (the "right table") are included In the result set, even if there is no
matching data in the left table.
In summary, the difference between a LEFT JOIN and a RIGHT JOIN is the table
whose data is preserved when there is no match in the other table.
6. How would you retrieve all the records from a "
customers " table in SQL?
Ans: To retrieve all the records from a table called "customers" in SQL, you would
use the following query:
SELECT * FROM customers;
7. What is a subquery, and how is it used in SQL?
A subquery is a query that is embedded within another query. It retrieves data used
in the main query as a filter or a condition.
Syntax:
SELECT column1, column2
FROM table1
WHERE column3 IN (SELECT column3 FROM table2 WHERE condition);
8. What is the difference between SQL's WHERE and
HAVING clauses?
In SQL, the WHERE clause is used to filter rows based on a condition on a column,
while the HAVING clause is used to filter groups based on an aggregate function.
The WHERE clause is applied before any grouping takes place and filters individual
rows based on a condition. On the other hand, the HAVING clause is applied after
the grouping and filter groups based on the results of aggregate functions such as
COUNT, SUM, AVG, etc.
9. What is the difference between a function and a stored
procedure in SQL?
In SQL, a function returns a value, while a stored procedure does not necessarily
return a value and may execute a series of operations or tasks. Functions can be
used as part of a SQL statement or expression to return a value. In contrast, stored
procedures can be used to encapsulate a series of SQL statements and can be
executed as a single unit. Additionally, functions can be used within stored
procedures, but stored procedures cannot be used within functions.
10. Write a SQL query to find the second-highest salary
from an employee table.
Assuming we have the following "employees" table:
CREATE TABLE employees (
id INT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
salary INT
);
INSERT INTO employees (id, name, salary) VALUES (1, 'Sangeeta', 100000);
INSERT INTO employees (id, name, salary) VALUES (2, 'Ranjita', 150000);
INSERT INTO employees (id, name, salary) VALUES (3, 'Anita', 70000);
INSERT INTO employees (id, name, salary) VALUES (4, 'Sunita', 50000);
INSERT INTO employees (id, name, salary) VALUES (5, 'Anjeeta', 90000);
SELECT MAX(salary) as second_highest_salary
FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees)
Output:
11. What is the purpose of an index in SQL, and how
does it work?
An index is used to improve the performance of queries by allowing for faster data
retrieval. It creates a separate data structure that stores the values of one or more
columns and allows faster access to the data based on those values.
12. What is the difference between NOSQL and SQL?
SQL NOSQL
It is a relational data model. It is a non-relational data model.
Vertical scaling is more common. Supports horizontal scaling.
Handles structured data. Handles large and unstructured data.
Fixed schema structure. Flexible structure.
Schema-based. Schema-less.
13. Write a SQL query to find the names of employees
who have not been assigned to any project.
We have created an Employee table and a Project table
CREATE TABLE employees (
employee_id INT PRIMARY KEY,
name VARCHAR(50)
);
INSERT INTO employees (employee_id, name)
VALUES
(1, 'Raghav'),
(2, 'Raashi'),
(3, 'Rohan'),
(4, 'Mohan');
CREATE TABLE projects (
project_id INT PRIMARY KEY,
name VARCHAR(50),
employee_id INT,
FOREIGN KEY (employee_id) REFERENCES employees(employee_id)
);
INSERT INTO projects (project_id, name, employee_id)
VALUES
(1, 'Project A', 1),
(2, 'Project B', 2),
(3, 'Project C', 1),
(4, 'Project D', 3);
SELECT [Link]
FROM employees
LEFT JOIN projects
ON employees.employee_id = projects.employee_id
WHERE projects.employee_id IS NULL;
Output:
Explanation:
This is because the employee Mohan has not been assigned to any project, as there
are no corresponding rows in the "projects" table with their respective employee
IDs. The rest have been assigned to at least one project, so they are not included in
the output.
14. In the Student table, the marks column contains a
list of values separated by commas. How can you
determine the number of values in this comma-separated
list?
CREATE TABLE Student (
id INT NOT NULL,
name VARCHAR(50) NOT NULL,
marks VARCHAR(255) NOT NULL,
PRIMARY KEY (id)
);
INSERT INTO Student (id, name, marks)
VALUES (1, 'Rohit', '87,92,76,89');
SELECT id, name, marks, LENGTH(marks) - LENGTH(REPLACE(marks, ',', '')) + 1
AS num_marks
FROM Student
WHERE id = 1;
Output:
15. State the difference between cross-join and natural
join.
Features CROSS JOIN NATURAL JOIN
Returns the Cartesian product of Joins two tables based on
the two tables, meaning every columns with the same name,
Definition row from the first table is producing a result set with only
combined with every row from one column for each pair of
the second table. same-named columns.
SELECT * FROM table1 SELECT * FROM table1
Syntax
CROSS JOIN table2; NATURAL JOIN table2;
Join Joins every row of the first table Joins the two tables based on
Condition to every row of the second table. columns with the same name.
Rows where the values in
Resulting Total rows in table1 multiplied
columns with the same name are
Rows by total rows in table2.
equal.
More efficient than CROSS
It can be slow for large tables,
Performance JOIN but may require
generates Cartesian product.
specifying columns explicitly.
Used when no columns exist to Used when two tables have at
join tables or when you want all least one column with the same
Usage
possible combinations of rows name, and you want to join
from the two tables. them based on that column.
16. List the different types of relationships in SQL.
In SQL, there are four main types of relationships:
One-to-One (1:1) Relationship: In this type of relationship, each record in the
first table is associated with only one record in the second table, and vice versa.
This is typically used when the two tables have a common attribute or key, and
the second table contains additional information about the first table.
One-to-Many (1:N) Relationship: In this type of relationship, each record in the
first table can be associated with multiple records in the second table, but each
record in the second table is associated with only one record in the first table.
This is used when one record in the first table can have multiple related records
in the second table.
Many-to-One (N:1) Relationship: This is the inverse of the one-to-many
relationship. In this type of relationship, each record in the second table can be
associated with multiple records in the first table, but each record in the first
table is associated with only one record in the second table. This is used when
multiple records in the second table are related to one record in the first table.
Many-to-Many (N:N) Relationship: In this type of relationship, each record in
the first table can be associated with multiple records in the second table and
vice versa. This requires the use of an intermediary table, often called a junction
table, which contains foreign keys to both the first and second tables. This is
used when multiple records in each table can be related to multiple records in
the other table.
17. What are Tables and Fields?
In a relational database, a table is a collection of data organized in rows and
columns. Tables are used to store and manage data in a structured way, with each
row representing a unique record and each column representing specific information
about the record. Tables are often named according to the type of data they contain,
such as "customers", "orders", or "employees".
A field, also known as a column or an attribute, is a single information stored in a
table. Each field is named and has a specific data type, such as text, number, date,
or Boolean, that determines the type of data that can be stored in the field. For
example, a "customers" table might have fields for the customer's name, address,
phone number, and email address.
Fields can also have other properties, such as a maximum length or a default value,
that define how the data is stored and how it can be used. In addition, fields can be
used to define relationships between tables by referencing the primary key of
another table or by creating foreign keys that link related records across different
tables.
Tables Fields
customer's customer_id, name, email, phone, and address.
orders order_id, customer_id, order_date, total_amount.
products product_id, name, description, price, quantity.
employees employee_id, first_name, last_name, job_title, hire_date.
Together, tables and fields form the basic building blocks of a relational database,
providing a flexible and powerful way to store, manage, and query large amounts of
data in a structured and organized way.
18. What is the difference between the SQL statements
DELETE and TRUNCATE?
Statement DELETE TRUNCATE
DELETE FROM table_name
Syntax TRUNCATE TABLE table_name;
WHERE condition;
Deletes specific rows that match
Functionality Removes all rows from the table.
the WHERE condition.
Auto- Does not reset auto-increment Resets auto-increment values to their
increment values. starting value.
It can be rolled back within a It cannot be rolled back within a
Transaction
transaction. transaction.
Logs, each row deletion, can be It does not log individual row deletions but
Logging
slower for large tables. can be faster for large tables.
Requires to DELETE privileges Requires to DROP and CREATE
Access
on the table. privileges on the table.
19. How should data be structured to support Join
Operations in a one-to-many relationship?
In a one-to-many relationship, where one record in the primary table is related to
many records in the related table, the data should be structured in a way that
supports efficient join operations.
A practical method to establish a relationship between two tables is to utilize a
foreign key column within the related table that points to the primary key column in
the primary table. This allows the database to quickly locate all the related records
for a given primary record.
Consider two tables
CREATE TABLE customers_Table (
customer_id INT PRIMARY KEY,
name VARCHAR(50),
email VARCHAR(100)
);
INSERT INTO customers_Table (customer_id, name, email)
VALUES (1, 'Pallavi Tiwari', 'Pallo@[Link]');
INSERT INTO customers_Table (customer_id, name, email)
VALUES (2, 'Muskan Sharma', 'Muskan@[Link]');
INSERT INTO customers_Table (customer_id, name, email)
VALUES (3, 'Raashi Batla', 'Raashi@[Link]');
CREATE TABLE orders_Table (
order_id INT PRIMARY KEY,
customer_id INT,
order_date DATE,
total_amount DECIMAL(10, 2),
FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
);
INSERT INTO orders_Table(order_id, customer_id, order_date, total_amount)
VALUES (101, 1, '2023-01-05', 100.00);
INSERT INTO orders_Table (order_id, customer_id, order_date, total_amount)
VALUES (102, 1, '2023-02-12', 50.00);
INSERT INTO orders_Table (order_id, customer_id, order_date, total_amount)
VALUES (103, 2, '2023-02-18', 200.00);
INSERT INTO orders_Table (order_id, customer_id, order_date, total_amount)
VALUES (104, 3, '2023-01-25', 75.00);
In this example, the table name customer_Table has a primary key column called
"customer_id", a unique identifier for each customer. The orders_Table has a foreign
key column called "customer_id", which references the customer_id column in the
customers_Table. This establishes a one-to-many relationship between customers
and orders: each can have multiple orders, but each order is associated with a single
customer.
To retrieve a list of all customers and their associated orders, you could use a SQL
statement like this:
SELECT customers_Table.customer_id, customers_Table.name, orders_Table.orde
r_id, orders_Table.order_date, orders_Table.total_amount
FROM customers_Table
LEFT JOIN orders_Table ON customers_Table.customer_id =
orders_Table.customer_id;
This statement uses a LEFT JOIN operation to include all records from the
customers_Table, and any matching records from the orders_Table. The ON clause
specifies the join condition, which matches records in the orders table with the
corresponding customer records based on the customer_id column.
Output:
As you can see, this query combines the data from both tables, showing the
customer and order information together in a single result set.
20. What is a transaction in SQL, and why is it
important?
In SQL, a transaction is a logical unit of work consisting of one or more SQL
statements executed as a single atomic operation. The primary purpose of a
transaction is to ensure that a group of SQL statements is executed as a single,
consistent, and reliable unit.
When a transaction is initiated, a set of SQL statements are executed, and the
changes made to the database are temporarily stored in a buffer area called a
transaction log. If all the SQL statements in the transaction are executed
successfully, the changes made to the database are committed, which means they
are made permanent.
If any error occurs during the transaction, all changes made to the database are
rolled back, and the database is restored to its original state before the
transaction starts.
The importance of transactions in SQL is maintaining the consistency, reliability,
and integrity of the data in the database. Transactions help to ensure that the
database is always in a valid state and that data is not lost or corrupted due to
errors or system failures.
Transactions also provide a mechanism for concurrent access to the database,
allowing multiple users to access the database simultaneously without
interfering with each other's work.
Transactions form the backbone of many business-critical applications and
systems by ensuring that database changes are processed reliably and
consistently.
21. What is the difference between CHAR and VARCHAR
in SQL?
CHAR is a fixed-length data type in SQL, meaning it will always occupy the exact
number of characters specified, even if the actual value is shorter. Padding with
spaces is done to meet the required length. On the other hand, VARCHAR is a
variable-length data type. It stores only the number of characters that are used,
without extra padding, making it more efficient for storing variable-length strings.
However, CHAR can be faster for fixed-length data as there is no length checking
involved.
22. What is the use of the GROUP BY clause in SQL?
The GROUP BY clause in SQL is used to group rows that share the same values in
specified columns into summary rows. It is typically used with aggregate functions
like COUNT(), SUM(), AVG(), etc., to perform operations on these grouped data. For
instance, you can use GROUP BY to find the total sales for each product in a sales
table. It helps in producing summary reports and is commonly used for analytical
queries.
23. What is the default sorting order in SQL?
The default sorting order in SQL is ascending. When you run a query with the
ORDER BY clause, it automatically sorts the results in ascending order unless
explicitly specified as DESC (for descending order). For example, in a list of numbers
or dates, sorting in ascending order will arrange them from smallest to largest or
from oldest to newest, respectively. Ascending sorting can be done by simply using
the ORDER BY clause without specifying ASC.
24. What is the difference between UNION and UNION
ALL in SQL?
UNION and UNION ALL are both used to combine the result sets of two or more
SELECT statements. The key difference is that UNION removes duplicate rows,
ensuring that each row in the final result set is unique. In contrast, UNION ALL
includes all rows from each query, including duplicates. While UNION is helpful when
you need to eliminate duplicates, UNION ALL is faster since it does not perform the
duplicate check and simply appends the results.
25. How do you use the DISTINCT keyword in SQL?
The DISTINCT keyword is used in SQL to remove duplicate values from the result
set of a SELECT query. It ensures that only unique records are returned. For
instance, when retrieving data from a column with repeating values, using DISTINCT
will return each unique value only once. This is useful when you want to know
distinct categories, items, or identifiers in a table. For example, SELECT DISTINCT
department FROM employees; will give a list of unique departments.