Home Blog Page 23

Using LIMIT and OFFSET in SQL

0
sql course

Table of Contents

  1. Introduction
  2. What is the LIMIT Clause?
  3. Syntax of LIMIT
  4. Why Use LIMIT?
  5. Basic Example of LIMIT
  6. What is the OFFSET Clause?
  7. Syntax of LIMIT with OFFSET
  8. Practical Pagination with LIMIT and OFFSET
  9. Using ORDER BY with LIMIT
  10. Retrieving Top-N Records
  11. Pagination UI and SQL Integration
  12. MySQL vs PostgreSQL vs SQLite: Syntax Notes
  13. Common Errors with LIMIT and OFFSET
  14. LIMIT with Joins
  15. LIMIT in Subqueries
  16. Performance Tips
  17. Real-World Use Cases
  18. Best Practices
  19. Summary Table of Syntax Patterns
  20. Summary and What’s Next

1. Introduction

In SQL, the result of a query can return thousands of records — but often, we only need a subset. The LIMIT and OFFSET clauses let you control how many rows you get and where to start reading from. This is essential for building pagination, leaderboards, and top-ranked reports.


2. What is the LIMIT Clause?

The LIMIT clause restricts the number of rows returned by a query.


3. Syntax of LIMIT

sqlCopyEditSELECT column1, column2
FROM table_name
LIMIT number_of_rows;

Example:

sqlCopyEditSELECT * FROM products
LIMIT 10;

This returns only the first 10 rows of the products table.


4. Why Use LIMIT?

  • Prevents excessive data retrieval
  • Speeds up query performance
  • Useful in pagination, previews, summaries
  • Reduces network and UI load

5. Basic Example of LIMIT

sqlCopyEditSELECT name, price FROM products
ORDER BY price DESC
LIMIT 5;

This returns the 5 most expensive products.


6. What is the OFFSET Clause?

OFFSET skips a specified number of rows before starting to return rows.


7. Syntax of LIMIT with OFFSET

sqlCopyEditSELECT column1, column2
FROM table_name
ORDER BY column
LIMIT number_of_rows OFFSET number_to_skip;

Example:

sqlCopyEditSELECT name FROM students
ORDER BY marks DESC
LIMIT 10 OFFSET 10;

This retrieves records 11 to 20 in descending marks order.


8. Practical Pagination with LIMIT and OFFSET

For page 1 of 10 items per page:

sqlCopyEditSELECT * FROM users
ORDER BY id
LIMIT 10 OFFSET 0;

For page 2:

sqlCopyEditLIMIT 10 OFFSET 10;

For page N:

sqlCopyEditLIMIT 10 OFFSET (N - 1) * 10;

Use in web apps to handle pagination efficiently.


9. Using ORDER BY with LIMIT

Always combine LIMIT with ORDER BY to get predictable, meaningful results:

sqlCopyEditSELECT * FROM orders
ORDER BY order_date DESC
LIMIT 5;

Without ORDER BY, the order of rows is not guaranteed.


10. Retrieving Top-N Records

sqlCopyEditSELECT name, salary FROM employees
ORDER BY salary DESC
LIMIT 3;

Get top 3 highest-paid employees.


11. Pagination UI and SQL Integration

PageSQL Query Example
1LIMIT 10 OFFSET 0
2LIMIT 10 OFFSET 10
3LIMIT 10 OFFSET 20

Works with frontend frameworks (React, Angular, etc.) via API calls that support page numbers.


12. MySQL vs PostgreSQL vs SQLite: Syntax Notes

FeatureMySQLPostgreSQLSQLite
LIMIT only✅✅✅
LIMIT + OFFSET✅✅✅
OFFSET keyword requiredYesYesYes

You can also use this compact format (PostgreSQL, SQLite):

sqlCopyEditSELECT * FROM table
LIMIT 10, 20;  -- Fetch 20 rows, starting from offset 10 (MySQL only)

13. Common Errors with LIMIT and OFFSET

  • Using LIMIT without ORDER BY (leads to random results)
  • Incorrect offset math in pagination
  • Forgetting that OFFSET starts from 0
  • Overusing high OFFSET values can degrade performance

