- Create a database
CREATE DATABASE mydatabase;
- Drop a database
DROP DATABASE mydatabase;
- Create a table
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL,
email VARCHAR(100) NOT NULL
);
- Drop a table
DROP TABLE users;
- Insert a record into a table
INSERT INTO users (username, email) VALUES (‘john_doe’, ‘john@example.com’);
- Update records in a table
UPDATE users SET email = ‘new_email@example.com’ WHERE username = ‘john_doe’;
- Delete records from a table
DELETE FROM users WHERE username = ‘john_doe’;
- Select all records from a table
SELECT * FROM users;
- Select specific columns from a table
SELECT username, email FROM users;
- Select records with a condition
SELECT * FROM users WHERE id = 1;
- Select records with multiple conditions
SELECT * FROM users WHERE username = ‘john_doe’ AND email = ‘john@example.com’;
- Select records with pattern matching
SELECT * FROM users WHERE username LIKE ‘john%’;
- Order records in ascending order
SELECT * FROM users ORDER BY username ASC;
- Order records in descending order
SELECT * FROM users ORDER BY username DESC;
- Limit the number of records returned
SELECT * FROM users LIMIT 10;
- Offset the start of records returned
SELECT * FROM users LIMIT 10 OFFSET 20;
- Count the number of records in a table
SELECT COUNT(*) FROM users;
- Sum of values in a column
SELECT SUM(sales) FROM transactions;
- Average value in a column
SELECT AVG(price) FROM products;
- Maximum value in a column
SELECT MAX(score) FROM exam_results;
- Minimum value in a column
SELECT MIN(age) FROM employees;
- Group records by a column
SELECT department, COUNT(*) FROM employees GROUP BY department;
- Join two tables
SELECT users.username, orders.order_id
FROM users
INNER JOIN orders ON users.id = orders.user_id;
- Left join two tables
SELECT users.username, orders.order_id
FROM users
LEFT JOIN orders ON users.id = orders.user_id;
- Right join two tables
SELECT users.username, orders.order_id
FROM users
RIGHT JOIN orders ON users.id = orders.user_id;
- Full outer join two tables
SELECT users.username, orders.order_id
FROM users
FULL OUTER JOIN orders ON users.id = orders.user_id;
- Create an index on a table
CREATE INDEX idx_username ON users (username);
- Drop an index from a table
DROP INDEX idx_username ON users;
- Grant privileges to a user
GRANT SELECT, INSERT, UPDATE ON mydatabase.* TO ‘username’@’localhost’ IDENTIFIED BY ‘password’;
- Revoke privileges from a user
REVOKE SELECT, INSERT, UPDATE ON mydatabase.* FROM ‘username’@’localhost’;
Top comments (0)