Basic SQL Queries: SELECT, WHERE, Filtering 🖥️
What SELECT Does
- SELECT chooses columns
- You decide what data you want to see
- Database returns only those columns
Example Table: customers
customer_id | name | city | signup_date
101 | Rahul | Pune | 2024-01-15
102 | Neha | Mumbai | 2024-02-10
103 | Amit | Delhi | 2024-03-05
104 | Priya | Pune | 2024-04-20
Basic SELECT
SELECT name, city FROM customers;Output
name | city
Rahul | Pune
Neha | Mumbai
Amit | Delhi
Priya | Pune
What Happens
- Database scans all rows
- Returns name and city columns
- No filtering yet
Why SELECT Matters
- Smaller output
- Faster queries
- Clear analysis
What WHERE Does
- WHERE filters rows
- It answers conditions like who, when, how much
Think Like This
- SELECT decides columns
- WHERE decides rows
Basic WHERE Example
SELECT name, city FROM customers WHERE city = 'Pune';Output
name | city
Rahul | Pune
Priya | Pune
Common Operators
- = equal
- != not equal
- > greater than
- < less than
- > =, <=
Example
SELECT name, signup_date FROM customers WHERE signup_date >= '2024-03-01';Output
name | signup_date
Amit | 2024-03-05
Priya | 2024-04-20
Logical Filters
AND
- All conditions must match
Example:
SELECT name FROM customers WHERE city = 'Pune' AND signup_date >= '2024-01-01';Output
name
Rahul
Priya
OR
- Any condition can match
Example:
SELECT name FROM customers WHERE city = 'Pune' OR city = 'Mumbai';Output
name
Rahul
Neha
Priya
IN
- Shortcut for multiple OR conditions
Example:
SELECT name FROM customers WHERE city IN ('Pune','Mumbai','Delhi');Output
name
Rahul
Neha
Amit
Priya
BETWEEN
- Filters within a range
- Inclusive of start and end
Example:
SELECT name FROM customers WHERE signup_date BETWEEN '2024-01-01' AND '2024-03-31';Output
name
Rahul
Neha
Amit
Filtering Numbers
Example table: orders
order_id | customer_id | amount | order_date
1 | 101 | 3000 | 2024-01-16
2 | 102 | 6000 | 2024-02-11
3 | 103 | 4000 | 2024-03-06
SELECT order_id, amount FROM orders WHERE amount > 5000;Output
order_id | amount
2 | 6000
Filtering Text
- Text values go inside quotes
- Case sensitivity depends on database
Filtering NULL Values
- NULL means missing value
- = NULL does not work
Correct way:
SELECT name FROM customers WHERE city IS NULL;Assume city is NULL for customer_id 103
Output
name
Amit
Exclude NULL:
SELECT name FROM customers WHERE city IS NOT NULL;Output
name
Rahul
Neha
Priya
How SELECT and WHERE Work Together
- FROM picks the table
- WHERE filters rows
- SELECT picks columns
- Result is sent back
Real Business Example
- Manager asks for Pune customers with orders above 5,000
- WHERE applies city and amount filters
- SELECT shows required columns
Assume orders table has customer_id 101 with amount 6000
SELECT name FROM customers WHERE city = 'Pune' AND customer_id IN (SELECT customer_id FROM orders WHERE amount > 5000);Output
name
Rahul
Common Beginner Mistakes
- Using WHERE before FROM
- Forgetting quotes for text
- Using = NULL
- Writing SELECT * always
Double Tap ♥️ For More