14. LIMIT with Joins

sqlCopyEditSELECT u.name, o.total
FROM users u
JOIN orders o ON u.id = o.user_id
ORDER BY o.total DESC
LIMIT 10;

LIMIT applies after the join result is computed.


15. LIMIT in Subqueries

sqlCopyEditSELECT * FROM (
  SELECT * FROM products
  ORDER BY price DESC
  LIMIT 5
) AS top_products
ORDER BY price ASC;

Use subqueries when needing multiple sorted stages.


16. Performance Tips

  • Avoid high OFFSET values on large datasets
  • Consider using key-based pagination (e.g., WHERE id > last_seen_id)
  • Add indexes on columns used in ORDER BY

17. Real-World Use Cases

  • Product catalog pagination
  • Paginating blog posts or search results
  • Top N performers in a leaderboard
  • Infinite scrolling in modern web apps

18. Best Practices

  • Always use ORDER BY with LIMIT
  • Validate page number to prevent invalid offsets
  • Use indexes to support sorted fields
  • For large datasets, consider cursor-based or seek-based pagination instead of OFFSET

19. Summary Table of Syntax Patterns

Use CaseSQL Syntax Example
Top 5 usersSELECT * FROM users ORDER BY score DESC LIMIT 5
Page 2 of 10LIMIT 10 OFFSET 10
Skip 50, take 20LIMIT 20 OFFSET 50
Last 5 ordersORDER BY order_date DESC LIMIT 5
With JOINJOIN ... ORDER BY column LIMIT X

20. Summary and What’s Next

The LIMIT and OFFSET clauses are essential tools for managing how much data is returned from a query. They power everything from pagination to performance optimization.

Sorting Results with ORDER BY in SQL

0
sql course

Table of Contents

  1. Introduction
  2. What is the ORDER BY Clause?
  3. Basic Syntax of ORDER BY
  4. Sorting in Ascending Order (ASC)
  5. Sorting in Descending Order (DESC)
  6. Default Sorting Behavior
  7. Sorting by Multiple Columns
  8. Sorting by Column Positions
  9. Sorting by Aliased Columns
  10. Sorting Text vs Numbers
  11. Sorting by Date and Time
  12. Sorting with NULL Values
  13. Using ORDER BY with LIMIT
  14. Combining ORDER BY with WHERE
  15. Real-World Examples of Sorting
  16. Performance Considerations
  17. ORDER BY vs GROUP BY
  18. Common Mistakes and How to Avoid Them
  19. Best Practices for Sorting
  20. Summary and What’s Next

1. Introduction

When working with SQL queries, the order in which rows are returned is not guaranteed unless you explicitly define it using the ORDER BY clause. Whether you’re building a leaderboard, a product list, or a list of recent transactions — ORDER BY is essential.


2. What is the ORDER BY Clause?

The ORDER BY clause in SQL is used to sort the result set returned by a SELECT query. You can sort data ascendingly or descendingly based on one or more columns.


3. Basic Syntax of ORDER BY

sqlCopyEditSELECT column1, column2
FROM table_name
ORDER BY column1 [ASC | DESC];

Example:

sqlCopyEditSELECT name, age FROM users
ORDER BY age;

4. Sorting in Ascending Order (ASC)

This is the default behavior:

sqlCopyEditSELECT name FROM employees
ORDER BY name ASC;

It sorts alphabetically (A–Z) or numerically (low to high).


5. Sorting in Descending Order (DESC)

Use DESC to sort in reverse order:

sqlCopyEditSELECT name, salary FROM employees
ORDER BY salary DESC;

This is useful for rankings, top-scorers, etc.


6. Default Sorting Behavior

If you do not specify a direction, SQL assumes ASC by default:

sqlCopyEditORDER BY age;  -- same as ORDER BY age ASC

7. Sorting by Multiple Columns

Sort first by one column, then by another:

sqlCopyEditSELECT * FROM users
ORDER BY city ASC, age DESC;

This sorts users by city alphabetically and then by age (older users first) within each city.


8. Sorting by Column Positions

You can also use column position numbers:

