Master the fundamentals of SQL and databases with clear explanations and practical queries.
0 / 11 topics completed
01
Introduction to SQL
SQL (Structured Query Language) is the standard language used to communicate with Relational Database Management Systems (RDBMS). It is used to store, manipulate, and retrieve data in databases.
What Can SQL Do?
Execute queries against a database
Retrieve data from a database
Insert, update, and delete records in a database
Create new databases, tables, and views
Set permissions on tables, procedures, and views
Here is a basic SQL query to get you started:
SQL
SELECT * FROM users;
💡
SQL keywords are NOT case sensitive: select is the same as SELECT. However, it is a common convention to write SQL keywords in UPPERCASE for readability.
Practice: Introduction to SQL
Write a query that selects all columns from a table named employees.
SQL
SELECT * FROM employees;
02
Database Fundamentals
A Relational Database stores data in tables. A table is a collection of related data entries and it consists of columns and rows.
Key Terms
Table: A structured format of rows and columns (e.g., users table).
Row (Record): A single data entry in a table.
Column (Field): A specific attribute of the data (e.g., email, age).
Primary Key: A unique identifier for each record in a table.
Foreign Key: A field in one table that uniquely identifies a row of another table.
📚
SQL databases are known as RDBMS (Relational Database Management Systems). Examples include MySQL, PostgreSQL, Oracle, and Microsoft SQL Server.
Practice: Database Fundamentals
Identify which of the following is typically a Primary Key in a `users` table: first_name, user_id, age.
user_id is the best candidate for a Primary Key because it uniquely identifies each user. first_name or age can have duplicate values.
03
Installation & Setup
To practice SQL, you need a database system. There are many options ranging from lightweight local files to robust server software.
Popular RDBMS Options
SQLite: Extremely lightweight, stores data in a local file. Ideal for beginners and mobile apps. No background server process required.
MySQL: Very popular, open-source RDBMS used widely in web development.
PostgreSQL: Advanced, open-source object-relational database known for robustness and complex querying.
For beginners, SQLite is highly recommended. You can use DB Browser for SQLite or try an online compiler like SQL Fiddle.
🚀
You don't need to install anything right away! Many online platforms allow you to run SQL queries directly in your browser.
Practice: Setup
Which database engine is best if you want a lightweight solution that runs without a server?
SQLite is the best choice for a lightweight, serverless database.
04
Creating Databases & Tables
Before you can insert data, you must define the structure of your database and tables using Data Definition Language (DDL).
SQL
CREATE DATABASE company_db;
USE company_db;
Now, let's create a table:
SQL
CREATE TABLE employees (
id INT PRIMARY KEY,
first_name VARCHAR(50),
last_name VARCHAR(50),
age INT,
hire_date DATE
);
Practice: Create Table
Write a query to create a table named products with an id (INT, PRIMARY KEY), name (VARCHAR(100)), and price (DECIMAL).
SQL
CREATE TABLE products (
id INT PRIMARY KEY,
name VARCHAR(100),
price DECIMAL
);
05
Data Types
When creating a table, you must specify the data type for each column. This defines what kind of data can be stored.
Data Type
Description
INT
Numeric value without a decimal (e.g., 42).
VARCHAR(n)
Variable-length character string. Max length is n.
DECIMAL(p, s)
Exact fixed-point number. p is precision, s is scale (e.g. DECIMAL(10,2) stores 99999999.99).
DATE
Date value in format YYYY-MM-DD.
BOOLEAN
True or False. Often represented as 1 and 0 in databases like MySQL.
💡
Data types can vary slightly between different databases (e.g., SQL Server uses DATETIME while Postgres uses TIMESTAMP).
Practice: Data Types
What data type would you use to store a user's biography (which could be long text)?
You would typically use TEXT or VARCHAR(n) with a large number for n.
06
INSERT, UPDATE, DELETE
Data Manipulation Language (DML) commands allow you to modify data within your tables.
Modify existing data. Always use a WHERE clause, otherwise all rows will be updated!
SQL
UPDATE employees
SET age = 29WHERE id = 1;
Deleting Data
Remove rows from a table. Again, use a WHERE clause to avoid deleting everything.
SQL
DELETE FROM employees
WHERE id = 1;
Practice: INSERT
Write an INSERT statement to add a product to the products table with id 10, name 'Laptop', and price 1200.50.
SQL
INSERT INTO products (id, name, price)
VALUES (10, 'Laptop', 1200.50);
07
SELECT Queries
The SELECT statement is used to select data from a database. The result is stored in a result table, called the result-set.
SQL
-- Select specific columnsSELECT first_name, last_name FROM employees;
-- Select all columnsSELECT * FROM employees;
You can also use the DISTINCT keyword to return only distinct (different) values.
SQL
SELECT DISTINCT age FROM employees;
Practice: SELECT
Write a query to fetch only the name and price of all products from the products table.
SQL
SELECT name, price FROM products;
08
WHERE, ORDER BY, LIMIT
These clauses help you filter, sort, and restrict the amount of data returned by a SELECT query.
Filtering with WHERE
Extract only those records that fulfill a specified condition.
SQL
SELECT * FROM employees
WHERE age >= 30AND last_name = 'Smith';
Sorting with ORDER BY
Sort the result-set in ascending (ASC) or descending (DESC) order.
SQL
SELECT * FROM employees
ORDER BY age DESC;
Restricting with LIMIT
Specify the number of records to return. Useful for large tables or pagination.
SQL
SELECT * FROM employees
ORDER BY hire_date DESCLIMIT5;
Practice: Filtering and Sorting
Write a query to select the names of products that cost more than 500, ordered by price from highest to lowest, and limit the result to 10 rows.
SQL
SELECT name FROM products
WHERE price > 500ORDER BY price DESCLIMIT10;
09
Aggregate Functions
Aggregate functions perform a calculation on a set of values and return a single value.
COUNT() - Returns the number of rows
SUM() - Returns the total sum of a numeric column
AVG() - Returns the average value
MIN() - Returns the smallest value
MAX() - Returns the largest value
SQL
SELECTCOUNT(*) as total_employees,
AVG(age) as average_age,
MAX(age) as oldest_employee
FROM employees;
Practice: Aggregate Functions
Write a query to find the total (SUM) price of all products in the products table.
SQL
SELECTSUM(price) FROM products;
10
GROUP BY & HAVING
The GROUP BY statement groups rows that have the same values into summary rows, like "find the number of customers in each country". The HAVING clause was added to SQL because the WHERE keyword cannot be used with aggregate functions.
SQL
SELECT department, COUNT(id) as emp_count
FROM employees
GROUP BY department
HAVINGCOUNT(id) > 5;
⚡
Execution order: WHERE filters before grouping. HAVING filters after grouping.
Practice: GROUP BY
Group a sales table by category and select the category along with the SUM of revenue for each.
SQL
SELECT category, SUM(revenue)
FROM sales
GROUP BY category;
11
JOINs
A JOIN clause is used to combine rows from two or more tables, based on a related column between them.
INNER JOIN: Returns records that have matching values in both tables.
LEFT JOIN: Returns all records from the left table, and the matched records from the right table.
RIGHT JOIN: Returns all records from the right table, and the matched records from the left table.
SQL
SELECT orders.order_id, customers.customer_name
FROM orders
INNER JOIN customers ON orders.customer_id = customers.customer_id;
🔗
When selecting columns with the same name from different tables, prefix the column name with the table name (e.g., table_name.column_name).
Practice: JOINs
Write a query using a LEFT JOIN to list all students and any courses they are enrolled in (using an enrollments table on student_id).
SQL
SELECT students.name, enrollments.course_id
FROM students
LEFT JOIN enrollments ON students.student_id = enrollments.student_id;