DEV Community

Quipoin
Quipoin

Posted on

5 Most Asked SQL Interview Questions

  1. What is the difference between WHERE and HAVING in SQL?

Answer:

The main difference is WHERE filters rows before grouping, while HAVING filters groups after aggregation.

WHERE

  • Used with SELECT, UPDATE, DELETE
  • Filters individual rows
  • Cannot use aggregate functions like SUM() or COUNT()

Example

SELECT *
FROM employees
WHERE salary > 50000;

HAVING

  • Used with GROUP BY
  • Filters grouped data
  • Works with aggregate functions

Example

SELECT department, COUNT()
FROM employees
GROUP BY department
HAVING COUNT(
) > 5;

  1. What is the difference between INNER JOIN and LEFT JOIN?

Answer:

INNER JOIN

  • Returns only matching records from both tables.

LEFT JOIN

  • Returns all records from the left table and matching records from the right table.
  • If no match is found, NULL values are returned.

Example

SELECT e.name, d.department_name
FROM employees e
INNER JOIN departments d
ON e.department_id = d.id;

  1. What is a Primary Key in SQL?

Answer:

A Primary Key is a column (or group of columns) that uniquely identifies each row in a table.

Key features:

  • Must contain unique values
  • Cannot contain NULL values
  • Only one primary key per table

Example

CREATE TABLE users (
id INT PRIMARY KEY,
name VARCHAR(50),
email VARCHAR(100)
);

  1. What is the difference between DELETE, TRUNCATE, and DROP?

Answer:

DELETE

  • Removes specific rows
  • Can use WHERE
  • Can be rolled back

DELETE FROM employees WHERE id = 10;

TRUNCATE

  • Removes all rows
  • Faster than DELETE
  • Cannot use WHERE

TRUNCATE TABLE employees;

DROP

  • Deletes the entire table structure and data

DROP TABLE employees;

  1. What is a Subquery in SQL?

Answer:

A Subquery is a query inside another query. It is used to retrieve data that will be used in the main query.

Example

SELECT name
FROM employees
WHERE salary > (
SELECT AVG(salary)
FROM employees
);

This query finds employees whose salary is greater than the average salary.

✅ Want to master SQL step by step?
Check out the complete SQL tutorial here:
https://www.quipoin.com/tutorial/sql

Top comments (0)