SQL
SQL
Example:
-- Create a table
CREATE TABLE students (id INT PRIMARY KEY, name VARCHAR(100), age INT);
-- Insert data
INSERT INTO students (id, name, age) VALUES (1, 'John', 20);
-- Read data
SELECT * FROM students;
-- Update data
UPDATE students SET age = 21 WHERE id = 1;
-- Delete data
DELETE FROM students WHERE id = 1;
SQL vs MySQL:
SQL is the query language used to interact with databases.
MySQL is a type of RDBMS (Relational Database Management System) that uses SQL to
store and manage data.
MySQL uses a client-server model where the client (could be a frontend or command
line) interacts with the MySQL server to manage databases.
Example:
SQL is the language:
SELECT * FROM users; -- This is SQL syntax
MySQL is the RDBMS where the SQL query is run.
Example:
-- Using MySQL to create and manage tables
CREATE TABLE employees (id INT PRIMARY KEY, name VARCHAR(50), department
VARCHAR(50));
SQL Data Types:
SQL uses different data types to define the type of data stored in columns.
Common Data Types:
INT: Integer numbers.
VARCHAR(size): Variable-length string (up to a defined size).
DATE: Stores date values in YYYY-MM-DD format.
FLOAT/DOUBLE: For decimal numbers with precision.
Example:
CREATE TABLE products (
id INT,
name VARCHAR(100),
price DOUBLE,
created_at DATE
);
-- Update data
UPDATE employees SET name = 'Alicia' WHERE id = 1;
-- Delete data
DELETE FROM employees WHERE id = 1;
-- Revoke access
REVOKE SELECT, UPDATE ON employees FROM 'username';
SQL Constraints:
Constraints are used to enforce rules at the table level.
Common Constraints:
Primary Key: Uniquely identifies each row.
Foreign Key: Links data between two tables.
UNIQUE: Ensures all values in a column are unique.
CHECK: Ensures a condition is met for each row.
DEFAULT: Provides a default value for a column if no value is specified.
Example:
CREATE TABLE orders (
id INT PRIMARY KEY,
customer_id INT,
amount DOUBLE CHECK (amount > 0),
FOREIGN KEY (customer_id) REFERENCES customers(id)
);
SQL Joins:
Joins are used to combine rows from two or more tables based on a related column.
Types of Joins:
INNER JOIN: Returns rows with matching values in both tables.
LEFT JOIN: Returns all rows from the left table and matching rows from the right
table.
RIGHT JOIN: Returns all rows from the right table and matching rows from the left
table.
FULL JOIN: Returns rows when there is a match in either the left or right table.
CROSS JOIN: Returns the Cartesian product of both tables (every combination).
Example:
-- Inner Join
SELECT employees.name, departments.department_name
FROM employees
INNER JOIN departments ON employees.department_id = departments.id;
-- Left Join
SELECT customers.name, orders.amount
FROM customers
LEFT JOIN orders ON customers.id = orders.customer_id;
Example:
-- Select names starting with 'J'
SELECT * FROM employees WHERE name LIKE 'J%';