SQL & Databases Interview Questions and Answers

Relational database fundamentals, query execution lifecycle, advanced JOINs, subqueries, window functions, indexing, ACID transactions, and query optimization.

Practise 10 random 115 peer-reviewed questions
SQL & Databases Interview Syllabus & Preparation Strategy

Whether you are preparing for entry-level SQL & Databases interview questions for freshers or senior software engineer interview questions addressing concurrency, scalability, and system architecture, this track provides peer-reviewed model answers with syntax walkthroughs, edge cases, and practical interview tips.

1 SQL was developed as an integral part of... Easy

Relational Database Management Systems (RDBMS). SQL is the ANSI-standard language for creating, querying, updating, and managing relational databases. Major implementations include MySQL, PostgreSQL, SQL Server, Oracle, and SQLite.

*Real-world context*: Every web application you use — Instagram, Netflix, Uber — stores its data in SQL databases (often sharded or replicated, but SQL at the core).

2 What does SQL stand for? Easy

SQL stands for Structured Query Language.

Originally developed at IBM by Donald D. Chamberlin and Raymond F. Boyce in the early 1970s, it was initially named SEQUEL (Structured English Query Language) designed to manipulate and retrieve data stored in IBM's original relational database management system, System R.

### Key Aspects of SQL:

  1. Declarative Paradigm: Unlike imperative programming languages (where you write step-by-step algorithms), SQL is declarative—you describe *what* data you want, and the database query optimizer plans *how* to execute the retrieval.
  2. ANSI & ISO Standards: SQL became an ANSI standard in 1986 and an ISO standard in 1987. Major relational engines (PostgreSQL, MySQL, Oracle, SQL Server) adhere to core SQL standards while offering dialect-specific extensions.
  3. Core Language Subsets:
  • DDL (Data Definition Language): CREATE, ALTER, DROP, TRUNCATE
  • DML (Data Manipulation Language): SELECT, INSERT, UPDATE, DELETE
  • DCL (Data Control Language): GRANT, REVOKE
  • TCL (Transaction Control Language): COMMIT, ROLLBACK, SAVEPOINT
3 Which is NOT a valid SQL command: SELECT, REMOVE, UPDATE, INSERT? Easy

REMOVE is not valid. To delete rows, use DELETE. DROP removes objects (tables, databases).

| Command | Purpose |
|---------|---------|
| SELECT | Read data |
| INSERT | Add new rows |
| UPDATE | Modify existing rows |
| DELETE | Remove rows |
| CREATE/ALTER/DROP | Manage schema objects |

4 What is MySQL, and how does it differ from SQL? Easy

SQL is the *language* (like English). MySQL is a *database system* that *speaks* SQL (like a person who speaks English).

Analogy: SQL is the recipe; MySQL is the kitchen that follows it.

5 What is PL/SQL, and how is it different from SQL? Easy

PL/SQL = Procedural Language extensions to SQL (Oracle-specific). It adds variables, loops, IF-ELSE, and exception handling.

| SQL | PL/SQL |
|-----|--------|
| Single statements | Blocks of code |
| No variables | Variables & constants |
| No loops | FOR, WHILE loops |
| Data-oriented | Application-oriented |
| Can embed in PL/SQL | Cannot embed SQL inside itself |

6 What are the possible values for a BOOLEAN field in MySQL? Easy

MySQL doesn't have a native BOOLEAN type. It uses TINYINT(1) where 0 = false, 1 = true, and any non-zero value is treated as true in conditions.

CREATE TABLE users (is_active TINYINT(1) DEFAULT 1);

PostgreSQL, however, has a true BOOLEAN type accepting TRUE, FALSE, and NULL.

7 Which data type for distance rounded to the nearest mile? Easy

When storing distance rounded to the nearest whole mile, an integer data type is the optimal choice:

ALTER TABLE travel_logs ADD COLUMN distance_miles INT NOT NULL;

