- SQL Basics
- SQL Introduction
- SQL Syntax
- SQL Sample Database
- SQL SELECT
- SQL WHERE
- SQL ORDER BY
- SQL DISTINCT
- SQL LIMIT
- SQL FETCH
- SQL AND
- SQL OR
- SQL BETWEEN
- SQL IN
- SQL LIKE
- SQL IS NULL
- SQL Comparison Operators
- SQL Logical Operators
- SQL Alias
- SQL CASE
- Joins and Subqueries
- SQL INNER JOIN
- SQL LEFT JOIN
- SQL RIGHT JOIN
- SQL FULL OUTER JOIN
- SQL SELF JOIN
- SQL CROSS JOIN
- SQL Subquery
- SQL Correlated Subquery
- SQL UNION
- SQL INTERSECT
- SQL EXCEPT
- Aggregate Functions
- SQL AVG
- SQL COUNT
- SQL MAX
- SQL MIN
- SQL SUM
- SQL GROUP BY
- SQL HAVING
- SQL ROLLUP
- SQL CUBE
- SQL GROUPING SETS
- Database Management
- SQL CREATE DATABASE
- SQL ALTER DATABASE
- SQL DROP DATABASE
- SQL BACKUP DATABASE
- SQL SHOW DATABASES
- SQL SELECT DATABASE
- Table Management
- SQL CREATE TABLE
- SQL ALTER TABLE
- SQL ADD COLUMN
- SQL DROP COLUMN
- SQL DROP TABLE
- SQL TRUNCATE TABLE
- SQL SHOW TABLES
- SQL RENAME TABLE
- SQL Constraints
- SQL Primary Key
- SQL Foreign Key
- SQL UNIQUE Constraint
- SQL CHECK Constraint
- SQL NOT NULL Constraint
SQL Introduction
SQL (Structured Query Language) is the industry-standard language designed specifically for communicating with relational databases. Think of it as the bridge between your application's logic and the raw data it needs to function. Whether you are building a mobile app, a financial dashboard, or a simple blog, SQL allows you to store, retrieve, and organize data in a way that is both efficient and reliable.
Key Features of SQL
Database Interaction
- SQL is the primary tool for interacting with Relational Database Management Systems (RDBMS). Famous examples include MySQL, PostgreSQL, Microsoft SQL Server, and SQLite.
- Benefit: It provides a declarative way to handle data. Instead of writing complex loops to find a specific record, you simply tell the database *what* you want, and the engine decides the most efficient way to get it.
Data Querying
- At its heart, SQL is about asking questions. Using the
SELECTstatement, you can pull specific rows and columns from millions of records in milliseconds. - Benefit: You can filter, sort, and aggregate data to generate reports, calculate averages, or power search bars in your applications.
SELECT Name, Email) instead of using SELECT *. This reduces the load on the database and improves application performance.
Data Manipulation
- SQL includes a set of commands (DML) like
INSERT,UPDATE, andDELETEto manage the lifecycle of your data. - Benefit: These commands allow your application to handle user registrations, profile updates, and account deletions in real-time.
Database Structure Management
- Beyond just data, SQL manages the "schema" or the blueprint of the database using
CREATE,ALTER, andDROP. - Benefit: This allows developers to version-control their database structure, making it easy to mirror the production environment on a local machine.
Data Integrity and Constraints
- SQL enforces rules to keep data clean. Constraints like
PRIMARY KEY(unique identifiers) andFOREIGN KEY(relationships between tables) prevent "garbage data" from entering your system. - Benefit: It ensures that an order cannot exist without a customer, or that two users cannot have the same unique username.
Basic SQL Commands
SELECT: The most common command, used to fetch data.
-- Fetch all columns from the Customers table
SELECT * FROM Customers;
INSERT INTO: Used to add a new row of data.
-- Adding a new user to the system
INSERT INTO Customers (Name, Age) VALUES ('John Doe', 30);
UPDATE: Modifies data that is already in the table.
-- Updating John's age on his birthday
UPDATE Customers SET Age = 31 WHERE Name = 'John Doe';
WHERE clause in an UPDATE or DELETE statement. Without it, the command will apply to every single row in the table!
DELETE: Removes records from a table.
-- Removing a specific user record
DELETE FROM Customers WHERE Name = 'John Doe';
CREATE TABLE: Defines a new table and its data types.
-- Defining the structure for a customer list
CREATE TABLE Customers (
ID INT PRIMARY KEY,
Name VARCHAR(50),
Age INT
);
Types of SQL Queries
Data Retrieval
SELECT: This is used for "Read" operations. You can filter results using theWHEREclause to find specific users or items.- Example:
-- Finding users who are older than 25
SELECT Name, Age FROM Customers WHERE Age > 25;
Data Insertion
INSERT INTO: This handles "Create" operations. In the real world, this is what happens when a user clicks "Submit" on a sign-up form.- Example:
INSERT INTO Customers (Name, Age) VALUES ('Jane Smith', 28);
Data Update
UPDATE: This handles "Update" operations. It is crucial for maintaining accurate, up-to-date information.- Example:
UPDATE Customers SET Age = 29 WHERE Name = 'Jane Smith';
Data Deletion
DELETE: This handles "Delete" operations. Use this when a user cancels an account or a record becomes obsolete.- Example:
DELETE FROM Customers WHERE Name = 'Jane Smith';
SQL Clauses and Operators
WHERE: This is your primary filter. It allows you to target specific data based on conditions.
- Example:
SELECT * FROM Customers WHERE Age > 30;
ORDER BY: Results from a database aren't guaranteed to be in a specific order unless you ask for it. ASC (default) is ascending, DESC is descending.
- Example:
-- Sorting customers from oldest to youngest
SELECT * FROM Customers ORDER BY Age DESC;
AND/OR: Use these to build more complex logic. AND requires both conditions to be true; OR requires only one.
- Example:
SELECT * FROM Customers WHERE Age > 25 AND Name = 'John Doe';
LIKE: Used for pattern matching. The % symbol is a wildcard that represents zero or more characters.
- Example:
-- Finding all names that start with the letter 'J'
SELECT * FROM Customers WHERE Name LIKE 'J%';
LIKE '%text%' to find a word anywhere in a string, but be careful this can be slow on very large tables because it prevents the database from using certain types of indexes.
SQL Functions
COUNT(): Useful for statistics, such as finding out how many users have signed up.
SELECT COUNT(*) FROM Customers;
AVG(): Calculates the mean value. Great for financial or demographic reporting.
SELECT AVG(Age) FROM Customers;
MAX(): Finds the highest value in a column, like the most expensive product in a store.
SELECT MAX(Age) FROM Customers;
MIN(): Finds the lowest value, such as the earliest join date.
SELECT MIN(Age) FROM Customers;
SUM(): Adds up numeric values, commonly used for calculating total revenue.
SELECT SUM(Age) FROM Customers;
Database Relationships
- One-to-Many Relationship: The most common type. For example, one
Customercan have manyOrders. The "Many" side (Orders) usually holds aCustomer_IDto link back to the parent. - Many-to-Many Relationship: For example, a
Studentcan enroll in manyCourses, and aCoursecan have manyStudents. This requires a third "Join Table" (likeEnrollments) to map the IDs together.
user_id instead of just id_val) to make your database schema self-documenting for other developers.
Summary
SQL is much more than just a way to store data; it is the universal language for data management in the software world. By mastering basic commands like SELECT, INSERT, and UPDATE, and understanding how to structure relationships between tables, you gain the ability to build scalable, professional-grade applications. As you continue your journey, you'll find that SQL’s logical structure and powerful filtering capabilities make it one of the most valuable tools in any developer's toolkit.