sqlCopyEditSELECT name, age, salary FROM employees
ORDER BY 3 DESC, 2 ASC;

This sorts by the 3rd column (salary), then 2nd column (age). While concise, this is less readable and more error-prone — use with caution.


9. Sorting by Aliased Columns

If you use AS to alias a column, you can sort by that alias:

sqlCopyEditSELECT name, salary * 12 AS annual_salary
FROM employees
ORDER BY annual_salary DESC;

10. Sorting Text vs Numbers

  • Strings sort lexicographically (alphabetically)
  • Numbers sort mathematically

Example:

sqlCopyEditSELECT name, department FROM employees
ORDER BY department;

Departments are ordered alphabetically:
Accounting, Engineering, Finance, etc.


11. Sorting by Date and Time

sqlCopyEditSELECT * FROM orders
ORDER BY order_date DESC;

This is especially useful to get:

  • Most recent orders
  • Latest login
  • Chronological events

12. Sorting with NULL Values

Different databases handle NULL differently:

  • MySQL: NULL appears first with ASC, last with DESC
  • PostgreSQL: allows NULLS FIRST or NULLS LAST explicitly:
sqlCopyEditSELECT * FROM products
ORDER BY discount DESC NULLS LAST;

13. Using ORDER BY with LIMIT

You can combine ORDER BY with LIMIT to retrieve top/bottom results:

sqlCopyEdit-- Top 5 highest salaries
SELECT name, salary FROM employees
ORDER BY salary DESC
LIMIT 5;

14. Combining ORDER BY with WHERE

sqlCopyEditSELECT name, age FROM users
WHERE is_active = TRUE
ORDER BY age DESC;

Filter first, then sort — always.


15. Real-World Examples of Sorting

Sort Top 3 Cities by Number of Users:

sqlCopyEditSELECT city, COUNT(*) AS user_count
FROM users
GROUP BY city
ORDER BY user_count DESC
LIMIT 3;

Sort Products by Price (Low to High):

sqlCopyEditSELECT product_name, price FROM products
ORDER BY price ASC;

16. Performance Considerations

  • Sorting large datasets may slow down performance.
  • Use indexes on frequently sorted columns.
  • Avoid sorting unfiltered data unless necessary.

17. ORDER BY vs GROUP BY

FeatureORDER BYGROUP BY
PurposeSorts dataAggregates data
OutputReturns individual rows in orderReturns one row per group
Used WithAny queryOften with COUNT, SUM, AVG

18. Common Mistakes and How to Avoid Them

  • Assuming implicit order: SQL results are not ordered unless you specify ORDER BY
  • Sorting by columns not included in SELECT without understanding scope
  • Using column positions instead of names — prone to break in refactors
  • Sorting before filtering (should be after WHERE)

19. Best Practices for Sorting

  • Always explicitly specify ASC or DESC for clarity
  • Use column names over column positions
  • Combine ORDER BY with LIMIT for better performance on top results
  • Add indexes to columns that are frequently sorted

20. Summary and What’s Next

The ORDER BY clause empowers you to return data in a meaningful order, making your results more readable and more useful in applications. By sorting on columns like names, prices, dates, or computed values, you can build everything from reports to dashboards.

Logical Operators in SQL: AND, OR, NOT

0
sql course

Table of Contents

  1. Introduction
  2. What Are Logical Operators in SQL?
  3. The Role of Logical Operators in Filtering
  4. Basic Syntax and Usage
  5. Using AND to Combine Conditions
  6. Using OR to Widen Conditions
  7. Using NOT to Invert Conditions
  8. Combining AND and OR
  9. Operator Precedence: NOT, AND, OR
  10. Controlling Logic with Parentheses
  11. Real-World Use Case: Employee Filtering
  12. Real-World Use Case: Product Search
  13. Using Logical Operators in UPDATE
  14. Using Logical Operators in DELETE
  15. Logical Operators with NULL Checks
  16. Performance Considerations
  17. Common Mistakes to Avoid
  18. Best Practices
  19. Summary Table of Logical Use Cases
  20. Summary and What’s Next

1. Introduction

