SQL Notes
What is SQL?
SQL (Structured Query Language) is used to store, retrieve, manage, and manipulate data in relational
databases.
Basic SQL Commands
SELECT - Retrieve data
INSERT - Add new data
UPDATE - Modify data
DELETE - Remove data
CREATE - Create table/database
DROP - Delete table/database
WHERE - Conditions
ORDER BY - Sorting
Create Table
CREATE TABLE Students (
ID INT PRIMARY KEY,
Name VARCHAR(100),
Age INT,
Grade CHAR(1)
);
Insert Data
INSERT INTO Students (ID, Name, Age, Grade)
VALUES (1, 'Alice', 20, 'A');
Select Data
SELECT * FROM Students;
SELECT Name, Age FROM Students WHERE Age > 18;
SQL Notes
Update Data
UPDATE Students SET Grade = 'B' WHERE ID = 1;
Delete Data
DELETE FROM Students WHERE Name = 'Alice';
Aggregate Functions
SELECT COUNT(*) FROM Students;
SELECT AVG(Age) FROM Students;
SELECT MAX(Age), MIN(Age) FROM Students;
Group By and Having
SELECT Grade, COUNT(*) FROM Students GROUP BY Grade HAVING COUNT(*) > 1;
Joins
SELECT Students.Name, Courses.CourseName
FROM Students
INNER JOIN Courses ON Students.ID = Courses.StudentID;
Subqueries
SELECT Name FROM Students WHERE Age > (SELECT AVG(Age) FROM Students);
Aliases
SELECT Name AS StudentName, Age AS StudentAge FROM Students;
Tips
- Use LIMIT to restrict rows
- Use DISTINCT to remove duplicates
- Use WHERE, AND, OR, NOT for filtering