$ settings --editor

$ settings --general

$ save --settings

SQL for beginners

Filtering a range with BETWEEN #

Checking a range with >= and <= combined by AND works, but SQL gives us a shorter way to write it: BETWEEN.

Syntax #

SELECT
    column_name
FROM
    table_name
WHERE
    column_name BETWEEN low_value AND high_value;

BETWEEN keeps rows where the value is greater than or equal to low_value and less than or equal to high_value. Both endpoints are included.

Example #

SELECT
    *
FROM
    products
WHERE
    price BETWEEN 20 AND 50;

is equivalent to:

SELECT
    *
FROM
    products
WHERE
    price >= 20
    AND price <= 50;

Result:

+----+-------------------+-------------+-------+
| id |       name        |  category   | price |
+----+-------------------+-------------+-------+
| 2  | Bluetooth Speaker  | Electronics | 45.5  |
| 3  |     Yoga Mat       |   Fitness   | 25.0  |
| 6  |    Desk Lamp       |    Home     | 22.0  |
| 8  |      Backpack      |   Office    | 40.0  |
+----+-------------------+-------------+-------+

Products priced below 20 or above 50, like the Wireless Mouse and the Running Shoes, are excluded.


Exercise #

Write a query that retrieves all columns from the products table, keeping only the rows where price is between 20 and 50, inclusive.

  • The result has a price column.
  • The result contains exactly the rows where price is between 20 and 50, and no others.
Solution
SELECT
    *
FROM
    products
WHERE
    price BETWEEN 20 AND 50;
Output will be displayed here