MySQL Quick Notes
MySQL Constraints
NOT NULL: Ensures a column cannot have NULL values.
CREATE TABLE users (id INT NOT NULL);
UNIQUE: Ensures all values in a column are different.
CREATE TABLE users (email VARCHAR(100) UNIQUE);
PRIMARY KEY: Uniquely identifies each record in a table.
CREATE TABLE users (id INT PRIMARY KEY);
FOREIGN KEY: Links two tables using a related column.
CREATE TABLE orders (user_id INT, FOREIGN KEY (user_id) REFERENCES
users(id));
CHECK: Ensures that column values satisfy a condition.
CREATE TABLE products (price DECIMAL CHECK (price > 0));
DEFAULT: Sets a default value if no value is provided.
CREATE TABLE users (status VARCHAR(20) DEFAULT 'active');
INDEX: Improves query performance by creating indexes.
CREATE INDEX idx_name ON users(name);
MySQL Aggregate Functions
COUNT(): Returns the number of rows that match a condition.
SELECT COUNT(*) FROM users;
SUM(): Returns the total sum of a numeric column.
SELECT SUM(salary) FROM employees;
AVG(): Returns the average value of a numeric column.
SELECT AVG(age) FROM students;
MIN(): Returns the smallest value in a set.
SELECT MIN(price) FROM products;
MAX(): Returns the largest value in a set.
SELECT MAX(score) FROM tests;
GROUP_CONCAT(): Concatenates values from multiple rows into one string.
SELECT GROUP_CONCAT(name) FROM employees;