SQL logical operators — AND, OR, and NOT — are essential for writing powerful and flexible filtering conditions. They allow you to combine multiple expressions in your WHERE clause to get precise control over query results.


2. What Are Logical Operators in SQL?

Logical operators are used to combine or negate conditions in a WHERE clause. You can filter data using multiple rules instead of just one.


3. The Role of Logical Operators in Filtering

Instead of writing separate queries for each condition, logical operators let you write complex filters within a single SQL statement:

sqlCopyEditSELECT * FROM employees 
WHERE department = 'IT' AND age > 30;

4. Basic Syntax and Usage

sqlCopyEditSELECT column1, column2
FROM table_name
WHERE condition1 [AND|OR|NOT] condition2;

Example:

sqlCopyEditSELECT * FROM users
WHERE city = 'Mumbai' AND is_active = TRUE;

5. Using AND to Combine Conditions

The AND operator returns true only if both conditions are true:

sqlCopyEditSELECT * FROM orders 
WHERE status = 'shipped' AND payment_method = 'UPI';

Example Output Logic:

statuspayment_methodIncluded
shippedUPI✅
shippedCredit Card❌
pendingUPI❌

6. Using OR to Widen Conditions

The OR operator returns true if either condition is true:

sqlCopyEditSELECT * FROM employees 
WHERE department = 'HR' OR department = 'Admin';

You can match rows from either department.


7. Using NOT to Invert Conditions

The NOT operator negates the result of a condition:

sqlCopyEditSELECT * FROM users WHERE NOT city = 'Delhi';

This returns all users not from Delhi.

More examples:

sqlCopyEditSELECT * FROM orders WHERE NOT status = 'cancelled';
SELECT * FROM customers WHERE NOT age BETWEEN 18 AND 25;

8. Combining AND and OR

You can use both AND and OR together for more advanced logic:

sqlCopyEditSELECT * FROM employees 
WHERE (department = 'HR' OR department = 'Finance') 
AND age > 30;

This selects employees from HR or Finance who are also older than 30.


9. Operator Precedence: NOT, AND, OR

SQL evaluates operators in the following order:

  1. NOT
  2. AND
  3. OR

So this query:

sqlCopyEditSELECT * FROM users 
WHERE NOT age < 18 AND city = 'Mumbai' OR is_active = TRUE;

Is interpreted as:

sqlCopyEdit((NOT age < 18) AND (city = 'Mumbai')) OR (is_active = TRUE)

Use parentheses to avoid ambiguity.


10. Controlling Logic with Parentheses

Parentheses clarify and control precedence:

sqlCopyEditSELECT * FROM orders 
WHERE status = 'shipped' AND (payment_method = 'UPI' OR payment_method = 'Wallet');

Without parentheses, SQL may evaluate logic differently than intended.


11. Real-World Use Case: Employee Filtering

sqlCopyEditSELECT * FROM employees
WHERE department = 'IT' 
  AND (experience > 5 OR salary > 60000);

This returns IT employees who either have more than 5 years of experience or earn more than 60K.


12. Real-World Use Case: Product Search

sqlCopyEditSELECT * FROM products 
WHERE (category = 'Books' OR category = 'Stationery') 
  AND price < 500;

Use logical operators to create advanced filters on e-commerce search or dashboards.


13. Using Logical Operators in UPDATE

sqlCopyEditUPDATE users
SET status = 'inactive'
WHERE last_login < '2024-01-01' AND is_active = TRUE;

You can update based on multiple logical checks.


14. Using Logical Operators in DELETE

sqlCopyEditDELETE FROM logs 
WHERE severity = 'low' OR created_at < '2023-01-01';

This removes either old or low-priority logs.


15. Logical Operators with NULL Checks

sqlCopyEditSELECT * FROM users
WHERE phone IS NULL OR email IS NULL;

You can combine logical operators with IS NULL, IS NOT NULL.


16. Performance Considerations

  • Use indexed columns in conditions to speed up filtering.
  • Avoid overly complex conditions in huge datasets without proper indexing.
  • Group conditions for efficient evaluation.

