- 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 Syntax
SQL (Structured Query Language) is the standard language for communicating with relational database management systems like MySQL, PostgreSQL, and SQL Server. Think of it as the bridge between your application code and your data storage. Whether you are building a simple blog or a complex e-commerce platform, mastering SQL syntax is essential for managing information efficiently.
Basic SQL Commands
Every SQL statement starts with a keyword and ends with a semicolon (;). While SQL is generally case-insensitive, it is a common professional standard to write keywords in uppercase to distinguish them from table and column names.
SELECT - This is your primary tool for retrieving data. You can specify exact columns or use an asterisk (*) to grab everything from a table.
-- Example: Fetching specific user details
SELECT first_name, email FROM users WHERE status = 'active';
INSERT INTO - Used to add new records. You specify the target table, the columns you want to fill, and the actual values.
-- Example: Registering a new product
INSERT INTO products (product_name, price) VALUES ('Mechanical Keyboard', 89.99);
UPDATE - This modifies existing data. It is extremely powerful and must be used with caution.
-- Example: Changing a user's subscription tier
UPDATE users SET membership_level = 'Premium' WHERE user_id = 101;
DELETE - Removes rows from a table based on a condition.
-- Example: Removing an expired session
DELETE FROM sessions WHERE expiry_date < '2023-01-01';
CREATE TABLE - This command defines the blueprint of your data. You must specify the column names and the type of data they will hold (integers, strings, dates, etc.).
-- Example: Creating a basic profiles table
CREATE TABLE profiles (
id INT PRIMARY KEY,
username VARCHAR(50),
bio TEXT
);
ALTER TABLE - Use this when your requirements change and you need to add, delete, or modify columns in an existing table structure.
-- Example: Adding a phone number column to users
ALTER TABLE users ADD phone_number VARCHAR(15);
DROP TABLE - This is the "nuclear option." It deletes the entire table and all the data stored within it permanently.
DROP TABLE temporary_logs;
Clauses
Clauses are the modifiers of SQL. They help you filter, sort, and organize your results to get exactly what you need.
WHERE: This is your primary filter. You can use operators like =, !=, <, >, and LIKE (for pattern matching).
SELECT * FROM orders WHERE total_price > 100.00;
ORDER BY: Controls the presentation of your data. You can sort by one or multiple columns in ascending (ASC) or descending (DESC) order.
-- Sorting newest products first
SELECT * FROM products ORDER BY created_at DESC;
GROUP BY: This is used to arrange identical data into groups. It is almost always used with "aggregate functions" like COUNT or SUM to generate reports.
-- Counting how many customers are in each city
SELECT city, COUNT(customer_id) FROM customers GROUP BY city;
JOIN: Relational databases are built on links between tables. JOIN allows you to pull related data from different tables into a single result set.
-- Linking orders to the customers who placed them
SELECT orders.id, customers.name
FROM orders
JOIN customers ON orders.customer_id = customers.id;
Functions
SQL provides built-in functions to perform calculations on your data on the fly, which is often much faster than doing the math in your application code.
COUNT(): Returns the number of rows that match a specific criteria.
SELECT COUNT(id) FROM users WHERE active = 1;
SUM(): Adds up all values in a numeric column. Great for financial reporting.
SELECT SUM(revenue) FROM daily_sales;
AVG(): Calculates the mathematical average of a column.
SELECT AVG(rating) FROM product_reviews WHERE product_id = 45;
Constraints
Constraints are the rules you apply to your data to ensure its "integrity"—meaning the data stays accurate, reliable, and consistent.
- PRIMARY KEY: A unique identifier for every row. No two rows can have the same Primary Key, and it cannot be empty (NULL).
- FOREIGN KEY: A column that points to a Primary Key in another table, creating a link between the two.
- NOT NULL: A rule that prevents a column from being left empty. Use this for essential data like usernames or email addresses.
- UNIQUE: Ensures that all values in a column are different from one another (for example, ensuring no two users register with the same email).
Summary
SQL syntax is the foundation of modern data management. By combining basic commands like SELECT and INSERT with powerful JOIN clauses and Constraints, you can build robust systems that handle data safely and efficiently. Start with the basics, and as your queries get more complex, focus on readability and data integrity to become a proficient SQL developer.