MySQL + SQL · Lesson 1
⭐ Complete SQL Commands Reference (All Commands)
1. CREATE DATABASE & USE
Before creating any table, you must first create a database and then select it with USE.
SQL
-- Create a new database CREATE DATABASE school_db; -- Select / switch to that database USE school_db; -- List all databases SHOW DATABASES; -- Check which database is active SELECT DATABASE();
▶ Output
Database changed +--------------------+ | Database | +--------------------+ | school_db | +--------------------+
2. CREATE TABLE + Data Types
A table holds data in rows and columns. Each column has a data type — INT, VARCHAR, DATE, DECIMAL, etc.
SQL
CREATE TABLE students (
roll_no INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(80) NOT NULL,
class INT DEFAULT 10,
marks DECIMAL(5,2) DEFAULT 0,
dob DATE,
email VARCHAR(100) UNIQUE
);| Data Type | Use for | Example |
|---|---|---|
| INT | Whole numbers | age INT |
| DECIMAL(p,s) | Exact decimals (money, marks) | marks DECIMAL(5,2) |
| VARCHAR(n) | Text up to n chars | name VARCHAR(80) |
| TEXT | Long text | description TEXT |
| DATE | Date (YYYY-MM-DD) | dob DATE |
| DATETIME | Date + Time | created_at DATETIME |
| BOOLEAN / TINYINT(1) | True/False | is_active BOOLEAN |
SQL
-- See all tables in current database SHOW TABLES; -- See table structure DESCRIBE students;
3. INSERT Records
INSERT INTO adds one or more rows to a table.
SQL
-- Insert one row
INSERT INTO students (name, class, marks, dob, email)
VALUES ('Aman Sharma', 10, 88.50, '2009-04-15', 'aman@mail.com');
-- Insert multiple rows at once
INSERT INTO students (name, class, marks, dob, email) VALUES
('Priya Gupta', 10, 92.00, '2009-07-22', 'priya@mail.com'),
('Ravi Kumar', 11, 76.50, '2008-03-10', 'ravi@mail.com'),
('Sneha Singh', 11, 85.25, '2008-11-05', 'sneha@mail.com'),
('Arjun Patel', 12, 91.75, '2007-08-30', 'arjun@mail.com');4. SELECT — Show All Records
SELECT is the most used SQL command. It retrieves data from a table.
SQL
-- Show all rows and columns SELECT * FROM students; -- Show only specific columns SELECT name, marks FROM students; -- Show with an alias (rename column in output) SELECT name AS 'Student Name', marks AS 'Total Marks' FROM students;
▶ Output
+----+---------------+-------+-------+ | id | name | class | marks | +----+---------------+-------+-------+ | 1 | Aman Sharma | 10 | 88.50 | | 2 | Priya Gupta | 10 | 92.00 | | 3 | Ravi Kumar | 11 | 76.50 | +----+---------------+-------+-------+
5. Show Specific Columns & Rows
SQL
-- Specific columns only SELECT name, class, marks FROM students; -- Specific row (filter by roll_no) SELECT * FROM students WHERE roll_no = 2; -- Specific column of a specific row SELECT name FROM students WHERE roll_no = 2;
6. WHERE — Filter Rows
WHERE filters rows based on a condition. Use comparison operators: =, !=, >, <, >=, <= and logical: AND, OR, NOT.
SQL
-- Students in class 10 SELECT * FROM students WHERE class = 10; -- Marks greater than 80 SELECT name, marks FROM students WHERE marks > 80; -- Class 10 AND marks > 85 SELECT * FROM students WHERE class = 10 AND marks > 85; -- Class 10 OR class 11 SELECT * FROM students WHERE class = 10 OR class = 11; -- NOT class 12 SELECT * FROM students WHERE NOT class = 12;
7. DISTINCT — Remove Duplicates
DISTINCT returns only unique (non-duplicate) values.
SQL
-- All distinct class values (no repeats) SELECT DISTINCT class FROM students; -- Distinct name + class combinations SELECT DISTINCT name, class FROM students;
▶ Output
+-------+ | class | +-------+ | 10 | | 11 | | 12 | +-------+
8. ORDER BY — Sort Results
SQL
-- Sort by marks ascending (lowest first) SELECT name, marks FROM students ORDER BY marks ASC; -- Sort by marks descending (highest/topper first) SELECT name, marks FROM students ORDER BY marks DESC; -- Find the topper SELECT name, marks FROM students ORDER BY marks DESC LIMIT 1;
9. LIMIT — Restrict Number of Rows
SQL
-- Show only first 3 rows SELECT * FROM students LIMIT 3; -- Skip 2 rows, then show next 3 (pagination) SELECT * FROM students LIMIT 2, 3;
10. UPDATE Records
⚠️ Always use WHERE with UPDATE
Without WHERE, ALL rows get updated!SQL
-- Update one column UPDATE students SET marks = 95.00 WHERE roll_no = 1; -- Update multiple columns UPDATE students SET marks = 90.00, class = 11 WHERE name = 'Aman Sharma'; -- Increase all marks by 5 (bonus marks) UPDATE students SET marks = marks + 5;
11. DELETE Records
⚠️ Always use WHERE with DELETE
Without WHERE, ALL rows get deleted!SQL
-- Delete one row DELETE FROM students WHERE roll_no = 3; -- Delete all class 12 students DELETE FROM students WHERE class = 12; -- Delete all rows (keep table structure) DELETE FROM students; -- TRUNCATE: faster way to delete all rows TRUNCATE TABLE students;
| Command | Deletes | Rollback? | Speed |
|---|---|---|---|
| DELETE | Selected rows | Yes | Slow |
| TRUNCATE | All rows | No | Fast |
| DROP | Entire table | No | Instant |
12. ALTER TABLE — Modify Structure
ALTER TABLE changes the structure of an existing table — add/modify/drop columns.
SQL
-- Add a new column ALTER TABLE students ADD phone VARCHAR(15); -- Add column at a specific position ALTER TABLE students ADD address TEXT AFTER name; -- Change column data type (MODIFY) ALTER TABLE students MODIFY marks DECIMAL(6,2); -- Rename a column (CHANGE) ALTER TABLE students CHANGE phone mobile VARCHAR(15); -- Drop (remove) a column ALTER TABLE students DROP COLUMN address; -- Rename the table ALTER TABLE students RENAME TO student_info;
13. DROP TABLE & DROP DATABASE
⚠️ Cannot be undone!
DROP permanently deletes the table or database and all its data.SQL
-- Drop a table DROP TABLE students; -- Drop only if it exists (no error if not found) DROP TABLE IF EXISTS students; -- Drop the entire database DROP DATABASE school_db; -- Drop database if it exists DROP DATABASE IF EXISTS school_db;
14. Constraints
Constraints are rules on columns that keep data correct, valid and consistent.
14.1 PRIMARY KEY
SQL
-- Inline (at column level)
CREATE TABLE products (
product_id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100) NOT NULL
);
-- Table level (for composite key)
CREATE TABLE order_items (
order_id INT,
product_id INT,
PRIMARY KEY (order_id, product_id)
);14.2 FOREIGN KEY
SQL
CREATE TABLE orders (
order_id INT PRIMARY KEY AUTO_INCREMENT,
student_id INT,
item VARCHAR(100),
FOREIGN KEY (student_id) REFERENCES students(roll_no)
ON DELETE CASCADE
ON UPDATE CASCADE
);14.3 NOT NULL
SQL
CREATE TABLE teachers (
id INT PRIMARY KEY,
name VARCHAR(80) NOT NULL, -- cannot be empty
email VARCHAR(100) -- can be NULL
);14.4 UNIQUE
SQL
CREATE TABLE users (
id INT PRIMARY KEY,
username VARCHAR(50) UNIQUE, -- no two users same username
email VARCHAR(100) UNIQUE
);14.5 CHECK
SQL
CREATE TABLE employees (
id INT PRIMARY KEY,
name VARCHAR(80),
salary DECIMAL(10,2) CHECK (salary > 0),
age INT CHECK (age >= 18 AND age <= 65)
);14.6 DEFAULT
SQL
CREATE TABLE posts (
id INT PRIMARY KEY AUTO_INCREMENT,
title VARCHAR(200) NOT NULL,
status VARCHAR(20) DEFAULT 'draft', -- 'draft' if not given
created_at DATETIME DEFAULT NOW() -- auto timestamp
);| Constraint | Purpose | NULL allowed? |
|---|---|---|
| PRIMARY KEY | Unique row identifier | No |
| FOREIGN KEY | Links to another table's PK | Yes (unless NOT NULL) |
| NOT NULL | Column must have a value | No |
| UNIQUE | No duplicate values | Yes (once) |
| CHECK | Value must satisfy condition | Yes |
| DEFAULT | Automatic value if none given | Yes |
15. Aggregate Functions
Aggregate functions work on a set of rows and return one result: COUNT, SUM, AVG, MIN, MAX.
SQL
-- COUNT: number of rows
SELECT COUNT(*) AS total_students FROM students;
SELECT COUNT(*) FROM students WHERE class = 10;
-- SUM: total of marks
SELECT SUM(marks) AS total_marks FROM students;
-- AVG: average marks
SELECT AVG(marks) AS average FROM students;
SELECT AVG(marks) FROM students WHERE class = 10;
-- MIN and MAX
SELECT MIN(marks) AS lowest, MAX(marks) AS highest FROM students;
-- All in one query
SELECT
COUNT(*) AS total,
SUM(marks) AS sum_marks,
AVG(marks) AS avg_marks,
MIN(marks) AS min_marks,
MAX(marks) AS max_marks
FROM students;▶ Output
+-------+------------+-----------+-----------+-----------+ | total | sum_marks | avg_marks | min_marks | max_marks | +-------+------------+-----------+-----------+-----------+ | 5 | 433.25 | 86.65 | 76.50 | 92.00 | +-------+------------+-----------+-----------+-----------+
16. GROUP BY & HAVING
GROUP BY groups rows by a column so you can apply aggregate functions per group. HAVING filters groups (like WHERE but for groups).
SQL
-- Average marks per class SELECT class, AVG(marks) AS avg_marks FROM students GROUP BY class; -- Count students per class SELECT class, COUNT(*) AS num_students FROM students GROUP BY class; -- Classes where average marks > 80 (HAVING filters groups) SELECT class, AVG(marks) AS avg_marks FROM students GROUP BY class HAVING AVG(marks) > 80;
▶ Output (average per class)
+-------+-----------+ | class | avg_marks | +-------+-----------+ | 10 | 90.25 | | 11 | 80.88 | | 12 | 91.75 | +-------+-----------+
17. LIKE — Pattern Matching
LIKE searches for a pattern in a text column. Use
% (any number of chars) and _ (exactly one char).SQL
-- Names starting with 'A' SELECT * FROM students WHERE name LIKE 'A%'; -- Names ending with 'a' SELECT * FROM students WHERE name LIKE '%a'; -- Names containing 'Kumar' SELECT * FROM students WHERE name LIKE '%Kumar%'; -- Names with exactly 10 characters SELECT * FROM students WHERE name LIKE '__________'; -- Emails from gmail.com SELECT * FROM students WHERE email LIKE '%@gmail.com'; -- NOT LIKE: names NOT starting with 'A' SELECT * FROM students WHERE name NOT LIKE 'A%';
| Pattern | Meaning |
|---|---|
| LIKE 'A%' | Starts with A |
| LIKE '%a' | Ends with a |
| LIKE '%am%' | Contains 'am' anywhere |
| LIKE '_m%' | Second character is m |
| LIKE 'A__' | A followed by exactly 2 chars |
18. BETWEEN
BETWEEN x AND y selects values in a range (inclusive of both endpoints). Works with numbers, dates and text.
SQL
-- Marks between 75 and 90 (includes 75 and 90) SELECT * FROM students WHERE marks BETWEEN 75 AND 90; -- Born between two dates SELECT * FROM students WHERE dob BETWEEN '2008-01-01' AND '2009-12-31'; -- NOT BETWEEN: marks outside range SELECT * FROM students WHERE marks NOT BETWEEN 75 AND 90;
19. IN Operator
IN checks if a value matches any value in a list. It is shorter than writing multiple OR conditions.
SQL
-- Students in class 10 or 12
SELECT * FROM students WHERE class IN (10, 12);
-- Specific students by name
SELECT * FROM students WHERE name IN ('Aman Sharma', 'Priya Gupta');
-- NOT IN: exclude classes 10 and 11
SELECT * FROM students WHERE class NOT IN (10, 11);
-- IN with subquery (students who placed orders)
SELECT * FROM students WHERE roll_no IN (SELECT student_id FROM orders);20. JOINs
A JOIN combines rows from two or more tables using a related column (usually primary key + foreign key).
SQL
-- INNER JOIN: only matching rows in both tables SELECT students.name, orders.item FROM students INNER JOIN orders ON students.roll_no = orders.student_id; -- LEFT JOIN: all students + their orders (NULL if no order) SELECT students.name, orders.item FROM students LEFT JOIN orders ON students.roll_no = orders.student_id; -- RIGHT JOIN: all orders + matching students SELECT students.name, orders.item FROM students RIGHT JOIN orders ON students.roll_no = orders.student_id;
| JOIN Type | Returns |
|---|---|
| INNER JOIN | Only rows that match in BOTH tables |
| LEFT JOIN | All left table rows + matched right (NULL if no match) |
| RIGHT JOIN | All right table rows + matched left (NULL if no match) |
21. Quick Reference Table
| Command | Purpose | Quick Example |
|---|---|---|
| CREATE DATABASE | Make a new database | CREATE DATABASE mydb; |
| USE | Select a database | USE mydb; |
| CREATE TABLE | Make a new table | CREATE TABLE t (id INT PRIMARY KEY); |
| INSERT INTO | Add rows | INSERT INTO t VALUES (1); |
| SELECT | Show data | SELECT * FROM t; |
| WHERE | Filter rows | SELECT * FROM t WHERE id=1; |
| UPDATE | Change data | UPDATE t SET col=val WHERE id=1; |
| DELETE | Remove rows | DELETE FROM t WHERE id=1; |
| ALTER TABLE | Change structure | ALTER TABLE t ADD col INT; |
| DROP TABLE | Remove table | DROP TABLE t; |
| DISTINCT | No duplicates | SELECT DISTINCT class FROM t; |
| ORDER BY | Sort results | SELECT * FROM t ORDER BY col DESC; |
| LIMIT | Limit rows | SELECT * FROM t LIMIT 5; |
| COUNT/SUM/AVG | Aggregate | SELECT AVG(marks) FROM t; |
| GROUP BY | Group for aggregates | SELECT class, COUNT(*) FROM t GROUP BY class; |
| HAVING | Filter groups | HAVING AVG(marks) > 80 |
| LIKE | Pattern match | WHERE name LIKE 'A%' |
| BETWEEN | Range filter | WHERE marks BETWEEN 75 AND 90 |
| IN | Match list | WHERE class IN (10, 11) |
| INNER JOIN | Match both tables | t1 INNER JOIN t2 ON t1.id=t2.fk |
💡 Practice tip
Create the students table shown in this guide and run every command yourself. SQL is learned by doing, not by reading.
Frequently Asked Questions
What is the difference between DROP TABLE and DELETE FROM?
DELETE FROM removes rows from the table but keeps the table structure. DROP TABLE removes the entire table (structure + data) permanently.
What is the difference between WHERE and HAVING?
WHERE filters individual rows before grouping. HAVING filters groups after GROUP BY. You cannot use aggregate functions (COUNT, SUM, AVG) in WHERE — use HAVING instead.
What is the difference between TRUNCATE and DELETE?
TRUNCATE removes all rows quickly and cannot be rolled back. DELETE can use WHERE to remove specific rows and can be rolled back.
What does DISTINCT do in SQL?
DISTINCT removes duplicate values from the result. For example, SELECT DISTINCT class FROM students returns each class number only once.
How does LIKE work in SQL?
LIKE is used with WHERE for pattern matching. % means any number of characters, _ means exactly one character. Example: WHERE name LIKE 'A%' returns all names starting with A.
What is GROUP BY used for?
GROUP BY groups rows with the same value in a column so aggregate functions (COUNT, SUM, AVG, MIN, MAX) can be applied to each group separately. Use HAVING to filter the groups.
What is the difference between PRIMARY KEY and UNIQUE?
Both enforce uniqueness, but a table can have only ONE primary key (it also cannot be NULL). A table can have multiple UNIQUE constraints, and UNIQUE columns can have one NULL value.
How do you find the topper using SQL?
Use ORDER BY marks DESC LIMIT 1: SELECT name, marks FROM students ORDER BY marks DESC LIMIT 1; This sorts by marks highest-first and returns only the first row.
💻 Live Code Editor
This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.