Hour 2: SQL Basics
1. SELECT Statement
- Syntax:
SELECT column1, column2 FROM table_name;
- Purpose: Retrieve data from one or more columns in a table.
- Example:
Retrieve first name and last name from employees table:
SELECT first_name, last_name FROM employees;
2. Filtering Data with WHERE
- Syntax:
SELECT column1 FROM table_name WHERE condition;
- Conditions: Use operators like '=', '>', '<', 'BETWEEN', 'IN', etc.
- Examples:
a. Find employees with a salary greater than 50,000:
SELECT * FROM employees WHERE salary > 50000;
b. Find employees in specific departments (10, 20, 30):
SELECT * FROM employees WHERE department_id IN (10, 20, 30);
c. Find employees hired between two dates:
SELECT * FROM employees WHERE hire_date BETWEEN TO_DATE('2023-01-01', 'YYYY-
MM-DD') AND TO_DATE('2023-12-31', 'YYYY-MM-DD');
d. Find employees whose name starts with 'A':
SELECT * FROM employees WHERE first_name LIKE 'A%';
3. Limiting Results
- Syntax (Oracle 12c+):
SELECT * FROM table_name FETCH FIRST n ROWS ONLY;
- Examples:
a. Get the first 5 employees:
SELECT * FROM employees FETCH FIRST 5 ROWS ONLY;
b. Get the first 3 employees with the highest salary:
SELECT * FROM employees ORDER BY salary DESC FETCH FIRST 3 ROWS ONLY;