17. Common Mistakes to Avoid

  • Forgetting parentheses when combining AND and OR
  • Incorrect assumptions about precedence
  • Using = for NULL comparisons (instead of IS NULL)
  • Neglecting quotes around string literals

18. Best Practices

  • Always group complex expressions with parentheses
  • Test each condition individually before combining
  • Prioritize readability — future you will thank you
  • Use logical operators to reduce the number of queries

19. Summary Table of Logical Use Cases

OperatorUse CaseExample
ANDAll conditions must be trueWHERE salary > 50000 AND city = 'Delhi'
ORAt least one condition must be trueWHERE city = 'Delhi' OR city = 'Mumbai'
NOTInvert a conditionWHERE NOT is_active = TRUE
CombinedAdvanced conditionsWHERE (role = 'admin' OR role = 'editor') AND active

20. Summary and What’s Next

Logical operators are indispensable in SQL for writing meaningful filters. They make your WHERE clauses far more powerful by allowing multiple conditions and combinations.

Using the WHERE Clause for Filtering

0
sql course

Table of Contents

  1. Introduction
  2. What is the WHERE Clause?
  3. Basic Syntax of WHERE
  4. Filtering with Equality Conditions
  5. Using !=, <>, and NOT
  6. Greater Than and Less Than Comparisons
  7. Filtering Text with LIKE
  8. Wildcards in LIKE: % and _
  9. Using IN to Match Multiple Values
  10. Filtering Between Ranges with BETWEEN
  11. Handling NULL Values
  12. Logical Operators: AND, OR, and NOT
  13. Precedence in Conditional Expressions
  14. Combining Multiple Conditions
  15. WHERE Clause in Numeric Fields
  16. WHERE Clause in Date Fields
  17. WHERE Clause in String Fields
  18. Using WHERE with Subqueries
  19. Common Mistakes and Troubleshooting
  20. Summary and What’s Next

1. Introduction

The WHERE clause is one of the most important tools in SQL. It allows you to filter records in a table by specifying one or more conditions. This means instead of retrieving every row, you can retrieve just the data you need.


2. What is the WHERE Clause?

The WHERE clause is used in SQL to filter records before they are selected, updated, or deleted. It is applicable in:

  • SELECT
  • UPDATE
  • DELETE

3. Basic Syntax of WHERE

sqlCopyEditSELECT column1, column2
FROM table_name
WHERE condition;

Example:

sqlCopyEditSELECT * FROM employees WHERE age > 30;

4. Filtering with Equality Conditions

The simplest use case of WHERE is to check equality:

sqlCopyEditSELECT * FROM users WHERE country = 'India';
SELECT * FROM orders WHERE status = 'delivered';

5. Using !=, <>, and NOT

You can use either != or <> for “not equal to”:

sqlCopyEditSELECT * FROM products WHERE category != 'Electronics';
SELECT * FROM students WHERE grade <> 'A';

Or use NOT:

sqlCopyEditSELECT * FROM customers WHERE NOT city = 'Delhi';

6. Greater Than and Less Than Comparisons

sqlCopyEditSELECT * FROM sales WHERE amount > 1000;
SELECT * FROM inventory WHERE quantity < 50;

Also:

  • >= greater than or equal to
  • <= less than or equal to

7. Filtering Text with LIKE

The LIKE operator is used to match text patterns:

sqlCopyEditSELECT * FROM users WHERE name LIKE 'A%';   -- starts with A
SELECT * FROM users WHERE email LIKE '%@gmail.com'; -- ends with

8. Wildcards in LIKE: % and _

WildcardMeaning
%Matches any number of characters
_Matches exactly one character

Example:

sqlCopyEditSELECT * FROM books WHERE title LIKE '_ar%';  -- Matches 'Harry', 'Dark', etc.

9. Using IN to Match Multiple Values

sqlCopyEditSELECT * FROM employees WHERE department IN ('HR', 'Finance', 'Sales');

This is cleaner than using multiple OR conditions.


10. Filtering Between Ranges with BETWEEN

sqlCopyEditSELECT * FROM products WHERE price BETWEEN 100 AND 500;

This is inclusive — both 100 and 500 are part of the result.


