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.
OperatorDescriptionExample
=Equal toWHERE age = 30
!= or <>Not equal toWHERE city != ‘London’
>Greater thanWHERE salary > 50000
<Less thanWHERE age < 40
>=Greater than or equal toWHERE score >= 90
<=Less than or equal toWHERE height <= 5.5
BETWEENWithin a range (inclusive)WHERE age BETWEEN 20 AND 30
INMatches multiple valuesWHERE department IN (‘HR’, ‘Finance’)
LIKEPattern matchingWHERE 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