Commonly Asked SQL Interview QnA
Commonly Asked SQL Interview QnA
1. What is SQL?
Ans: 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.
• 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.
5. 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;
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.
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:
12. Write a SQL query to find the names of employees who have
not been assigned to any project.
Ans: We have created an Employee table and a Project table
CREATE TABLE employees (
employee_id INT PRIMARY KEY,
name VARCHAR(50)
);
SELECT employees.name
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.
Output:
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.
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 on Requires to DROP and CREATE privileges
Access
the table. on the table.
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.order_id, or
ders_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.
• 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.
• Load: The final step is to load the transformed data into a data warehouse
or database. This may involve loading data into tables, creating indexes,
or performing other database operations.
The ETL process is critical for data integration, as it allows organizations to collect
data from various sources, transform it into a consistent format, and store it in a central
location for analysis and reporting. ETL tools such as Microsoft SQL Server
Integration Services (SSIS) or Talend can automate much of the ETL process and
provide a visual interface for designing and managing data flows.
• LEFT JOIN: It returns all the left and the matching rows from the right table.
The result will contain null values for the right table's columns if there are
no matches.
• RIGHT JOIN: It returns all the rows from the right table and the matching
ones from the left table. The result will contain null values for the left table's
columns if there are no matches.
• FULL OUTER JOIN: It returns all the rows from both tables, including
unmatched ones. If there are no matches, the result will contain null values
for the table's columns that don't have a matching row.
There is also a CROSS JOIN, which returns the Cartesian product of the two tables,
which combines every row from the first table with all rows from the second table.
However, unlike the other JOIN types, it doesn't use a join condition to match the rows
between the tables.
Aggregate functions are used to perform calculations on data sets and return a single
value representing some summary of that set. In contrast, scalar functions operate on
a single value and return a single value. Both functions are commonly used in
database management systems to manipulate and analyze data.
• Unique Index: A unique index enforces the constraint that the values in
the indexed column(s) must be unique across all rows in the table.
Depending on the table's primary key, it can be either a clustered or non-
clustered index.
28. What are some standard clauses used with SELECT queries
in SQL?
Ans: In SQL, the SELECT statement retrieves data from a database. Along with the
introductory SELECT statement, you can use clauses to specify additional details
about how the data should be retrieved. Here are some standard clauses used with
the SELECT statement example:
Here, we consider a table name List_1 and perform the following SELECT queries.
CREATE TABLE `List_1` (
order_id int(11) NOT NULL,
customer_id int(11) NOT NULL,
order_date date NOT NULL,
total_amount decimal(10,2) NOT NULL,
PRIMARY KEY (`order_id`)
);
Output:
Output:
• GROUP BY: This clause group the results by one or more columns. For
example, you can use GROUP BY to group a list of sales by month or by
product.
Output:
Output:
• LIMIT: This clause limits the number of rows returned by the query. For
example, you can use LIMIT to retrieve the top 10 customers based on
their sales.
29. How to get unique records from the table without using
distinct keywords.
Ans: To get unique records from a table without using the DISTINCT keyword in SQL,
you can use the GROUP BY clause with aggregate functions like COUNT, SUM, or
AVG.
Create a Table Sales
CREATE TABLE sales (
product VARCHAR(50),
quantity INT
);
To get unique products from the sales table, you can group the rows by the product
column and use the COUNT aggregate function to count the number of occurrences
of each product:
SELECT product
FROM sales
GROUP BY product;
Output:
If you want to include additional columns in the output, you can also use aggregate
functions for those columns. For example, to get the sum of quantities sold for each
product, you can use the SUM aggregate function:
SELECT product, SUM(quantity) as total_quantity
FROM sales
GROUP BY product;
Output:
By grouping the rows by the product column and using the aggregate functions, you
can effectively get unique records from the table without using the DISTINCT keyword.
Output:
Nested Subquery:
A nested subquery is a query that is embedded within another query. The inner query
is performed first, and the outer query uses its results. The inner query is enclosed
within parentheses and is usually placed in the WHERE or HAVING clause of the outer
query. A nested subquery returns a single value or a list of values.
Example:
SELECT order_id, customer_id, total_amount
FROM orderss
WHERE customer_id IN (
SELECT customer_id
FROM customerss
WHERE customer_location = 'New York'
);
Output:
Correlated Subquery:
It uses a value from the outer query. The inner query is performed once for each row
of the outer query, and the result depends on the outer query's current row. A
correlated subquery filters or joins data from two or more tables.
Example:
SELECT customer_name, (
SELECT SUM(total_amount)
FROM orderss
WHERE orderss.customer_id = customerss.customer_id
) AS total_spent
FROM customerss;
Output:
Join Operation:
When you have information about a single object or entity spread across multiple
tables, you can use a join operation to combine this information into a single table.
Join operations work by matching the data in a specific column between two or more
tables and then combining the rows from these tables into a new table. Different types
of join operations determine how data is matched and combined. You can retrieve a
piece of complete information about an object or entity using join operations from
multiple tables.
Example:
CREATE TABLE employees (
employee_id INT,
employee_name VARCHAR(50),
department_id INT
);
Output:
SELECT *
FROM table1
JOIN table2
ON table1.value > table2.value;
Output:
As you can see, this query returns all possible combinations of rows where the value
in table1 is greater than the corresponding value in table2.