11. Handling NULL Values

Use IS NULL and IS NOT NULL:

sqlCopyEditSELECT * FROM users WHERE email IS NULL;
SELECT * FROM users WHERE phone IS NOT NULL;

NULL cannot be compared using = or !=.


12. Logical Operators: AND, OR, and NOT

You can combine multiple conditions:

sqlCopyEditSELECT * FROM orders 
WHERE status = 'shipped' AND payment_method = 'Credit Card';
sqlCopyEditSELECT * FROM users 
WHERE age > 30 OR city = 'Mumbai';
sqlCopyEditSELECT * FROM employees 
WHERE NOT department = 'Sales';

13. Precedence in Conditional Expressions

Parentheses help control evaluation order:

sqlCopyEditSELECT * FROM users 
WHERE (age > 25 AND city = 'Pune') OR is_active = TRUE;

Always group related conditions to avoid logical errors.


14. Combining Multiple Conditions

sqlCopyEditSELECT * FROM events
WHERE city = 'Delhi' AND category IN ('Music', 'Art') AND date BETWEEN '2024-01-01' AND '2024-12-31';

You can build powerful filters using combinations of:

  • IN
  • BETWEEN
  • LIKE
  • AND/OR logic

15. WHERE Clause in Numeric Fields

sqlCopyEditSELECT * FROM invoices WHERE total_amount > 10000;

Use numeric filtering for salaries, scores, stock counts, etc.


16. WHERE Clause in Date Fields

sqlCopyEditSELECT * FROM reservations 
WHERE reservation_date >= '2025-01-01' AND reservation_date <= '2025-01-31';

SQL supports date comparisons directly. Use the proper format (YYYY-MM-DD).


17. WHERE Clause in String Fields

sqlCopyEditSELECT * FROM customers WHERE name = 'Ravi Kumar';
SELECT * FROM customers WHERE email LIKE '%@yahoo.com';

