Posted on: January 19, 2025 Posted by: rahulgite Comments: 0

1. Introduction to SQL

SQL (Structured Query Language) is a standard language used to interact with relational database systems. It allows users to query, manipulate, and manage data efficiently.


2. SQL Commands

SQL commands are categorized into the following types:

2.1 Data Definition Language (DDL)

Used to define and manage database schema.

CommandDescriptionExample
CREATECreates a new database, table, or other database objects.CREATE TABLE students (id INT, name VARCHAR(50));
ALTERModifies the structure of an existing table.ALTER TABLE students ADD COLUMN age INT;
DROPDeletes a database or table.DROP TABLE students;
TRUNCATERemoves all records from a table but keeps its structure.TRUNCATE TABLE students;

2.2 Data Manipulation Language (DML)

Used to manage data within tables.

CommandDescriptionExample
SELECTRetrieves data from one or more tables.SELECT * FROM students;
INSERTAdds new records to a table.INSERT INTO students (id, name) VALUES (1, 'John');
UPDATEModifies existing records in a table.UPDATE students SET name = 'Jane' WHERE id = 1;
DELETERemoves records from a table.DELETE FROM students WHERE id = 1;

2.3 Data Control Language (DCL)

Used to control access to data.

CommandDescriptionExample
GRANTProvides privileges to users.GRANT SELECT, INSERT ON students TO user1;
REVOKERemoves privileges from users.REVOKE INSERT ON students FROM user1;

2.4 Transaction Control Language (TCL)

Manages database transactions.

CommandDescriptionExample
COMMITSaves all changes made during a transaction.COMMIT;
ROLLBACKReverts changes made during a transaction.ROLLBACK;
SAVEPOINTSets a point within a transaction to roll back to.SAVEPOINT sp1;
SET TRANSACTIONConfigures properties of a transaction.SET TRANSACTION READ ONLY;

3. SQL Clauses

Clauses specify conditions for queries and data manipulation.

ClauseDescriptionExample
WHEREFilters records based on a condition.SELECT * FROM students WHERE age > 18;
GROUP BYGroups rows sharing a property for aggregate functions.SELECT age, COUNT(*) FROM students GROUP BY age;
HAVINGFilters aggregated data.SELECT age, COUNT(*) FROM students GROUP BY age HAVING COUNT(*) > 2;
ORDER BYSorts data in ascending or descending order.SELECT * FROM students ORDER BY name ASC;
LIMITRestricts the number of rows returned.SELECT * FROM students LIMIT 5;

4. SQL Conditions

Used to define rules for filtering and data manipulation.

ConditionDescriptionExample
ANDCombines multiple conditions (all must be true).SELECT * FROM students WHERE age > 18 AND name = 'John';
ORCombines multiple conditions (any can be true).SELECT * FROM students WHERE age > 18 OR name = 'John';
NOTReverses the result of a condition.SELECT * FROM students WHERE NOT age > 18;
BETWEENSpecifies a range of values.SELECT * FROM students WHERE age BETWEEN 18 AND 25;
INMatches values in a list.SELECT * FROM students WHERE name IN ('John', 'Jane');
LIKESearches for patterns in text.SELECT * FROM students WHERE name LIKE 'J%';
IS NULLChecks for null values.SELECT * FROM students WHERE age IS NULL;

5. SQL Functions

5.1 Aggregate Functions

Perform calculations on multiple rows.

FunctionDescriptionExample
COUNT()Returns the number of rows.SELECT COUNT(*) FROM students;
SUM()Returns the sum of numeric values.SELECT SUM(age) FROM students;
AVG()Returns the average value.SELECT AVG(age) FROM students;
MAX()Returns the maximum value.SELECT MAX(age) FROM students;
MIN()Returns the minimum value.SELECT MIN(age) FROM students;

5.2 Scalar Functions

Perform operations on a single value.

FunctionDescriptionExample
UCASE()Converts text to uppercase.SELECT UCASE(name) FROM students;
LCASE()Converts text to lowercase.SELECT LCASE(name) FROM students;
LEN()Returns the length of a string.SELECT LEN(name) FROM students;
ROUND()Rounds numeric values.SELECT ROUND(age, 0) FROM students;
NOW()Returns the current date and time.SELECT NOW();

6. SQL Case Statements

Allows conditional logic in queries.

StatementDescriptionExample
CASEExecutes conditional expressions.SELECT name, CASE WHEN age >= 18 THEN 'Adult' ELSE 'Minor' END AS category FROM students;

7. SQL Joins

Combines rows from two or more tables.

Join TypeDescriptionExample
INNER JOINReturns rows with matching values in both tables.SELECT * FROM students INNER JOIN courses ON students.course_id = courses.id;
LEFT JOINReturns all rows from the left table and matching rows from the right table.SELECT * FROM students LEFT JOIN courses ON students.course_id = courses.id;
RIGHT JOINReturns all rows from the right table and matching rows from the left table.SELECT * FROM students RIGHT JOIN courses ON students.course_id = courses.id;
FULL JOINReturns rows when there is a match in either table.SELECT * FROM students FULL JOIN courses ON students.course_id = courses.id;
CROSS JOINReturns the Cartesian product of two tables.SELECT * FROM students CROSS JOIN courses;

8. Advanced SQL Features

8.1 Subqueries

Queries nested within other queries.

FeatureDescriptionExample
SubqueryA query within a query.SELECT name FROM students WHERE age = (SELECT MAX(age) FROM students);

8.2 Views

Virtual tables based on SQL queries.

CommandDescriptionExample
CREATE VIEWCreates a view.CREATE VIEW adult_students AS SELECT * FROM students WHERE age >= 18;
DROP VIEWDeletes a view.DROP VIEW adult_students;

8.3 Indexes

Improve query performance.

CommandDescriptionExample
CREATE INDEXCreates an index.CREATE INDEX idx_name ON students(name);
DROP INDEXDeletes an index.DROP INDEX idx_name;

9. SQL Constraints

Define rules for data integrity.

ConstraintDescriptionExample
NOT NULLEnsures a column cannot have null values.CREATE TABLE students (id INT NOT NULL);
UNIQUEEnsures all values in a column are unique.CREATE TABLE students (email VARCHAR(100) UNIQUE);
PRIMARY KEYCombines NOT NULL and UNIQUE.CREATE TABLE students (id INT PRIMARY KEY);
FOREIGN KEYLinks two tables.ALTER TABLE students ADD CONSTRAINT fk_course FOREIGN KEY (course_id) REFERENCES courses(id);
CHECKEnsures values satisfy a condition.CREATE TABLE students (age INT CHECK (age >= 18));
DEFAULTSets a default value.CREATE TABLE students (enrolled BOOLEAN DEFAULT TRUE);

10. SQL Practical Example

Task: Retrieve the names of students enrolled in the “Math” course.

SELECT s.name
FROM students s
INNER JOIN courses c ON s.course_id = c.id
WHERE c.name = 'Math';

Leave a Comment