SQL Interactive Q&A

Click questions to reveal answers | Covers basic to advanced SQL | Perfect for interview prep
Test your SQL knowledge with these interactive questions. Click any question to reveal the detailed answer with examples. Try answering yourself before checking the solutions!
The most basic SELECT query retrieves data from a table:
SELECT column1, column2 FROM table_name;
Key components:
- SELECT specifies columns to retrieve
- FROM specifies the source table
- Semicolon (;) terminates the statement (in most SQL dialects)
To select all columns:
SELECT * FROM table_name;
The WHERE clause filters rows based on conditions:
SELECT product_name, price FROM products WHERE price > 100 AND category = 'Electronics';
Common operators:
Operator | Description | Example |
---|---|---|
= | Equal | WHERE id = 5 |
> | Greater than | WHERE age > 30 |
LIKE | Pattern matching | WHERE name LIKE 'A%' |
BETWEEN | Range inclusive | WHERE price BETWEEN 50 AND 100 |
INNER JOIN: Returns only matching rows from both tables
SELECT a.name, b.order_date FROM customers a INNER JOIN orders b ON a.id = b.customer_id;
LEFT JOIN: Returns all rows from left table + matches from right (NULL if no match)
SELECT a.name, b.order_date FROM customers a LEFT JOIN orders b ON a.id = b.customer_id;
Visualization:
Table A: [1, 2, 3]
Table B: [2, 3, 4]
INNER JOIN: [2, 3]
LEFT JOIN: [1, 2, 3] (with NULL for 1's match)
GROUP BY aggregates data by specified columns, while HAVING filters the grouped results:
SELECT department, COUNT(*) as emp_count, AVG(salary) as avg_salary FROM employees GROUP BY department HAVING COUNT(*) > 5 AND AVG(salary) > 50000;
Key differences from WHERE:
- WHERE filters rows before grouping
- HAVING filters groups after aggregation
- HAVING can use aggregate functions (COUNT, AVG, etc.)
Subqueries (nested queries) are SELECT statements within other queries:
Example 1: In WHERE clause
SELECT product_name FROM products WHERE price > (SELECT AVG(price) FROM products);
Example 2: In FROM clause (derived table)
SELECT dept, avg_salary FROM ( SELECT department as dept, AVG(salary) as avg_salary FROM employees GROUP BY department ) AS dept_stats WHERE avg_salary > 75000;
Common use cases:
- Comparing values against aggregated results
- Creating temporary result sets for complex operations
- Exists/Not Exists conditions
Want more practice? See our SQL interview questions | Try our Show All Answers button