### Choosing the Exact Integer Type:

  • SMALLINT (-32,768 to 32,767 or 0 to 65,535 unsigned): Ideal for domestic road trips and regional commutes (takes only 2 bytes).
  • INT / INTEGER (up to ~2.14 billion, 4 bytes): Safe default for global flights or astronomical distances.
  • DECIMAL(8, 2) / NUMERIC: If requirements ever change to support fractional miles (e.g. 14.75 miles), switch to exact fixed-point decimals rather than floating-point FLOAT/DOUBLE to prevent binary rounding inaccuracies.
8 Which are valid SQL comments? Easy

SQL supports both single-line and multi-line commenting syntax across relational database engines:

### 1. Single-Line Standard Comment (--):
The official ANSI SQL standard single-line comment begins with two hyphens followed by a space:

-- Query active users who signed up this year
SELECT * FROM users WHERE signup_year = 2026;

### 2. Multi-Line Comment (/* ... */):
Used for extended explanations or commenting out blocks of SQL logic:

/* 
   Author: Engineering Team
   Purpose: Calculate month-end churn metrics
*/
SELECT department, COUNT(*) FROM employees GROUP BY department;

### 3. MySQL-Specific Hash Comment (#):
MySQL also supports the hash symbol (#) for single-line comments, though -- is strongly preferred for ANSI portability.

9 Can we rename a column in output? Easy

Yes, using AS (alias):

SELECT first_name AS fname, last_name AS lname FROM customers;
-- AS is optional but recommended for readability:
SELECT first_name fname FROM customers;
10 How to select FirstName from Customers? Easy

To retrieve only the FirstName column from the Customers table, use the standard SELECT projection statement:

SELECT FirstName 
FROM Customers;

### Performance Best Practice:
Always select specific column names instead of using SELECT *. Explicit column projection:

  • Reduces network transfer bandwidth between the database server and application.
  • Decreases application server memory usage during row hydration.
  • Allows database engines to leverage Covering Indexes, satisfying queries entirely in-memory from the index tree without scanning table row pages.
11 Which statement returns only different values? Easy

SELECT DISTINCT. It operates on the *entire selected row*.

-- Returns unique city-state combinations
SELECT DISTINCT city, state FROM addresses;
12 Display distinct cities in ADDRESSES(id, street_name, number, city, state)? Easy

To retrieve a list of unique cities without duplicates from the ADDRESSES table, use the DISTINCT keyword:

SELECT DISTINCT city 
FROM addresses 
ORDER BY city ASC;

### Performance Consideration:
The DISTINCT clause forces the database engine to perform a deduplication sort or hash aggregation over the candidate rows. On tables containing millions of records, ensure an index exists on the city column (CREATE INDEX idx_addresses_city ON addresses(city)) to enable an index skip-scan or fast stream deduplication.

13 Select all records where FirstName is "John"? Easy

To retrieve all columns for records where FirstName equals 'John', combine SELECT * with a WHERE equality filter:

SELECT * 
FROM Customers 
WHERE FirstName = 'John';

### Case Sensitivity & Index Usage:

  • In MySQL with default collation (utf8mb4_general_ci), string comparisons are case-insensitive ('John' matches 'john').
  • In PostgreSQL, comparisons are case-sensitive by default ('John' != 'john'). For case-insensitive matching in Postgres, use WHERE FirstName ILIKE 'John'.
  • Ensure an index exists on FirstName to avoid an expensive full table scan.
14 OR vs AND? Easy

AND requires ALL conditions to be true. OR requires ANY to be true. Use parentheses to control precedence — AND binds tighter than OR.

-- Without parentheses, this is parsed as:
-- WHERE (age > 18 AND city = 'NY') OR status = 'active'
SELECT * FROM customers 
WHERE age > 18 AND (city = 'NY' OR city = 'LA');
15 Which comparison operators exist? Easy

Relational SQL engines provide a rich set of comparison operators evaluated in WHERE and HAVING clauses:

| Operator | Meaning | Example |
| :--- | :--- | :--- |
| = | Equal to | status = 'active' |
| != or <> | Not equal to | role <> 'admin' |
| > / < | Greater than / Less than | salary > 75000 |
| >= / <= | Greater or equal / Less or equal | age >= 21 |
| BETWEEN | Inclusive range check | price BETWEEN 10 AND 50 |
| IN | Matches any value in a list | status IN ('new', 'pending') |
| LIKE | Wildcard string pattern matching | email LIKE '%@gmail.com' |
| IS NULL / IS NOT NULL | Null identity checks | deleted_at IS NULL |
| <=> (MySQL) | NULL-safe equality operator | a <=> b |

16 Select records where FirstName="John" AND LastName="Jackson"? Easy

To retrieve records that satisfy multiple simultaneous criteria, use the AND logical conjunction operator:

SELECT * 
FROM Customers 
WHERE FirstName = 'John' 
  AND LastName = 'Jackson';

### Optimization Tip:
When frequently querying by both columns, create a composite index on (LastName, FirstName):

CREATE INDEX idx_customers_name ON Customers(LastName, FirstName);

Composite B-tree indexes allow the database engine to locate the exact record in $O(\log n)$ lookup time.

17 How to select 10 random rows? Easy
-- MySQL
SELECT * FROM tbl ORDER BY RAND() LIMIT 10;
-- PostgreSQL
SELECT * FROM tbl ORDER BY RANDOM() LIMIT 10;
-- SQL Server
SELECT TOP 10 * FROM tbl ORDER BY NEWID();

Performance note: This is O(n log n) and full table scan. For large tables, use a random ID approach.

18 What does ISNULL(price, 50) return if price is NULL? Easy

If price is NULL, ISNULL(price, 50) evaluates to 50.

### Function Nuances Across Databases:

  1. SQL Server: ISNULL(check_expression, replacement_value) returns the replacement if the first argument is NULL.
  2. MySQL: ISNULL(expr) returns a boolean 1 (true) or 0 (false). For value substitution, MySQL uses IFNULL(price, 50).
  3. ANSI Standard Portable Solution (COALESCE):

The ANSI standard function supported across all SQL databases (PostgreSQL, MySQL, Oracle, SQLite, SQL Server) is COALESCE:

   SELECT COALESCE(price, 50) AS effective_price FROM products;
   

COALESCE accepts two or more arguments and returns the very first non-NULL value.

19 Which operator searches text patterns? Easy

LIKE with wildcards % (zero or more chars) and _ (single char).

WHERE name LIKE 'A%'      -- starts with A
WHERE name LIKE '%a%'     -- contains a
WHERE name LIKE '_a%'     -- second char is a
WHERE name LIKE '___'     -- exactly 3 characters
20 Details of students whose FirstName starts with 'K'? Easy

To find records where a text column begins with a specific letter or prefix, use the LIKE operator with the % wildcard:

SELECT * 
FROM Students 
WHERE FirstName LIKE 'K%';

### How Wildcards Work:

  • %: Matches zero, one, or multiple arbitrary characters ('K', 'Kevin', 'Katherine').
  • _: Matches exactly one single character ('K_' matches 'Ka', but not 'Kevin').
  • *Index efficiency:* Prefix wildcards like 'K%' leverage B-tree indexes effectively. Leading wildcards like '%K' cannot use standard B-tree indexes and cause full table scans.
Showing 20 of 115 questions

Frequently Asked Questions About SQL & Databases Interviews

What do hiring managers evaluate in SQL & Databases technical rounds?

Technical interviewers look for foundational fluency, idiomatic syntax, clarity when communicating complex logic, and awareness of performance trade-offs (e.g. memory footprint, render performance, and network latency) in production environments.

What are the best interview tips for practicing SQL & Databases questions?

Use active recall: summarize each answer in your own words before revealing the model solution. Focus on explaining why a certain approach is chosen rather than just memorizing code syntax.