Session 3: Working with Data – Part 1
Selecting & Retrieving Data
SELECT Statements
- The SELECT statement is used to retrieve data from a database.
Basic Syntax:
SELECT column_name FROM table_name;
Example: Selecting student names and IDs from a students table:
SELECT student_id, name FROM students;
To select all columns, use *:
SELECT * FROM students;
Using Aliases (AS)
- Aliases provide temporary names for columns or tables to improve readability.
Syntax:
SELECT column_name AS alias_name FROM table_name;
Example: Renaming columns in the result set:
SELECT product_name AS Product, price AS “Price (USD)” FROM products;
Table Aliases:
SELECT s.name FROM students AS s;
Filtering Data with Comparison Operators
Boolean Data Types & Comparison Operators
- Boolean values (TRUE or FALSE) are used in conditions.
- Comparison operators return boolean results and are used in WHERE clauses to filter data.
| Operator | Description | Example |
| = | Equal to | WHERE age = 30 |
| != or <> | Not equal to | WHERE city != ‘London’ |
| > | Greater than | WHERE salary > 50000 |
| < | Less than | WHERE age < 40 |
| >= | Greater than or equal to | WHERE score >= 90 |
| <= | Less than or equal to | WHERE height <= 5.5 |
| BETWEEN | Within a range (inclusive) | WHERE age BETWEEN 20 AND 30 |
| IN | Matches multiple values | WHERE department IN (‘HR’, ‘Finance’) |
| LIKE | Pattern matching | WHERE name LIKE ‘J%’ |
Using WHERE to Filter Data
Filter by a specific condition:
SELECT * FROM employees WHERE age = 30;
Exclude certain values:
SELECT * FROM employees WHERE age != 30;
Filter using ranges (BETWEEN):
SELECT * FROM employees WHERE age BETWEEN 30 AND 40;
Check if a value exists in a set (IN):
SELECT * FROM employees WHERE name IN (‘Alice’, ‘Bob’);
Using LIKE for Pattern Matching
Find names that start with “J”:
SELECT * FROM students WHERE name LIKE ‘J%’;
Find names that end with “s”:
SELECT * FROM students WHERE name LIKE ‘%s’;
Find names that contain “ar” anywhere in them:
SELECT * FROM students WHERE name LIKE ‘%ar%’;
Key Takeaways
✔ SELECT retrieves data from a database.
✔ Aliases (AS) make query results more readable.
✔ Comparison operators allow filtering specific data.
✔ LIKE is used for pattern-based searches.
✔ BETWEEN, IN, and other conditions help refine queries.
Leave a comment