Free tutorials & notes in Hindi & English · Clean code examples · Mobile friendly learning
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 TypeUse forExample
INTWhole numbersage INT
DECIMAL(p,s)Exact decimals (money, marks)marks DECIMAL(5,2)
VARCHAR(n)Text up to n charsname VARCHAR(80)
TEXTLong textdescription TEXT
DATEDate (YYYY-MM-DD)dob DATE
DATETIMEDate + Timecreated_at DATETIME
BOOLEAN / TINYINT(1)True/Falseis_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;
CommandDeletesRollback?Speed
DELETESelected rowsYesSlow
TRUNCATEAll rowsNoFast
DROPEntire tableNoInstant

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
);
ConstraintPurposeNULL allowed?
PRIMARY KEYUnique row identifierNo
FOREIGN KEYLinks to another table's PKYes (unless NOT NULL)
NOT NULLColumn must have a valueNo
UNIQUENo duplicate valuesYes (once)
CHECKValue must satisfy conditionYes
DEFAULTAutomatic value if none givenYes

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%';
PatternMeaning
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 TypeReturns
INNER JOINOnly rows that match in BOTH tables
LEFT JOINAll left table rows + matched right (NULL if no match)
RIGHT JOINAll right table rows + matched left (NULL if no match)

21. Quick Reference Table

CommandPurposeQuick Example
CREATE DATABASEMake a new databaseCREATE DATABASE mydb;
USESelect a databaseUSE mydb;
CREATE TABLEMake a new tableCREATE TABLE t (id INT PRIMARY KEY);
INSERT INTOAdd rowsINSERT INTO t VALUES (1);
SELECTShow dataSELECT * FROM t;
WHEREFilter rowsSELECT * FROM t WHERE id=1;
UPDATEChange dataUPDATE t SET col=val WHERE id=1;
DELETERemove rowsDELETE FROM t WHERE id=1;
ALTER TABLEChange structureALTER TABLE t ADD col INT;
DROP TABLERemove tableDROP TABLE t;
DISTINCTNo duplicatesSELECT DISTINCT class FROM t;
ORDER BYSort resultsSELECT * FROM t ORDER BY col DESC;
LIMITLimit rowsSELECT * FROM t LIMIT 5;
COUNT/SUM/AVGAggregateSELECT AVG(marks) FROM t;
GROUP BYGroup for aggregatesSELECT class, COUNT(*) FROM t GROUP BY class;
HAVINGFilter groupsHAVING AVG(marks) > 80
LIKEPattern matchWHERE name LIKE 'A%'
BETWEENRange filterWHERE marks BETWEEN 75 AND 90
INMatch listWHERE class IN (10, 11)
INNER JOINMatch both tablest1 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.
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 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.