SQL_Comprehensive_Guide
SQL_Comprehensive_Guide
================================================
This guide combines simple explanations with detailed technical notes on SQL
concepts from the CBSE Class XII Informatics Practices curriculum. It's designed to
help you progress from beginner to advanced understanding of each SQL topic.
TABLE OF CONTENTS
=================
1. [Introduction to SQL](#introduction-to-sql)
2. [SQL Data Types](#sql-data-types)
3. [SQL Commands](#sql-commands)
- [Creating and Changing Tables (DDL)](#creating-and-changing-tables-ddl)
- [Adding and Changing Data (DML)](#adding-and-changing-data-dml)
- [Finding Information (DQL)](#finding-information-dql)
- [Other Command Types (DCL, TCL)](#other-command-types-dcl-tcl)
4. [SQL Functions](#sql-functions)
- [Mathematical Functions](#mathematical-functions)
- [String Functions](#string-functions)
- [Date Functions](#date-functions)
- [Aggregate Functions](#aggregate-functions)
5. [SQL Joins](#sql-joins)
6. [SQL Subqueries](#sql-subqueries)
7. [SQL Views](#sql-views)
8. [SQL Constraints](#sql-constraints)
9. [Practice Examples](#practice-examples)
10. [Tips for Learning SQL](#tips-for-learning-sql)
INTRODUCTION TO SQL
===================
SIMPLE EXPLANATION
==================
SQL is like a special language that helps you talk to databases (where information
is stored). Think of a database as a collection of spreadsheets (called tables)
that can be connected to each other.
SQL lets you ask questions about your data and make changes to it. For example,
"Show me all students who got more than 80 marks" or "Add a new student to the
class."
TECHNICAL DETAILS
=================
SQL (Structured Query Language) is a standard language for storing, manipulating,
and retrieving data in relational database management systems (RDBMS).
SIMPLE EXPLANATION
==================
Data types tell the database what kind of information you're storing, just like you
would specify if you're writing a number or text in a form.
NUMBERS
=======
- **INT**: Whole numbers only (like 1, 42, -10)
- **DECIMAL**: Numbers with decimal points (like 10.5, 3.14)
- **FLOAT**: Similar to decimal but for scientific calculations
TEXT
====
- **CHAR**: Fixed-length text (always uses the same amount of storage)
- **VARCHAR**: Variable-length text (only uses what it needs)
- **TEXT**: For longer pieces of writing
TECHNICAL DETAILS
=================
SQL COMMANDS
============
- **TRUNCATE**: Removes all records from a table but keeps the table structure
```sql
TRUNCATE TABLE Students;
```
SIMPLE EXPLANATION
==================
**INSERT**: Adds new information
```sql
-- This adds a new student to the table
INSERT INTO Students (StudentID, Name, Age, Class)
VALUES (1, 'Rahul Sharma', 16, 'XII-A');
```
SIMPLE EXPLANATION
==================
**SELECT**: Gets information from the database
```sql
-- This shows all students
SELECT * FROM Students;
TECHNICAL DETAILS
=================
SQL FUNCTIONS
=============
SIMPLE EXPLANATION
==================
Functions are like built-in tools that help you work with your data.
MATHEMATICAL FUNCTIONS
======================
SIMPLE EXPLANATION
==================
**ROUND()**: Rounds a number
```sql
-- This rounds 123.456 to 123.46
SELECT ROUND(123.456, 2);
```
TECHNICAL DETAILS
=================
ROUND()
=======
Rounds a number to a specified number of decimal places.
```sql
SELECT ROUND(123.456, 2); -- Returns 123.46
SELECT ROUND(123.456, 0); -- Returns 123
```
CEIL() / CEILING()
==================
Returns the smallest integer greater than or equal to the given number.
```sql
SELECT CEIL(123.45); -- Returns 124
SELECT CEILING(123.45); -- Returns 124
```
FLOOR()
=======
Returns the largest integer less than or equal to the given number.
```sql
SELECT FLOOR(123.45); -- Returns 123
```
ABS()
=====
Returns the absolute (positive) value of a number.
```sql
SELECT ABS(-123.45); -- Returns 123.45
```
STRING FUNCTIONS
================
SIMPLE EXPLANATION
==================
**CONCAT()**: Joins text together
```sql
-- This creates 'Hello World'
SELECT CONCAT('Hello', ' ', 'World');
```
TECHNICAL DETAILS
=================
CONCAT()
========
Combines two or more strings into one.
```sql
SELECT CONCAT('Hello', ' ', 'World'); -- Returns 'Hello World'
```
LENGTH() / CHAR_LENGTH()
========================
Returns the length of a string in characters.
```sql
SELECT LENGTH('Hello'); -- Returns 5
SELECT CHAR_LENGTH('Hello'); -- Returns 5
```
UPPER() / UCASE()
=================
Converts a string to uppercase.
```sql
SELECT UPPER('Hello'); -- Returns 'HELLO'
SELECT UCASE('Hello'); -- Returns 'HELLO'
```
LOWER() / LCASE()
=================
Converts a string to lowercase.
```sql
SELECT LOWER('Hello'); -- Returns 'hello'
SELECT LCASE('Hello'); -- Returns 'hello'
```
SUBSTRING() / SUBSTR()
======================
Extracts a substring from a string.
```sql
SELECT SUBSTRING('Hello World', 1, 5); -- Returns 'Hello'
SELECT SUBSTR('Hello World', 7, 5); -- Returns 'World'
```
DATE FUNCTIONS
==============
SIMPLE EXPLANATION
==================
**NOW()**: Gets current date and time
```sql
-- This returns the current datetime
SELECT NOW();
```
TECHNICAL DETAILS
=================
NOW()
=====
Returns the current date and time.
```sql
SELECT NOW(); -- Returns something like '2023-08-15 14:30:00'
```
CURDATE() / CURRENT_DATE()
==========================
Returns the current date.
```sql
SELECT CURDATE(); -- Returns something like '2023-08-15'
SELECT CURRENT_DATE(); -- Returns something like '2023-08-15'
```
DATE_ADD()
==========
Adds a time/date interval to a date and returns the result.
```sql
SELECT DATE_ADD('2023-08-15', INTERVAL 10 DAY); -- Returns '2023-08-25'
SELECT DATE_ADD('2023-08-15', INTERVAL 1 MONTH); -- Returns '2023-09-15'
```
AGGREGATE FUNCTIONS
===================
SIMPLE EXPLANATION
==================
**COUNT()**: Counts rows
```sql
-- This counts how many students you have
SELECT COUNT(*) FROM Students;
```
TECHNICAL DETAILS
=================
COUNT()
=======
Returns the number of rows that match a specified criterion.
```sql
SELECT COUNT(*) FROM Students; -- Counts all rows
SELECT COUNT(Email) FROM Students; -- Counts non-NULL Email values
```
SUM()
=====
Returns the sum of a numeric column.
```sql
SELECT SUM(Age) FROM Students; -- Adds up all ages
```
AVG()
=====
Returns the average value of a numeric column.
```sql
SELECT AVG(Age) FROM Students; -- Calculates average age
```
```sql
SELECT MIN(Age) FROM Students; -- Finds youngest student's age
SELECT MAX(Age) FROM Students; -- Finds oldest student's age
```
SQL JOINS
=========
SIMPLE EXPLANATION
==================
Joins connect information from different tables. Think of them like putting two
spreadsheets side by side and matching up related rows.
**LEFT JOIN**: Shows everything from the first table, even if there's no match in
the second table
```sql
-- This shows all students, even those without marks
SELECT Students.Name, Marks.Subject, Marks.Score
FROM Students
LEFT JOIN Marks ON Students.StudentID = Marks.StudentID;
```
**RIGHT JOIN**: Shows everything from the second table, even if there's no match in
the first table
```sql
-- This shows all marks, even for students not in the Students table
SELECT Students.Name, Marks.Subject, Marks.Score
FROM Students
RIGHT JOIN Marks ON Students.StudentID = Marks.StudentID;
```
TECHNICAL DETAILS
=================
INNER JOIN
==========
Returns records that have matching values in both tables.
```sql
SELECT Students.Name, Marks.Subject, Marks.Score
FROM Students
INNER JOIN Marks ON Students.StudentID = Marks.StudentID;
```
```sql
SELECT Students.Name, Marks.Subject, Marks.Score
FROM Students
LEFT JOIN Marks ON Students.StudentID = Marks.StudentID;
```
```sql
SELECT Students.Name, Marks.Subject, Marks.Score
FROM Students
RIGHT JOIN Marks ON Students.StudentID = Marks.StudentID;
```
```sql
SELECT Students.Name, Marks.Subject, Marks.Score
FROM Students
FULL JOIN Marks ON Students.StudentID = Marks.StudentID;
```
SQL SUBQUERIES
==============
SIMPLE EXPLANATION
==================
A subquery is a query inside another query - like asking a question within a
question.
```sql
-- This finds students older than the average age
SELECT Name, Age
FROM Students
WHERE Age > (SELECT AVG(Age) FROM Students);
```
TECHNICAL DETAILS
=================
A subquery is a query nested inside another query. It can be used in various parts
of a SQL statement:
SQL VIEWS
=========
SIMPLE EXPLANATION
==================
A view is like a saved query that you can use again and again. It doesn't store
data itself but shows data from other tables.
```sql
-- This creates a view showing students and their marks
CREATE VIEW StudentMarks AS
SELECT Students.Name, Marks.Subject, Marks.Score
FROM Students
INNER JOIN Marks ON Students.StudentID = Marks.StudentID;
TECHNICAL DETAILS
=================
A view is a virtual table based on the result-set of a SQL statement. It contains
rows and columns, just like a real table, but doesn't store the data physically.
CREATING A VIEW
===============
```sql
CREATE VIEW StudentMarks AS
SELECT Students.Name, Marks.Subject, Marks.Score
FROM Students
INNER JOIN Marks ON Students.StudentID = Marks.StudentID;
```
USING A VIEW
============
```sql
SELECT * FROM StudentMarks;
FROM StudentMarks
GROUP BY Name;
```
UPDATING A VIEW
===============
```sql
CREATE OR REPLACE VIEW StudentMarks AS
SELECT Students.Name, Students.Class, Marks.Subject, Marks.Score
FROM Students
INNER JOIN Marks ON Students.StudentID = Marks.StudentID;
```
DROPPING A VIEW
===============
```sql
DROP VIEW StudentMarks;
```
SQL CONSTRAINTS
===============
SIMPLE EXPLANATION
==================
Constraints are rules that control what data can be added to a table.
PRIMARY KEY
===========
Makes sure each row has a unique identifier
```sql
-- StudentID must be unique for each student
CREATE TABLE Students (
StudentID INT PRIMARY KEY,
Name VARCHAR(50)
);
```
FOREIGN KEY
===========
Connects tables together
```sql
-- This ensures marks are only added for existing students
CREATE TABLE Marks (
MarkID INT PRIMARY KEY,
StudentID INT,
Subject VARCHAR(50),
Score INT,
FOREIGN KEY (StudentID) REFERENCES Students(StudentID)
);
```
UNIQUE
======
Makes sure values aren't repeated
```sql
-- No two students can have the same email
CREATE TABLE Students (
StudentID INT PRIMARY KEY,
Email VARCHAR(100) UNIQUE,
Name VARCHAR(50)
);
```
NOT NULL
========
Makes sure a value is always provided
```sql
-- Every student must have a name
CREATE TABLE Students (
StudentID INT PRIMARY KEY,
Name VARCHAR(50) NOT NULL,
Age INT
);
```
CHECK
=====
Makes sure values meet certain conditions
```sql
-- Students must be at least 15 years old
CREATE TABLE Students (
StudentID INT PRIMARY KEY,
Name VARCHAR(50),
Age INT CHECK (Age >= 15)
);
```
DEFAULT
=======
Sets a starting value if none is provided
```sql
-- If no class is specified, put the student in XII-A
CREATE TABLE Students (
StudentID INT PRIMARY KEY,
Name VARCHAR(50),
Age INT,
Class VARCHAR(10) DEFAULT 'XII-A'
);
```
TECHNICAL DETAILS
=================
Constraints are rules enforced on data columns in tables to ensure data integrity.
PRIMARY KEY
===========
Uniquely identifies each record in a table. Cannot contain NULL values and must be
unique.
```sql
CREATE TABLE Students (
StudentID INT PRIMARY KEY,
Name VARCHAR(50)
);
```
FOREIGN KEY
===========
Links data between tables and ensures referential integrity.
```sql
CREATE TABLE Marks (
MarkID INT PRIMARY KEY,
StudentID INT,
Subject VARCHAR(50),
Score INT,
FOREIGN KEY (StudentID) REFERENCES Students(StudentID)
);
```
UNIQUE
======
Ensures all values in a column are different.
```sql
CREATE TABLE Students (
StudentID INT PRIMARY KEY,
Email VARCHAR(100) UNIQUE,
Name VARCHAR(50)
);
```
NOT NULL
========
Ensures a column cannot have a NULL value.
```sql
CREATE TABLE Students (
StudentID INT PRIMARY KEY,
Name VARCHAR(50) NOT NULL,
Age INT
);
```
CHECK
=====
Ensures all values in a column satisfy a specific condition.
```sql
CREATE TABLE Students (
StudentID INT PRIMARY KEY,
Name VARCHAR(50),
Age INT CHECK (Age >= 15)
);
```
DEFAULT
=======
Sets a default value for a column when no value is specified.
```sql
CREATE TABLE Students (
StudentID INT PRIMARY KEY,
Name VARCHAR(50),
Age INT,
Class VARCHAR(10) DEFAULT 'XII-A'
);
```
PRACTICE EXAMPLES
=================
3. **Find students who have scored above average in all subjects they've taken**
```sql
SELECT s.Name
FROM Students s
WHERE NOT EXISTS (
SELECT 1
FROM Marks m
WHERE m.StudentID = s.StudentID
AND m.Score <= (SELECT AVG(Score) FROM Marks WHERE Subject = m.Subject)
);
```
Remember, SQL is like learning any language - it gets easier with practice!