SELECT Queries Deep Dive — WHERE, Operators, ORDER BY, LIMIT AND More
SELECT Queries Deep Dive — WHERE, Operators, ORDER BY, LIMIT & More
SQL ki sabse powerful command — SELECT ko andar bahar se samjho. Real-world queries, har operator ka use, aur interview mein pooche jaane wale saare questions — sab kuch ek jagah Data Insights par.
📑 Is Part 2 Mein Aap Kya Sikhenge:
SELECT command ke saare operators aur clauses — ek ek karke real examples ke saath:
- Topic 1: Basic SELECT — *, Columns, Aliases, Expressions
- Topic 2: WHERE Clause — Row Filtering
- Topic 3: AND, OR, NOT — Logical Operators
- Topic 4: BETWEEN — Range Filtering
- Topic 5: IN — List Matching
- Topic 6: LIKE — Pattern Matching
- Topic 7: IS NULL / IS NOT NULL
- Topic 8: ORDER BY — Sorting Results
- Topic 9: LIMIT & OFFSET — Pagination
- Topic 10: DISTINCT — Unique Values
📋 Note: Is poore Part 2 mein hum ek hi employees table use karenge jo Part 1 mein banai thi. Saare queries usi table pe run honge taaki concept clearly samajh aaye.
Sample Data — Employees Table
Pehle yeh data insert karo — baaki saare topics isi data pe run honge:
CREATE TABLE employees (
emp_id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(50) NOT NULL,
dept VARCHAR(30),
salary DECIMAL(10,2),
city VARCHAR(30),
hire_date DATE,
age INT,
manager_id INT
);
INSERT INTO employees (name, dept, salary, city, hire_date, age, manager_id)
VALUES
('Rahul Sharma', 'IT', 75000, 'Delhi', '2021-03-15', 28, NULL),
('Priya Singh', 'HR', 62000, 'Mumbai', '2020-07-01', 32, 1),
('Amit Kumar', 'Sales', 48000, 'Delhi', '2022-01-10', 25, 1),
('Sneha Patel', 'IT', 88000, 'Bangalore','2019-11-20', 35, 1),
('Ravi Verma', 'HR', 53000, 'Chennai', '2021-09-05', 29, 2),
('Kavita Joshi', 'Sales', 45000, 'Mumbai', '2023-02-14', 24, 2),
('Deepak Rao', 'Finance', 68000, 'Delhi', '2020-05-30', 31, 1),
('Anjali Mehta', 'IT', 92000, 'Bangalore','2018-08-12', 38, NULL),
('Suresh Nair', 'Sales', 51000, 'Chennai', '2022-06-20', 27, 2),
('Neha Gupta', 'Finance', 71000, 'Mumbai', '2019-04-18', 36, 1),
('Vikram Bose', 'IT', 83000, 'Delhi', '2020-12-01', 33, 8),
('Pooja Reddy', 'HR', NULL, 'Bangalore','2023-07-01', 23, 2),
('Arjun Das', 'Sales', 39000, 'Delhi', '2023-09-15', 22, 2),
('Meena Iyer', 'Finance', 65000, 'Chennai', '2021-11-08', 30, 1),
('Rohit Sharma', 'IT', 55000, 'Mumbai', '2022-03-22', 26, 8);
📊 Table Preview:
| emp_id | name | dept | salary | city | hire_date | age | manager_id |
|---|---|---|---|---|---|---|---|
| 1 | Rahul Sharma | IT | 75000.00 | Delhi | 2021-03-15 | 28 | NULL |
| 2 | Priya Singh | HR | 62000.00 | Mumbai | 2020-07-01 | 32 | 1 |
| 3 | Amit Kumar | Sales | 48000.00 | Delhi | 2022-01-10 | 25 | 1 |
| 4 | Sneha Patel | IT | 88000.00 | Bangalore | 2019-11-20 | 35 | 1 |
| 5 | Ravi Verma | HR | 53000.00 | Chennai | 2021-09-05 | 29 | 2 |
| 6 | Kavita Joshi | Sales | 45000.00 | Mumbai | 2023-02-14 | 24 | 2 |
| 7 | Deepak Rao | Finance | 68000.00 | Delhi | 2020-05-30 | 31 | 1 |
| 8 | Anjali Mehta | IT | 92000.00 | Bangalore | 2018-08-12 | 38 | NULL |
| 9 | Suresh Nair | Sales | 51000.00 | Chennai | 2022-06-20 | 27 | 2 |
| 10 | Neha Gupta | Finance | 71000.00 | Mumbai | 2019-04-18 | 36 | 1 |
| 11 | Vikram Bose | IT | 83000.00 | Delhi | 2020-12-01 | 33 | 8 |
| 12 | Pooja Reddy | HR | NULL | Bangalore | 2023-07-01 | 23 | 2 |
| 13 | Arjun Das | Sales | 39000.00 | Delhi | 2023-09-15 | 22 | 2 |
| 14 | Meena Iyer | Finance | 65000.00 | Chennai | 2021-11-08 | 30 | 1 |
| 15 | Rohit Sharma | IT | 55000.00 | Mumbai | 2022-03-22 | 26 | 8 |
15 rows in set
1. Basic SELECT — *, Columns, Aliases, Expressions
🔍 Definition: The SELECT statement retrieves data from a table. You can select all columns using *, specific columns by name, create aliases for display, and perform arithmetic expressions directly in the query.
🎯 Samjho Simple Bhasha Mein: SELECT ek waiter ki tarah hai jo tumhara order leta hai. Tum keh sakte ho "sab kuch lao" (SELECT *), ya "sirf naam aur salary lao" (SELECT name, salary), ya "salary ko 12 se multiply karke annual salary bhi dikha do" (expression). Alias matlab — column ka display naam change karna sirf dikhane ke liye, actual column name nahi badalta.
💡 SELECT Query ka Basic Structure:
SELECT column1, column2 FROM table_name;
Execution Order yaad rakho: FROM pehle → phir SELECT. Matlab pehle table identify hoti hai, phir columns choose hote hain.
💻 Real-World Code Examples:
Example 1: Saare columns aur saari rows fetch karo.
-- Sabse basic query
SELECT *
FROM employees;
Example 2: Sirf specific columns select karo.
-- Sirf naam, department aur salary
SELECT name, dept, salary
FROM employees;
Example 3: Alias use karo aur expressions calculate karo.
-- Column aliases + calculations
SELECT
name AS 'Employee Name',
dept AS 'Department',
salary AS 'Monthly Salary',
salary * 12 AS 'Annual Salary',
salary * 0.10 AS 'Bonus (10%)'
FROM employees;
📊 Expected Output (Example 3):
| Employee Name | Department | Monthly Salary | Annual Salary | Bonus (10%) |
|---|---|---|---|---|
| Rahul Sharma | IT | 75000.00 | 900000.00 | 7500.000 |
| Priya Singh | HR | 62000.00 | 744000.00 | 6200.000 |
| Amit Kumar | Sales | 48000.00 | 576000.00 | 4800.000 |
| Sneha Patel | IT | 88000.00 | 1056000.00 | 8800.000 |
| Ravi Verma | HR | 53000.00 | 636000.00 | 5300.000 |
(15 rows total...)
⚠️ Common Mistakes:
- Mistake: Production mein
SELECT *use karna → Unnecessary data fetch, slow performance.
Fix: Hamesha specific column names likho. - Mistake: Alias mein space dena bina quotes ke →
AS Annual Salary❌
Fix:AS 'Annual Salary'ya backticks use karo ✅ - Mistake: Alias ko WHERE clause mein use karna → Error aayega.
Fix: WHERE mein original column name use karo — alias sirf display ke liye hai.
💬 Interview Questions:
Q1: Can we use column alias in WHERE clause?
Ans: No. Alias WHERE clause mein use nahi ho sakta because of execution order — WHERE runs before SELECT, so at the time WHERE executes, alias has not been created yet. You must use the original column name or expression in WHERE.
Q2: What is the difference between AS and without AS for alias?
Ans: Both work the same way. SELECT name AS 'Employee Name' and SELECT name 'Employee Name' produce identical results. However using AS keyword is considered best practice as it makes the query more readable and explicit.
Q3: Can we perform calculations in SELECT?
Ans: Yes, SELECT supports all arithmetic operators: + (add), - (subtract), * (multiply), / (divide), % (modulo). Example: SELECT salary * 12 AS annual_salary FROM employees. These calculations happen on-the-fly and do not modify actual table data.
2. WHERE Clause — Row Filtering
🔍 Definition: The WHERE clause filters rows from a table based on a specified condition. Only rows that satisfy the condition are included in the result. WHERE works with comparison operators: = (equal), != or <> (not equal), > (greater than), < (less than), >= (greater than or equal), <= (less than or equal).
🎯 Samjho Simple Bhasha Mein: Socho tumhare paas 15 employees hain. Tum sirf IT department ke employees dekhna chahte ho — WHERE lagao aur filter ho jayega. WHERE ek security guard ki tarah hai jo sirf specific criteria wale logon ko andar aane deta hai.
💡 Comparison Operators:
= Equal to | != or <> Not equal to
> Greater than | < Less than
>= Greater or equal | <= Less or equal
💻 Real-World Code Examples:
Example 1: Sirf IT department ke employees dikhao.
-- String comparison (quotes zaroori hain)
SELECT name, dept, salary
FROM employees
WHERE dept = 'IT';
Example 2: 60000 se zyada salary wale employees.
-- Numeric comparison (quotes nahi lagte numbers mein)
SELECT name, dept, salary
FROM employees
WHERE salary > 60000;
Example 3: Sales department ke employees ko exclude karo.
-- Not equal operator
SELECT name, dept, salary
FROM employees
WHERE dept != 'Sales';
-- Ya yeh bhi same kaam karta hai:
WHERE dept <> 'Sales';
📊 Expected Output (Example 1 — IT Employees):
| name | dept | salary |
|---|---|---|
| Rahul Sharma | IT | 75000.00 |
| Sneha Patel | IT | 88000.00 |
| Anjali Mehta | IT | 92000.00 |
| Vikram Bose | IT | 83000.00 |
| Rohit Sharma | IT | 55000.00 |
5 rows in set
⚠️ Common Mistakes:
- Mistake: String values mein quotes bhool jaana →
WHERE dept = IT❌ — MySQL "IT" ko column name samjhega.
Fix:WHERE dept = 'IT'✅ - Mistake: Numbers mein quotes lagana →
WHERE salary > '60000'— kaam toh karega but implicit type conversion hogi, slow performance.
Fix:WHERE salary > 60000✅ - Mistake: NULL check ke liye = use karna →
WHERE salary = NULL❌ — hamesha FALSE return karega.
Fix:WHERE salary IS NULL✅ (Topic 7 mein detail mein)
💬 Interview Questions:
Q1: When does WHERE clause get executed in a SELECT query?
Ans: WHERE executes after FROM (table identified) but before SELECT (columns chosen). So WHERE can only reference actual column names — not aliases defined in SELECT. Execution order: FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY → LIMIT.
Q2: What is the difference between != and <> in MySQL?
Ans: Both != and <> are identical in MySQL — they both mean "not equal to". <> is the SQL standard syntax while != is commonly used in programming languages like Python/Java. MySQL supports both equally. Some older databases only support <>.
Q3: Can WHERE clause be used with UPDATE and DELETE?
Ans: Yes, WHERE is not exclusive to SELECT. It is used with UPDATE to specify which rows to modify and with DELETE to specify which rows to remove. Without WHERE in UPDATE or DELETE, all rows are affected — which is one of the most dangerous mistakes in SQL.
3. AND, OR, NOT — Logical Operators
🔍 Definition: Logical operators combine multiple conditions in a WHERE clause. AND requires ALL conditions to be true. OR requires ANY ONE condition to be true. NOT reverses/negates a condition.
🎯 Samjho Simple Bhasha Mein: AND matlab "yeh bhi aur woh bhi" — dono conditions true honi chahiye. OR matlab "yeh ya woh" — koi ek bhi true ho toh chalega. NOT matlab "ulta karo" — jo true tha woh false, jo false tha woh true. Real life mein: "IT department AND salary > 70000" — dono conditions zaroor honi chahiye tab row select hogi.
💡 Operator Precedence (Priority Order):
MySQL mein pehle NOT, phir AND, phir OR evaluate hota hai.
WHERE A OR B AND C → Actually: WHERE A OR (B AND C)
Best Practice: Hamesha parentheses use karo confusion avoid karne ke liye!
💻 Real-World Code Examples:
Example 1 (AND): IT department mein 80000 se zyada salary wale.
-- AND: Dono conditions true honi chahiye
SELECT name, dept, salary, city
FROM employees
WHERE dept = 'IT' AND salary > 80000;
Example 2 (OR): IT ya Finance department ke employees.
-- OR: Koi ek condition true ho toh chalega
SELECT name, dept, salary
FROM employees
WHERE dept = 'IT' OR dept = 'Finance';
Example 3 (NOT): Delhi mein nahi rehne wale employees.
-- NOT: Condition ko negate karo
SELECT name, city, dept
FROM employees
WHERE NOT city = 'Delhi';
Example 4 (Combined): IT ya HR department mein ho AND salary 60000 se zyada ho AND Delhi mein na ho.
-- Complex condition with parentheses (best practice)
SELECT name, dept, salary, city
FROM employees
WHERE (dept = 'IT' OR dept = 'HR')
AND salary > 60000
AND NOT city = 'Delhi';
📊 Expected Output (Example 1 — AND):
| name | dept | salary | city |
|---|---|---|---|
| Sneha Patel | IT | 88000.00 | Bangalore |
| Anjali Mehta | IT | 92000.00 | Bangalore |
| Vikram Bose | IT | 83000.00 | Delhi |
3 rows in set
📊 Expected Output (Example 4 — Combined):
| name | dept | salary | city |
|---|---|---|---|
| Priya Singh | HR | 62000.00 | Mumbai |
| Sneha Patel | IT | 88000.00 | Bangalore |
| Anjali Mehta | IT | 92000.00 | Bangalore |
3 rows in set
⚠️ Common Mistakes:
- Mistake: Parentheses na lagana complex queries mein → Wrong results milenge silently.
Fix: Hamesha OR ke groups ko parentheses mein wrap karo. - Mistake:
WHERE dept = 'IT' OR 'HR'❌ — 'HR' ko boolean treat karega.
Fix:WHERE dept = 'IT' OR dept = 'HR'✅ — Har condition mein column name repeat karo. - Mistake: AND aur OR ki priority bhool jaana → AND pehle evaluate hota hai OR se.
Fix: Parentheses se explicit order define karo.
💬 Interview Questions:
Q1: What is operator precedence between AND and OR?
Ans: AND has higher precedence than OR. So WHERE A OR B AND C is evaluated as WHERE A OR (B AND C) — not as WHERE (A OR B) AND C. To override precedence, always use parentheses explicitly. NOT has the highest precedence among logical operators.
Q2: Give a scenario where wrong parentheses placement causes incorrect query results.
Ans: Query: WHERE dept = 'IT' OR dept = 'HR' AND salary > 70000 — Due to AND precedence, this means "IT department employees (any salary) OR HR employees with salary > 70000". If intent was "(IT or HR) AND salary > 70000" then parentheses are needed: WHERE (dept='IT' OR dept='HR') AND salary > 70000.
Q3: How does NOT operator work with NULL values?
Ans: NOT NULL is not the same as IS NOT NULL. WHERE NOT salary = NULL will not return rows with NULL salary because any comparison with NULL (including NOT) returns UNKNOWN, not TRUE. You must use WHERE salary IS NOT NULL to properly filter NULL values.
4. BETWEEN — Range Filtering
🔍 Definition: BETWEEN operator filters rows where a column value falls within a specified range — inclusive of both boundary values. It works with numbers, dates and strings. Syntax: column BETWEEN value1 AND value2.
🎯 Samjho Simple Bhasha Mein: BETWEEN ek range define karta hai. Jaise "50000 se 80000 ke beech salary" — toh 50000 aur 80000 dono included hain. Yeh salary >= 50000 AND salary <= 80000 likhne ka shortcut hai. Dates ke saath bhi kaam karta hai — "January 2021 se December 2022 ke beech join hue employees."
💡 Important: BETWEEN inclusive hota hai — matlab dono boundary values (value1 aur value2) bhi result mein aayenge. BETWEEN 50000 AND 80000 mein exactly 50000 aur exactly 80000 dono included hain.
💻 Real-World Code Examples:
Example 1: 50000 se 80000 ke beech salary wale employees.
-- Numeric range
SELECT name, dept, salary
FROM employees
WHERE salary BETWEEN 50000 AND 80000;
-- Equivalent to:
-- WHERE salary >= 50000 AND salary
Example 2: 2021 se 2022 ke beech hire hue employees.
-- Date range
SELECT name, hire_date, dept
FROM employees
WHERE hire_date BETWEEN '2021-01-01' AND '2022-12-31';
Example 3: NOT BETWEEN — 50000-80000 range ke bahar salary wale.
-- NOT BETWEEN: Range ke bahar
SELECT name, salary
FROM employees
WHERE salary NOT BETWEEN 50000 AND 80000;
📊 Expected Output (Example 1):
| name | dept | salary |
|---|---|---|
| Rahul Sharma | IT | 75000.00 |
| Priya Singh | HR | 62000.00 |
| Ravi Verma | HR | 53000.00 |
| Deepak Rao | Finance | 68000.00 |
| Suresh Nair | Sales | 51000.00 |
| Neha Gupta | Finance | 71000.00 |
| Vikram Bose | IT | 83000.00 |
| Meena Iyer | Finance | 65000.00 |
| Rohit Sharma | IT | 55000.00 |
9 rows in set
⚠️ Common Mistakes:
- Mistake: BETWEEN mein bada value pehle dena →
BETWEEN 80000 AND 50000❌ — Koi result nahi aayega.
Fix: Hamesha chota value pehle:BETWEEN 50000 AND 80000✅ - Mistake: Date BETWEEN mein time ignore karna →
BETWEEN '2022-01-01' AND '2022-12-31'mein December 31 ka time 00:00:00 maana jayega, baad ke records miss honge.
Fix:BETWEEN '2022-01-01' AND '2022-12-31 23:59:59'✅ - Mistake: BETWEEN ko exclusive samajhna → Yeh inclusive hai, dono boundary values included hain.
💬 Interview Questions:
Q1: Is BETWEEN inclusive or exclusive of boundary values?
Ans: BETWEEN is inclusive of both boundary values. WHERE salary BETWEEN 50000 AND 80000 is exactly equivalent to WHERE salary >= 50000 AND salary <= 80000. Both 50000 and 80000 are included in the result.
Q2: Can BETWEEN be used with string/text values?
Ans: Yes, BETWEEN works with strings using alphabetical/lexicographic ordering. WHERE name BETWEEN 'A' AND 'M' returns names starting from A to M alphabetically. However string BETWEEN can be tricky with case sensitivity based on collation settings, so it's mainly recommended for numbers and dates.
Q3: What is the performance difference between BETWEEN and >= with <=?
Ans: There is no performance difference — MySQL's query optimizer converts BETWEEN internally to >= AND <= before execution. BETWEEN is just syntactic sugar for better readability. Both produce identical execution plans and identical results.
5. IN — List Matching
🔍 Definition: The IN operator checks if a column value matches any value from a specified list. It is a cleaner alternative to writing multiple OR conditions. Syntax: column IN (value1, value2, value3, ...).
🎯 Samjho Simple Bhasha Mein: IN ek guest list ki tarah hai. Tum keh rahe ho "andar wohi aayega jo is list mein hai." WHERE city IN ('Delhi', 'Mumbai', 'Bangalore') matlab sirf in teeno cities ke employees aayenge. Yeh multiple OR likhne ka shortcut hai aur query zyada readable hoti hai.
💡 IN vs OR — Kab kya use karein:
2-3 values → OR theek hai.
4+ values → IN zyada readable aur maintainable hai.
IN can also take a subquery as its list — very powerful! (Part 5 mein cover hoga)
💻 Real-World Code Examples:
Example 1: Delhi, Mumbai ya Bangalore ke employees.
-- IN with string list
SELECT name, city, dept
FROM employees
WHERE city IN ('Delhi', 'Mumbai', 'Bangalore');
-- Equivalent to (but less readable):
-- WHERE city = 'Delhi' OR city = 'Mumbai' OR city = 'Bangalore'
Example 2: IT, HR aur Finance department ke employees.
SELECT name, dept, salary
FROM employees
WHERE dept IN ('IT', 'HR', 'Finance');
Example 3: NOT IN — Sales department ke employees exclude karo.
-- NOT IN: List ke bahar wale
SELECT name, dept, salary
FROM employees
WHERE dept NOT IN ('Sales');
📊 Expected Output (Example 2):
| name | dept | salary |
|---|---|---|
| Rahul Sharma | IT | 75000.00 |
| Priya Singh | HR | 62000.00 |
| Sneha Patel | IT | 88000.00 |
| Ravi Verma | HR | 53000.00 |
| Deepak Rao | Finance | 68000.00 |
| Anjali Mehta | IT | 92000.00 |
| Neha Gupta | Finance | 71000.00 |
| Vikram Bose | IT | 83000.00 |
| Pooja Reddy | HR | NULL |
| Meena Iyer | Finance | 65000.00 |
| Rohit Sharma | IT | 55000.00 |
11 rows in set
⚠️ Common Mistakes:
- Mistake: NOT IN list mein NULL include karna →
WHERE dept NOT IN ('IT', NULL)— Koi result nahi aayega!
Fix: NULL ko NOT IN list mein kabhi mat daalo. NULL ke liye IS NOT NULL separately use karo. - Mistake: Bahut badi IN list → Performance slow ho sakti hai.
Fix: Large lists ke liye subquery ya temporary table use karo. - Mistake: IN mein values ke beech space bhool jaana → Syntax error nahi aayega but wrong matching ho sakti hai.
💬 Interview Questions:
Q1: What happens when NULL is in a NOT IN list?
Ans: If the NOT IN list contains NULL, the entire NOT IN condition returns UNKNOWN (not TRUE or FALSE) for every row — resulting in zero rows returned. This is because any comparison with NULL returns UNKNOWN. Always ensure your NOT IN list has no NULLs, and separately handle NULLs with IS NULL / IS NOT NULL.
Q2: What is the difference between IN and EXISTS?
Ans: IN evaluates the subquery completely and returns a list, then checks each row against the list — works well for small lists. EXISTS stops as soon as it finds the first matching row — more efficient for large datasets. EXISTS is generally preferred with correlated subqueries on large tables. (Covered in detail in Part 5)
Q3: Can IN operator be used with a subquery?
Ans: Yes, IN can take a subquery: WHERE emp_id IN (SELECT emp_id FROM high_performers). This is called a subquery with IN and is very commonly used. The subquery must return a single column of values that the outer query's column is compared against.
6. LIKE — Pattern Matching
🔍 Definition: LIKE operator performs pattern matching on string columns using two wildcards: % (percent — matches any sequence of characters including none) and _ (underscore — matches exactly one character). It is used for partial string searches.
🎯 Samjho Simple Bhasha Mein: LIKE ek search tool hai jab exact value pata na ho. % matlab "kuch bhi, kitna bhi." _ matlab "exactly ek character." Socho Gmail search — tum "Rah" likhte ho aur "Rahul", "Rahman", "Raheja" sab show ho jaate hain — yeh LIKE 'Rah%' jaisa kaam hai.
💡 Wildcard Patterns — Quick Reference:
'R%' → R se shuru hone wale (Rahul, Ravi, Rohit)
'%a' → a pe khatam hone wale (Priya, Sneha, Neha)
'%ar%' → beech mein "ar" aane wale (Rahul Sharma, Arjun)
'R_vi' → R + exactly 1 char + vi (Ravi) — not Rahul
'____' → Exactly 4 characters
💻 Real-World Code Examples:
Example 1: "R" se shuru hone wale employees.
-- R se shuru hone wale naam
SELECT name, dept
FROM employees
WHERE name LIKE 'R%';
Example 2: Naam mein "Sharma" aane wale employees.
-- Beech mein 'Sharma' aane wale
SELECT name, city
FROM employees
WHERE name LIKE '%Sharma%';
Example 3: "a" pe khatam hone wale naam.
-- 'a' pe khatam hone wale
SELECT name
FROM employees
WHERE name LIKE '%a';
Example 4: NOT LIKE — "Sharma" naam wale exclude karo.
-- NOT LIKE
SELECT name
FROM employees
WHERE name NOT LIKE '%Sharma%';
📊 Expected Output (Example 1 — R% names):
| name | dept |
|---|---|
| Rahul Sharma | IT |
| Ravi Verma | HR |
| Rohit Sharma | IT |
3 rows in set
⚠️ Common Mistakes:
- Mistake:
LIKE '%value%'leading wildcard use karna large tables par → Full table scan hoga, index use nahi hoga — very slow!
Fix: Agar possible ho tohLIKE 'value%'(leading wildcard nahi) use karo — index ka fayda milega. - Mistake: Case sensitivity bhool jaana → MySQL mein LIKE by default case-insensitive hai (utf8 collation). 'sharma' aur 'Sharma' dono match honge.
Fix: Case-sensitive search ke liyeLIKE BINARY 'Sharma%'use karo. - Mistake:
%aur_ka role confuse karna →%= any length,_= exactly 1 character.
💬 Interview Questions:
Q1: What is the difference between % and _ wildcards in LIKE?
Ans: % matches any sequence of zero or more characters — so 'R%' matches R, Ra, Rahul, Ravi, etc. _ matches exactly one character — so 'R_vi' matches Ravi (R + a + vi) but not Rahul. You can combine them: 'R__ul' matches Rahul (R + ah + ul).
Q2: Why does LIKE '%value%' cause performance issues?
Ans: When a pattern starts with %, MySQL cannot use indexes because it doesn't know where in the string to start looking — it must scan every row's full column value (full table scan). This is called a non-sargable query. For large tables this is very slow. Patterns like 'value%' (no leading %) can use indexes efficiently.
Q3: Is LIKE case-sensitive in MySQL?
Ans: By default, LIKE is case-insensitive in MySQL for non-binary string columns with standard collations (like utf8_general_ci — 'ci' means case-insensitive). To make it case-sensitive, use LIKE BINARY: WHERE name LIKE BINARY 'rahul%' will only match 'rahul', not 'Rahul'.
7. IS NULL / IS NOT NULL — Handling Missing Data
🔍 Definition: NULL represents the absence of a value — it is not zero, not empty string, not false. It means "unknown" or "not applicable." IS NULL checks for missing values and IS NOT NULL checks for present values. Standard comparison operators (=, !=) do NOT work with NULL.
🎯 Samjho Simple Bhasha Mein: NULL matlab "pata nahi" ya "available nahi." Jaise Pooja Reddy ki salary table mein NULL hai — matlab uski salary abhi set nahi hui. Rahul Sharma ka manager_id NULL hai — matlab woh khud manager hai. NULL ko normal = se check nahi kar sakte — sirf IS NULL ya IS NOT NULL se check hota hai. Yeh SQL ka sabse confusing concept hai!
💡 NULL ke baare mein 3 Important Rules:
1. NULL = NULL → FALSE (NULL khud se bhi equal nahi hota!)
2. NULL != NULL → FALSE
3. Koi bhi comparison NULL ke saath → UNKNOWN return karta hai
Isliye hamesha: IS NULL ya IS NOT NULL use karo — koi aur operator nahi.
💻 Real-World Code Examples:
Example 1: Jinki salary NULL hai (abhi set nahi hui).
-- NULL salary wale employees
SELECT name, dept, salary
FROM employees
WHERE salary IS NULL;
-- ❌ Yeh WRONG hai — koi result nahi aayega:
-- WHERE salary = NULL
Example 2: Jinki salary set hai (NULL nahi hai).
-- Salary filled wale employees
SELECT name, dept, salary
FROM employees
WHERE salary IS NOT NULL;
Example 3: Manager ke NULL hone ka matlab — jo top-level managers hain (koi manager nahi hai inke upar).
-- Top level managers (koi manager nahi hai inke upar)
SELECT name, dept, manager_id
FROM employees
WHERE manager_id IS NULL;
-- NULL ko handle karna display mein — IFNULL / COALESCE
SELECT
name,
IFNULL(salary, 0) AS salary,
COALESCE(manager_id, 0) AS manager_id
FROM employees;
📊 Expected Output (Example 1 — NULL salary):
| name | dept | salary |
|---|---|---|
| Pooja Reddy | HR | NULL |
| name | dept | manager_id |
| Rahul Sharma | IT | NULL |
| Anjali Mehta | IT | NULL |
1 row in set -- Example 3 (Top managers with NULL manager_id): 2 rows in set
text⚠️ Common Mistakes:
- Mistake:
WHERE salary = NULLuse karna → Hamesha 0 rows return karega.
Fix:WHERE salary IS NULL✅ - Mistake: NULL aur empty string ('') ko same samajhna →
''ek valid empty string hai, NULL bilkul alag hai.
Fix: Dono alag alag handle karo:WHERE name = ''aurWHERE name IS NULL. - Mistake: NULL values aggregate functions mein ignore hona bhool jaana → COUNT(*) saari rows count karta hai, COUNT(salary) NULL values ignore karta hai.
💬 Interview Questions:
Q1: Why can't we use = to compare NULL values?
Ans: NULL represents "unknown" value. Any comparison with NULL (including = NULL, != NULL, > NULL) returns UNKNOWN — not TRUE or FALSE — because you can't compare something unknown with anything. SQL's three-valued logic (TRUE/FALSE/UNKNOWN) means WHERE conditions returning UNKNOWN are treated as FALSE. Only IS NULL and IS NOT NULL specifically handle this.
Q2: What is the difference between IFNULL and COALESCE?
Ans: IFNULL takes exactly 2 arguments — if first is NULL, return second: IFNULL(salary, 0). COALESCE takes multiple arguments — returns the first non-NULL value from the list: COALESCE(salary, bonus, 0). COALESCE is the SQL standard and more flexible. IFNULL is MySQL-specific.
Q3: How does NULL affect COUNT()?
Ans: COUNT(*) counts all rows including rows with NULL values. COUNT(column_name) counts only non-NULL values in that specific column. Example: If salary column has 15 rows but 1 is NULL — COUNT(*) returns 15 but COUNT(salary) returns 14. This distinction is critical in data analysis.
8. ORDER BY — Sorting Results
🔍 Definition: ORDER BY clause sorts the result set based on one or more columns. ASC (ascending — default) sorts from lowest to highest or A to Z. DESC (descending) sorts from highest to lowest or Z to A. You can sort by multiple columns — first column sorts first, ties broken by second column.
🎯 Samjho Simple Bhasha Mein: ORDER BY results ko arrange karta hai. Jaise salary ke hisaab se top earners pehle dikhao (DESC), ya naam ke alphabetical order mein dikhao (ASC). Multiple columns — pehle department ke hisaab se sort karo, phir same department mein salary ke hisaab se — yeh bhi possible hai.
💡 NULL values in ORDER BY:
ASC order mein NULL values pehle aate hain (sabse chhote maane jaate hain).
DESC order mein NULL values baad mein aate hain.
ORDER BY column position number se bhi ho sakta hai: ORDER BY 3 DESC = 3rd column descending.
💻 Real-World Code Examples:
Example 1: Salary ke hisaab se descending order (highest first).
-- Highest salary first
SELECT name, dept, salary
FROM employees
ORDER BY salary DESC;
Example 2: Naam ke alphabetical order mein (ASC — default).
-- Alphabetical A to Z (ASC is default, can skip writing it)
SELECT name, dept
FROM employees
ORDER BY name ASC;
Example 3: Pehle department alphabetically, phir same department mein salary descending.
-- Multi-column sort
SELECT name, dept, salary
FROM employees
ORDER BY dept ASC, salary DESC;
📊 Expected Output (Example 3 — Multi Column Sort):
| name | dept | salary |
|---|---|---|
| Neha Gupta | Finance | 71000.00 |
| Meena Iyer | Finance | 65000.00 |
| Deepak Rao | Finance | 68000.00 |
| Priya Singh | HR | 62000.00 |
| Ravi Verma | HR | 53000.00 |
| Pooja Reddy | HR | NULL |
| Anjali Mehta | IT | 92000.00 |
| Sneha Patel | IT | 88000.00 |
| Vikram Bose | IT | 83000.00 |
| Rahul Sharma | IT | 75000.00 |
| Rohit Sharma | IT | 55000.00 |
| Suresh Nair | Sales | 51000.00 |
| Amit Kumar | Sales | 48000.00 |
| Kavita Joshi | Sales | 45000.00 |
| Arjun Das | Sales | 39000.00 |
15 rows in set
⚠️ Common Mistakes:
- Mistake: ORDER BY ke baad LIMIT lagana bhool jaana → Large tables par saara sorted data memory mein load hoga.
Fix: Top N results ke liye hameshaORDER BY ... LIMIT nuse karo. - Mistake: ORDER BY column position number use karna production mein →
ORDER BY 3— Agar table structure change ho toh wrong column sort hoga.
Fix: Hamesha explicit column name use karo. - Mistake: ORDER BY aur GROUP BY dono hone par ORDER BY pehle likhna → Syntax error aayega.
Fix: Sequence: WHERE → GROUP BY → HAVING → ORDER BY → LIMIT.
💬 Interview Questions:
Q1: What is the default sort order in ORDER BY?
Ans: The default sort order is ASC (ascending) — numbers from lowest to highest, strings A to Z, dates from oldest to newest. You can omit writing ASC as it is implicit. DESC must always be explicitly written for descending order.
Q2: Can we ORDER BY a column that is not in the SELECT list?
Ans: Yes, in MySQL you can ORDER BY any column from the table even if it's not in the SELECT clause. For example: SELECT name FROM employees ORDER BY salary DESC — salary is not selected but results are sorted by it. However this may be confusing — best practice is to include the sort column in SELECT.
Q3: How are NULL values handled in ORDER BY?
Ans: In MySQL, NULL values are treated as the lowest possible value. In ASC order, NULLs appear first (before all other values). In DESC order, NULLs appear last. To control NULL placement: ORDER BY ISNULL(salary), salary DESC — this pushes NULLs to the end in ascending sort.
9. LIMIT & OFFSET — Pagination
🔍 Definition: LIMIT restricts the number of rows returned by a query. OFFSET skips a specified number of rows before starting to return results. Together they enable pagination — showing data in pages like websites do (Page 1, Page 2, Page 3...).
🎯 Samjho Simple Bhasha Mein: LIMIT matlab "sirf itne results do." OFFSET matlab "pehle itne skip karo, phir dena shuru karo." Jaise Flipkart par 100 products hain par page par sirf 10 dikhate hain — pehla page: LIMIT 10 OFFSET 0, doosra page: LIMIT 10 OFFSET 10, teesra page: LIMIT 10 OFFSET 20. Yahi pagination hai!
💡 Pagination Formula:
LIMIT page_size OFFSET (page_number - 1) * page_size
Page 1: LIMIT 5 OFFSET 0
Page 2: LIMIT 5 OFFSET 5
Page 3: LIMIT 5 OFFSET 10
Shorthand: LIMIT offset, count → LIMIT 10, 5 = skip 10, show 5
💻 Real-World Code Examples:
Example 1: Top 5 highest salary wale employees.
-- Top 5 earners
SELECT name, dept, salary
FROM employees
ORDER BY salary DESC
LIMIT 5;
Example 2: Page 2 of results (5 per page — skip first 5, show next 5).
-- Page 2 (records 6 to 10)
SELECT name, dept, salary
FROM employees
ORDER BY emp_id ASC
LIMIT 5
OFFSET 5;
-- Shorthand (same result):
LIMIT 5, 5;
-- LIMIT offset, count
Example 3: Salary mein 3rd highest earner kaun hai.
-- 3rd highest salary (skip top 2, show 1)
SELECT name, salary
FROM employees
WHERE salary IS NOT NULL
ORDER BY salary DESC
LIMIT 1
OFFSET 2;
📊 Expected Output (Example 1 — Top 5):
| name | dept | salary |
|---|---|---|
| Anjali Mehta | IT | 92000.00 |
| Sneha Patel | IT | 88000.00 |
| Vikram Bose | IT | 83000.00 |
| Rahul Sharma | IT | 75000.00 |
| Neha Gupta | Finance | 71000.00 |
5 rows in set
-- Example 3 (3rd highest):
| name | salary |
|---|---|
| Vikram Bose | 83000.00 |
1 row in set
⚠️ Common Mistakes:
- Mistake: LIMIT bina ORDER BY use karna → Random rows milenge — pagination consistent nahi hogi.
Fix: Hamesha LIMIT ke saath ORDER BY use karo. - Mistake: LIMIT 0, 5 ko confuse karna → LIMIT 0, 5 matlab OFFSET 0, COUNT 5 (pehle 5 records).
Fix: Clarity ke liye explicit syntax use karo:LIMIT 5 OFFSET 0. - Mistake: Bahut bade OFFSET ke saath slow query →
LIMIT 5 OFFSET 100000— MySQL 100000 rows skip karne ke liye scan karega.
Fix: Cursor-based pagination use karo large datasets ke liye:WHERE id > last_seen_id LIMIT 5.
💬 Interview Questions:
Q1: How to find the Nth highest salary using LIMIT and OFFSET?
Ans: SELECT salary FROM employees ORDER BY salary DESC LIMIT 1 OFFSET N-1. For 3rd highest: OFFSET 2 (skip top 2, take 1). Important: add WHERE salary IS NOT NULL to exclude NULLs, and consider using DISTINCT if duplicate salaries exist.
Q2: What is the difference between LIMIT 5 OFFSET 10 and LIMIT 10, 5?
Ans: Both are identical. LIMIT 5 OFFSET 10 is the standard SQL syntax — skip 10 rows, return 5. LIMIT 10, 5 is MySQL shorthand — first number is offset, second is count. Results are exactly the same. The explicit OFFSET syntax is recommended for clarity.
Q3: Why does pagination with large OFFSET become slow?
Ans: MySQL scans and discards OFFSET number of rows before returning results. So LIMIT 10 OFFSET 100000 actually reads 100010 rows and throws away the first 100000. As OFFSET grows, performance degrades linearly. Solution: use keyset/cursor pagination — WHERE id > last_seen_id LIMIT 10 — which always uses index efficiently regardless of page number.
10. DISTINCT — Unique Values
🔍 Definition: DISTINCT eliminates duplicate rows from the result set, returning only unique combinations of the selected columns. It is placed immediately after SELECT keyword and applies to all selected columns together.
🎯 Samjho Simple Bhasha Mein: 15 employees hain aur 4 departments hain. Agar tum sirf departments ki list chahte ho (repetitions ke bina), toh DISTINCT use karo. Bina DISTINCT: IT, HR, Sales, IT, HR, Sales, Finance... DISTINCT ke saath: IT, HR, Sales, Finance — bas ek baar. Yeh "unique values" nikalne ka tool hai.
💡 Important: DISTINCT multiple columns ke saath — combination unique hoti hai, individual column nahi. SELECT DISTINCT dept, city mein (IT, Delhi) aur (IT, Mumbai) dono aayenge — kyunki combination alag hai, even though dept same hai.
💻 Real-World Code Examples:
Example 1: Unique departments ki list.
-- Unique departments
SELECT DISTINCT dept
FROM employees;
Example 2: Unique department + city combinations.
-- Unique dept + city combinations
SELECT DISTINCT dept, city
FROM employees
ORDER BY dept, city;
Example 3: Kitne unique cities hain — COUNT with DISTINCT.
-- Count of unique cities
SELECT COUNT(DISTINCT city) AS unique_cities
FROM employees;
-- Count of unique departments
SELECT COUNT(DISTINCT dept) AS total_departments
FROM employees;
📊 Expected Output:
-- Example 1 (Unique departments):
4 rows in set
-- Example 2 (Unique dept+city combos):
| dept | city |
|---|---|
| Finance | Chennai |
| Finance | Delhi |
| Finance | Mumbai |
| HR | Bangalore |
| HR | Chennai |
| HR | Mumbai |
| IT | Bangalore |
| IT | Delhi |
| IT | Mumbai |
| Sales | Chennai |
| Sales | Delhi |
| Sales | Mumbai |
12 rows in set
-- Example 3 (Count):
⚠️ Common Mistakes:
- Mistake: DISTINCT ko sirf pehle column par apply samajhna →
SELECT DISTINCT dept, citymein DISTINCT dono columns ki combination par apply hota hai.
Fix: Clearly samjho — DISTINCT entire row combination check karta hai. - Mistake: DISTINCT aur GROUP BY ko same samajhna → Dono unique values dete hain but GROUP BY aggregation bhi kar sakta hai.
Fix: Sirf unique values chahiye → DISTINCT. Aggregate calculations bhi chahiye → GROUP BY. - Mistake: Large tables par DISTINCT overuse karna → Performance issue hoga kyunki sorting/hashing lagti hai.
Fix: Index use karo ya GROUP BY prefer karo jahan possible ho.
💬 Interview Questions:
Q1: What is the difference between DISTINCT and GROUP BY?
Ans: DISTINCT removes duplicate rows and returns unique values — no aggregation. GROUP BY groups rows together allowing aggregate functions (COUNT, SUM, AVG) to be applied per group. For simply getting unique values, DISTINCT is cleaner. For unique values with counts or other aggregations, GROUP BY is needed. Internally MySQL often uses similar mechanisms for both.
Q2: How does DISTINCT handle NULL values?
Ans: DISTINCT treats all NULL values as identical — so multiple NULL values in a column will appear as a single NULL in the result. Example: if city column has 3 rows with NULL, SELECT DISTINCT city will show NULL only once. This is one area where NULL = NULL behavior is different from comparison operators.
Q3: Can DISTINCT be used with COUNT()?
Ans: Yes — COUNT(DISTINCT column) counts only unique non-NULL values in a column. Example: SELECT COUNT(DISTINCT dept) FROM employees returns 4 (IT, HR, Sales, Finance). This is different from COUNT(dept) which would count all non-NULL values including duplicates (14 in our case).
Summary — SELECT Operators Quick Reference
| Operator / Clause | Purpose | Example | Key Point |
|---|---|---|---|
WHERE | Row filtering | WHERE salary > 50000 | Runs before SELECT |
AND / OR / NOT | Combine conditions | WHERE dept='IT' AND salary>70000 | AND priority > OR |
BETWEEN | Range check | WHERE age BETWEEN 25 AND 35 | Inclusive both ends |
IN | List matching | WHERE city IN ('Delhi','Mumbai') | No NULL in NOT IN list |
LIKE | Pattern matching | WHERE name LIKE 'R%' | % = any, _ = one char |
IS NULL | NULL check | WHERE salary IS NULL | = NULL works na karein |
ORDER BY | Sort results | ORDER BY salary DESC | Default ASC |
LIMIT / OFFSET | Pagination | LIMIT 5 OFFSET 10 | Always with ORDER BY |
DISTINCT | Unique values | SELECT DISTINCT dept | All columns combined |
Next: Data Insights MySQL Masterclass — Part 3
Part 3 mein hum cover karenge: Aggregate Functions + GROUP BY + HAVING — COUNT, SUM, AVG, MIN, MAX ke saath real-world analytics queries aur interview questions Data Insights par.
Happy Querying & Keep Learning SQL! 🚀
💬 Comments (0)
Loading comments...