Always enclose string values in single quotes (').


18. Using WHERE with Subqueries

sqlCopyEditSELECT * FROM users 
WHERE id IN (SELECT user_id FROM orders WHERE total > 1000);

Subqueries help filter based on the result of another query.


19. Common Mistakes and Troubleshooting

  • Using = instead of IS NULL
  • Forgetting quotes around string values
  • Mixing AND/OR without parentheses
  • Using incorrect operators (=> instead of >=)
  • Not checking for case sensitivity in string filters

20. Summary and What’s Next

The WHERE clause is essential for filtering data in SQL. It supports comparisons, pattern matching, range checks, null checks, and more — making your queries precise and powerful.

Introduction to the SELECT Statement

0
sql course

Table of Contents

  1. Introduction
  2. What is the SELECT Statement?
  3. Basic Syntax of SELECT
  4. Selecting All Columns with *
  5. Selecting Specific Columns
  6. Using Aliases with AS
  7. Selecting Distinct Records
  8. Filtering Results with WHERE
  9. Logical Operators: AND, OR, NOT
  10. Comparison Operators
  11. Working with NULL
  12. Sorting Results with ORDER BY
  13. Limiting Results with LIMIT
  14. Selecting Based on Ranges: BETWEEN
  15. Using IN to Match Multiple Values
  16. Pattern Matching with LIKE
  17. Combining Conditions
  18. Real-World Query Examples
  19. Best Practices for SELECT Queries
  20. Summary and What’s Next

1. Introduction

The SELECT statement is the foundation of SQL. It’s the command used to retrieve data from a database. Whether you’re pulling records from a table, filtering data, or aggregating it for analysis, SELECT is your go-to tool.

In this module, we’ll explore everything you need to know to write your first SELECT queries confidently.


2. What is the SELECT Statement?

The SELECT statement retrieves rows from one or more tables or views. It allows you to specify which columns you want, apply conditions, sort, limit, and more.


3. Basic Syntax of SELECT

SELECT column1, column2
FROM table_name;

Example:

SELECT name, email FROM users;

4. Selecting All Columns with *

The asterisk (*) selects all columns:

SELECT * FROM users;

Useful for quick debugging or exploration, but avoid it in production queries for performance reasons.


5. Selecting Specific Columns

You can specify only the columns you need:

SELECT name, age FROM employees;

This improves performance and makes results easier to understand.


6. Using Aliases with AS

Aliases give columns or tables temporary names:

SELECT name AS full_name, age AS years_old FROM users;

You can also alias tables:

SELECT u.name FROM users AS u;

7. Selecting Distinct Records

To eliminate duplicates:

SELECT DISTINCT city FROM customers;

DISTINCT ensures only unique values are returned.


8. Filtering Results with WHERE

The WHERE clause is used to filter records based on conditions.

SELECT * FROM orders WHERE total > 500;

You can use:

  • Comparison operators: =, !=, <, >, <=, >=
  • Logical operators: AND, OR, NOT
  • Special conditions: IN, BETWEEN, LIKE, IS NULL

9. Logical Operators: AND, OR, NOT

Combine multiple conditions:

sqlCopyEditSELECT * FROM employees 
WHERE department = 'HR' AND age > 30;
sqlCopyEditSELECT * FROM employees 
WHERE department = 'HR' OR department = 'Finance';
sqlCopyEditSELECT * FROM employees 
WHERE NOT age < 18;

10. Comparison Operators

OperatorMeaning
=Equal to
!= or <>Not equal to
<Less than
>Greater than
<=Less than or equal
>=Greater or equal

Example:

sqlCopyEditSELECT * FROM products WHERE price <= 1000;

11. Working with NULL

NULL represents missing or unknown data. You cannot use = or != to compare NULL.

Use:

sqlCopyEditSELECT * FROM users WHERE email IS NULL;
SELECT * FROM users WHERE email IS NOT NULL;

12. Sorting Results with ORDER BY

sqlCopyEditSELECT name, age FROM users ORDER BY age;
SELECT name, age FROM users ORDER BY age DESC;

You can sort by one or more columns.


13. Limiting Results with LIMIT

Restrict number of rows:

sqlCopyEditSELECT * FROM users LIMIT 5;

MySQL and PostgreSQL support:

sqlCopyEditSELECT * FROM users LIMIT 5 OFFSET 10;

SQLite also supports this syntax.


14. Selecting Based on Ranges: BETWEEN

Check if a value falls within a range:

sqlCopyEditSELECT * FROM products WHERE price BETWEEN 100 AND 500;

Inclusive: includes both 100 and 500.


15. Using IN to Match Multiple Values

sqlCopyEditSELECT * FROM customers 
WHERE country IN ('India', 'Nepal', 'Bangladesh');

IN is cleaner and more efficient than multiple OR conditions.


16. Pattern Matching with LIKE

Use LIKE for partial matches with % and _.

sqlCopyEditSELECT * FROM users WHERE name LIKE 'A%';  -- Starts with A
SELECT * FROM users WHERE email LIKE '%@gmail.com';  -- Ends with
SELECT * FROM users WHERE name LIKE '_ohn'; -- Matches 4-letter name ending in "ohn"

17. Combining Conditions

sqlCopyEditSELECT * FROM employees
WHERE department = 'Sales' 
  AND (age > 30 OR city = 'Delhi');

Use parentheses to group complex logic for clarity and accuracy.


18. Real-World Query Examples

Find all active users above 25 years of age:

sqlCopyEditSELECT name, email FROM users
WHERE age > 25 AND is_active = TRUE;

Get top 3 highest-paying jobs:

sqlCopyEditSELECT title, salary FROM jobs
ORDER BY salary DESC
LIMIT 3;

Search for customers not in India or Nepal:

sqlCopyEditSELECT * FROM customers
WHERE country NOT IN ('India', 'Nepal');

19. Best Practices for SELECT Queries

  • Avoid using SELECT * in production
  • Use meaningful aliases for readability
  • Filter early with WHERE to improve performance
  • Sort data after filtering, not before
  • Use indexes wisely for large datasets

20. Summary and What’s Next

The SELECT statement is your entry point to reading and analyzing data. Mastering it will help you query any relational database confidently. We’ve covered syntax, filtering, sorting, and limiting — all crucial to practical SQL use.