Persistence: Databases save data to non-volatile storage devices for long-term use. Most enterprise applications use relational databases to persist data from memory to disk.Key Benefits:
The most fundamental SQL operation is querying data:
-- Select all columnsSELECT * FROM employees;-- Select specific columnsSELECT employee_id, first_name, last_name FROM employees;-- With WHERE clause filteringSELECT employee_id, last_name FROM employeesWHERE department_id = 90;
Using SELECT * is not recommended in production as it:
-- DISTINCT removes duplicate rowsSELECT DISTINCT department_id FROM employees;-- Works on combination of all columnsSELECT DISTINCT department_id, salary FROM employees;
-- Fixed-length string (max 255)CHAR(size)-- Variable-length string (max 65,535)VARCHAR(size) -- MUST specify length-- Text types for large contentTEXT -- Up to 4GBLONGTEXT
-- LEFT JOIN - returns all from left tableSELECT e.last_name, d.department_nameFROM employees eLEFT JOIN departments dON e.department_id = d.department_id;-- RIGHT JOIN - returns all from right tableSELECT e.last_name, d.department_nameFROM employees eRIGHT JOIN departments dON e.department_id = d.department_id;
-- Create index on frequently queried columnsCREATE INDEX idx_salary ON employees(salary);-- Composite index for multiple columnsCREATE INDEX idx_dept_salary ON employees(department_id, salary);
-- COUNT, SUM, AVG, MAX, MINSELECT COUNT(*) as total_employees, AVG(salary) as avg_salary, MAX(salary) as max_salary, MIN(salary) as min_salaryFROM employees;-- GROUP BYSELECT department_id, COUNT(*) as emp_count, AVG(salary)FROM employeesGROUP BY department_idHAVING COUNT(*) > 5;
-- Common string operationsSELECT CONCAT(first_name, ' ', last_name) AS full_name, UPPER(last_name) AS upper_name, LENGTH(last_name) AS name_length, SUBSTRING(email, 1, 3) AS email_prefixFROM employees;
-- Date manipulationSELECT NOW() AS current_datetime, CURDATE() AS current_date, DATE_FORMAT(hire_date, '%Y-%m-%d') AS formatted_date, DATEDIFF(NOW(), hire_date) AS days_employedFROM employees;