Complete SQL Commands with Examples
Sample Table. Sample 'students' Table
Table: students
+---------+----------+-------+-------+
| roll_no | name | marks | grade |
+---------+----------+-------+-------+
| 1 | Vikas | 95 | A |
| 2 | Aryan | 88 | B |
| 3 | Sneha | 95 | A |
| 4 | Riya | 76 | C |
| 5 | Mohit | 65 | D |
| 6 | Anjali | NULL | NULL |
+---------+----------+-------+-------+
1. SELECT
Used to view data from a table.
Example:
SELECT * FROM students; -- shows all rows
2. WHERE
Filters records.
Example:
SELECT * FROM students WHERE marks > 90; -- shows Vikas and Sneha
3. LIKE
Matches a pattern.
Example:
SELECT * FROM students WHERE name LIKE 'A%'; -- shows Aryan, Anjali
4. IN
Checks if value is in a list.
Example:
SELECT * FROM students WHERE marks IN (76, 88);
5. BETWEEN
Checks if value is in range.
Example:
SELECT * FROM students WHERE marks BETWEEN 70 AND 90;
Complete SQL Commands with Examples
6. IS NULL
Checks if value is NULL.
Example:
SELECT * FROM students WHERE grade IS NULL; -- shows Anjali
7. ORDER BY
Sorts results.
Example:
SELECT * FROM students ORDER BY marks DESC;
8. DISTINCT
Removes duplicate values.
Example:
SELECT DISTINCT marks FROM students;
9. GROUP BY
Groups records with same values.
Example:
SELECT grade, COUNT(*) FROM students GROUP BY grade;
10. HAVING
Filters groups.
Example:
SELECT grade, COUNT(*) FROM students GROUP BY grade HAVING COUNT(*) > 1;
11. UPDATE
Modifies existing data.
Example:
UPDATE students SET marks = 90 WHERE name = 'Riya';
12. DELETE
Removes data.
Example:
DELETE FROM students WHERE marks < 70; -- removes Mohit
13. INSERT
Adds new data.
Example:
INSERT INTO students VALUES (7, 'Neha', 89, 'B');
Complete SQL Commands with Examples
14. ALTER TABLE ADD
Adds a new column.
Example:
ALTER TABLE students ADD city VARCHAR(20);
15. ALTER TABLE MODIFY
Changes column type.
Example:
ALTER TABLE students MODIFY marks FLOAT;
16. ALTER TABLE DROP
Removes a column.
Example:
ALTER TABLE students DROP COLUMN city;
17. DROP TABLE
Deletes entire table.
Example:
DROP TABLE students;
18. SUBQUERY
Nested query.
Example:
SELECT * FROM students WHERE marks = (SELECT MAX(marks) FROM students);