Learn SQL - 22 Code Examples & CST Typing Practice Test
SQL (Structured Query Language) is a standard language for managing and manipulating relational databases, enabling querying, insertion, updating, and deletion of data efficiently.
View all 22 SQL code examples →
Learn SQL with Real Code Examples
Updated Nov 27, 2025
Explain
SQL provides declarative commands to interact with relational database systems (RDBMS).
Supports querying, filtering, aggregation, joins, and transactions.
Used across major RDBMS like MySQL, PostgreSQL, Oracle, SQL Server, and SQLite.
Enforces schema, data types, constraints, and relationships.
Enables both simple queries and complex analytical operations.
Core Features
SELECT queries with filtering and ordering
INSERT, UPDATE, DELETE operations
JOINs (INNER, LEFT, RIGHT, FULL) and subqueries
GROUP BY, HAVING, and aggregate functions
Transactions and constraint enforcement
Basic Concepts Overview
Database - container for related tables
Table - collection of rows with defined columns
Row/Record - single entry in a table
Column/Field - attribute of a table with data type
Primary/Foreign Keys - enforce uniqueness and relationships
Project Structure
Database instance
Schemas for logical separation
Tables representing entities
Views for reusable queries
Stored procedures/functions for business logic
Building Workflow
Define schema: tables, columns, constraints
Insert initial data
Query and retrieve data using SELECT
Update or delete data as needed
Ensure transactions maintain consistency and integrity
Difficulty Use Cases
Beginner: simple SELECT queries
Intermediate: joins, filtering, and aggregation
Advanced: complex nested queries, CTEs, and window functions
Expert: database optimization, indexing, and partitioning
Enterprise: multi-database transactional systems with replication and sharding
Comparisons
SQL vs NoSQL: SQL for structured data, NoSQL for flexible schema/unstructured data
MySQL vs PostgreSQL: MySQL widely used, PostgreSQL more advanced features
SQL vs GraphQL: SQL queries relational data, GraphQL queries API endpoints
SQL vs ORM query languages: SQL native and powerful, ORM abstracts complexity
SQL vs Excel: SQL handles large datasets efficiently, Excel for small-scale analysis
Versioning Timeline
1970s - SQL developed at IBM
1986 - ANSI SQL standard established
1989 - SQL-89 standard
1992 - SQL-92 with expanded features
2025 - Latest SQL standards with JSON, analytical functions, and windowing support
Glossary
RDBMS - Relational Database Management System
Table - structured collection of rows
Row/Record - single data entry
Column/Field - attribute with data type
Primary/Foreign Key - enforces relationships and uniqueness
Installation Setup
Install an RDBMS like MySQL, PostgreSQL, or SQLite
Start database server and configure credentials
Create a database and define tables
Use command-line client or GUI tools (e.g., pgAdmin, MySQL Workbench)
Connect applications using drivers (JDBC, ODBC, or ORM libraries)
Environment Setup
Install RDBMS server
Create users and databases
Define schemas and tables
Connect with client or application
Test queries and transactions
Config Files
Database configuration files for connection and credentials
SQL scripts for schema creation
Stored procedures/functions for business logic
Backup and restore scripts
ORM mapping files if using with applications
Cli Commands
mysql -u user -p - connect to MySQL
psql -U user dbname - connect to PostgreSQL
CREATE DATABASE dbname; - create database
SHOW TABLES; - list tables
EXPLAIN SELECT ...; - analyze query performance
Internationalization
Supports Unicode and UTF-8 encoding
Locale-specific collations for sorting
Date/time formats configurable
Error messages often translatable in clients
Integrates with applications for localized data
Accessibility
Accessible via database clients, ORMs, or APIs
Permissions restrict read/write access
Views can abstract sensitive data
Encrypted connections improve secure access
Role-based access control enforces authorization
Ui Styling
Primarily backend data layer, no direct UI
Results can be visualized with reporting/BI tools
SQL queries integrate with dashboards
Can feed data to web apps or mobile apps
Optional stored procedures for dynamic reports
State Management
Transactions maintain atomic operations
Temporary tables and session variables can store intermediate state
Locking mechanisms manage concurrent access
Triggers enforce reactive changes
Constraints ensure persistent data integrity
Data Management
Tables store structured data
Indexes optimize query performance
Views and materialized views organize data
Backups ensure recovery
Replication provides high availability
Architecture
Client-server architecture: client sends SQL queries to RDBMS server
Query parser and optimizer interprets SQL commands
Execution engine retrieves and manipulates data
Transaction manager ensures ACID compliance
Storage engine manages physical data storage and indexing
Rendering Model
Client submits SQL query to database server
Query parser and optimizer interprets SQL command
Execution engine retrieves/manipulates data
Transaction manager ensures consistency
Results returned to client
Architectural Patterns
Client-server model
Layered architecture with parser, optimizer, execution engine, storage
Transaction management for ACID compliance
Indexing and query optimization layers
Views and stored procedures for abstraction
Real World Architectures
Enterprise transactional systems (banking, e-commerce)
Data warehouses for analytics and BI
Web application backends with RDBMS
Reporting and dashboards with aggregated data
High-concurrency systems with replication and clustering
Design Principles
Declarative querying
Relational data integrity and normalization
ACID-compliant transactions
Standardized syntax across RDBMS
Extensible with vendor-specific features
Scalability Guide
Use indexing and query optimization
Partition large tables (sharding) if supported
Use replication for read scaling
Leverage connection pooling
Monitor slow queries and optimize execution
Migration Guide
Export and import SQL scripts for migration
Update schema using ALTER statements
Test queries after migration
Adjust for vendor-specific SQL differences
Ensure constraints, indexes, and transactions are preserved
Performance Notes
Use indexes to speed up queries
Avoid SELECT * in large tables
Analyze query execution plans
Partition large tables if necessary
Optimize joins and subqueries
Security Notes
Use parameterized queries to prevent SQL injection
Restrict database user privileges
Encrypt sensitive data at rest and in transit
Enable audit logging for access tracking
Regularly update and patch the RDBMS
Monitoring Analytics
Monitor query performance via EXPLAIN and profiling tools
Track slow queries
Audit access and modification of data
Use replication and backup monitoring
Integrate with monitoring dashboards and alerts
Code Quality
Follow naming conventions for tables and columns
Use constraints and foreign keys for integrity
Write modular and reusable queries/stored procedures
Test queries on sample data before production
Document schema and business logic
Practical Examples
SELECT data with WHERE filters
JOIN multiple tables for relational queries
Aggregate data using SUM, COUNT, AVG, MAX, MIN
Create and manage tables with constraints
Use transactions to ensure atomic operations
Troubleshooting
Check SQL syntax errors
Verify table and column names
Ensure correct data types
Inspect indexes for performance issues
Check transaction and locking conflicts
Testing Guide
Validate queries with sample data
Use transaction rollbacks for safe testing
Check query performance with EXPLAIN/EXPLAIN ANALYZE
Test constraints and triggers
Simulate concurrent access for transactions
Deployment Options
Deploy database server on-premise or cloud
Use managed services like Amazon RDS or Azure SQL
Enable replication for high availability
Containerize with Docker for portability
Integrate with CI/CD pipelines for schema migrations
Tools Ecosystem
RDBMS: MySQL, PostgreSQL, Oracle, SQL Server, SQLite
GUI Tools: pgAdmin, MySQL Workbench, DBeaver
Command-line clients: psql, mysql, sqlcmd
ORMs: Hibernate, Sequelize, SQLAlchemy
ETL and analytics tools: Apache Airflow, Power BI
Integrations
Web applications via JDBC/ODBC/ORM drivers
ETL pipelines for analytics
Data warehouses and BI systems
Reporting tools like Tableau or Power BI
Backup and replication solutions for high availability
Productivity Tips
Use parameterized queries for security
Index frequently queried columns
Normalize data to reduce redundancy
Use views and stored procedures for reusable logic
Profile queries regularly for performance
Challenges
Designing normalized schemas
Writing efficient queries for large datasets
Managing transactions and concurrency
Optimizing indexes and storage
Handling cross-database migrations
Learning Path
Understand relational data modeling
Learn basic CRUD operations
Master joins, subqueries, and aggregation
Study indexing, constraints, and transactions
Practice database optimization and analytics queries
Skill Improvement Plan
Week 1: Basic SELECT, INSERT, UPDATE, DELETE
Week 2: Joins, GROUP BY, and aggregate functions
Week 3: Subqueries, CTEs, and window functions
Week 4: Transactions, constraints, and indexing
Week 5: Performance tuning and backup strategies
Interview Questions
What is SQL and why is it important?
Explain the difference between INNER JOIN, LEFT JOIN, and RIGHT JOIN.
How do transactions ensure data consistency?
What are indexes and how do they improve performance?
Explain normalization and denormalization in databases.
Cheat Sheet
SELECT * FROM table WHERE condition - basic query
INSERT INTO table (columns) VALUES (values) - add data
UPDATE table SET column=value WHERE condition - modify data
DELETE FROM table WHERE condition - remove data
CREATE TABLE table_name (columns) - define schema
Books
SQL in 10 Minutes, Sams Teach Yourself
Learning SQL by Alan Beaulieu
SQL Cookbook by Anthony Molinaro
Pro SQL Server Internals
High Performance MySQL
Tutorials
SQL basics: SELECT, INSERT, UPDATE, DELETE
Joins and subqueries
Aggregate functions and GROUP BY
Transactions and constraints
Advanced querying with window functions
Official Docs
https://www.iso.org/standard/63555.html (SQL standard)
MySQL Documentation
PostgreSQL Documentation
Oracle SQL Reference
SQL Server Docs
Community Links
StackOverflow SQL tag
Database-specific forums (MySQL, PostgreSQL, Oracle)
Reddit r/SQL
Official documentation and GitHub repositories
Tutorial blogs and courses
Community Support
RDBMS-specific forums and StackOverflow
Official documentation (MySQL, PostgreSQL, Oracle, SQL Server)
Community tutorials and blogs
Open-source RDBMS GitHub repositories
Database conferences and webinars
Monetization
Many RDBMS are open-source (MySQL, PostgreSQL, SQLite)
Enterprise editions (Oracle, SQL Server) provide advanced features
Core SQL skills valuable in IT, data, and analytics jobs
Optimized SQL improves application performance
Foundation for business intelligence and reporting
Future Roadmap
Improved JSON and semi-structured data support
Better analytical and window functions
Integration with cloud-native and distributed systems
Enhanced SQL standards adoption across vendors
Performance improvements and parallel query execution
When Not To Use
For unstructured or schema-less data (use NoSQL)
When horizontal scaling of huge datasets is primary concern
Rapid prototyping of small, transient datasets
Applications requiring real-time streaming analytics only
When fully distributed databases are preferred
Final Summary
SQL is the standard language for relational database management.
Enables querying, updating, and managing structured data.
Supports transactions, constraints, and complex joins.
Widely adopted in enterprise, analytics, and web applications.
Works with most RDBMS, with strong community and tooling support.
Faq
Is SQL open-standard? -> Yes, ANSI/ISO standard.
Does SQL work on all RDBMS? -> Core syntax is standard, but extensions vary.
Can SQL handle large datasets? -> Yes, with indexing and optimization.
Is SQL suitable for unstructured data? -> No, consider NoSQL for that.
How do you prevent SQL injection? -> Use parameterized queries and prepared statements.
Code Sample Descriptions
PostgreSQL Advanced Queries
-- Create tables with relationships
CREATE TABLE users (
id SERIAL PRIMARY KEY,
username VARCHAR(50) UNIQUE NOT NULL,
email VARCHAR(100) UNIQUE NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
last_login TIMESTAMP
);
CREATE TABLE posts (
id SERIAL PRIMARY KEY,
user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,
title VARCHAR(200) NOT NULL,
content TEXT,
status VARCHAR(20) DEFAULT 'draft',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE comments (
id SERIAL PRIMARY KEY,
post_id INTEGER REFERENCES posts(id) ON DELETE CASCADE,
user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,
content TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- Insert sample data
INSERT INTO users (username, email) VALUES
('alice', 'alice@example.com'),
('bob', 'bob@example.com'),
('charlie', 'charlie@example.com');
INSERT INTO posts (user_id, title, content, status) VALUES
(1, 'First Post', 'This is my first blog post.', 'published'),
(1, 'Second Post', 'Another interesting post.', 'published'),
(2, 'Draft Post', 'This is still a draft.', 'draft');
INSERT INTO comments (post_id, user_id, content) VALUES
(1, 2, 'Great first post!'),
(1, 3, 'Thanks for sharing.'),
(2, 3, 'Very informative.');
-- Complex queries with JOINs, aggregations, and CTEs
WITH user_stats AS (
SELECT
u.id,
u.username,
COUNT(DISTINCT p.id) as post_count,
COUNT(DISTINCT c.id) as comment_count,
MAX(p.created_at) as last_post_date
FROM users u
LEFT JOIN posts p ON u.id = p.user_id AND p.status = 'published'
LEFT JOIN comments c ON u.id = c.user_id
GROUP BY u.id, u.username
),
popular_posts AS (
SELECT
p.id,
p.title,
u.username as author,
COUNT(c.id) as comment_count,
RANK() OVER (ORDER BY COUNT(c.id) DESC) as popularity_rank
FROM posts p
JOIN users u ON p.user_id = u.id
LEFT JOIN comments c ON p.id = c.post_id
WHERE p.status = 'published'
GROUP BY p.id, p.title, u.username
)
SELECT
us.username,
us.post_count,
us.comment_count,
us.last_post_date,
COALESCE(pp.title, 'No posts') as most_popular_post,
COALESCE(pp.comment_count, 0) as most_popular_post_comments
FROM user_stats us
LEFT JOIN popular_posts pp ON pp.popularity_rank = 1
ORDER BY us.post_count DESC, us.comment_count DESC;
-- Window functions example
SELECT
u.username,
p.title,
p.created_at,
LAG(p.created_at) OVER (
PARTITION BY u.id
ORDER BY p.created_at
) as previous_post_date,
COUNT(*) OVER (
PARTITION BY u.id
) as total_user_posts,
ROW_NUMBER() OVER (
PARTITION BY u.id
ORDER BY p.created_at
) as post_sequence
FROM users u
JOIN posts p ON u.id = p.user_id
WHERE p.status = 'published'
ORDER BY u.username, p.created_at;
Demonstrates advanced SQL features including JOINs, CTEs, window functions, and complex aggregations.
SQL Employee Management System
CREATE TABLE departments (
department_id SERIAL PRIMARY KEY,
department_name VARCHAR(100) NOT NULL,
location VARCHAR(100)
);
CREATE TABLE employees (
employee_id SERIAL PRIMARY KEY,
first_name VARCHAR(50),
last_name VARCHAR(50),
email VARCHAR(100) UNIQUE,
hire_date DATE,
salary DECIMAL(10,2),
department_id INTEGER REFERENCES departments(department_id)
);
INSERT INTO departments (department_name, location) VALUES
('Engineering', 'New York'),
('Marketing', 'Chicago'),
('Finance', 'Boston');
INSERT INTO employees (first_name, last_name, email, hire_date, salary, department_id) VALUES
('John', 'Smith', 'john@example.com', '2022-01-15', 85000, 1),
('Sarah', 'Johnson', 'sarah@example.com', '2021-03-10', 92000, 1),
('Mike', 'Brown', 'mike@example.com', '2023-05-11', 70000, 2),
('Emma', 'Davis', 'emma@example.com', '2020-07-21', 88000, 3);
SELECT
d.department_name,
COUNT(e.employee_id) AS total_employees,
AVG(e.salary) AS avg_salary,
MAX(e.salary) AS highest_salary
FROM departments d
LEFT JOIN employees e ON d.department_id = e.department_id
GROUP BY d.department_name;
SELECT
first_name,
last_name,
salary,
RANK() OVER (ORDER BY salary DESC) AS salary_rank
FROM employees;
CREATE VIEW employee_summary AS
SELECT
e.employee_id,
e.first_name,
e.last_name,
d.department_name,
e.salary
FROM employees e
JOIN departments d ON e.department_id = d.department_id;
SELECT * FROM employee_summary;
Demonstrates employee, department, payroll, and reporting operations using joins, aggregations, views, and window functions.
SQL Employee Management System
CREATE TABLE departments (
department_id SERIAL PRIMARY KEY,
department_name VARCHAR(100) NOT NULL,
location VARCHAR(100)
);
CREATE TABLE employees (
employee_id SERIAL PRIMARY KEY,
first_name VARCHAR(50),
last_name VARCHAR(50),
email VARCHAR(100) UNIQUE,
hire_date DATE,
salary DECIMAL(10,2),
department_id INTEGER REFERENCES departments(department_id)
);
INSERT INTO departments (department_name, location) VALUES
('Engineering', 'New York'),
('Marketing', 'Chicago'),
('Finance', 'Boston');
INSERT INTO employees (first_name, last_name, email, hire_date, salary, department_id) VALUES
('John', 'Smith', 'john@example.com', '2022-01-15', 85000, 1),
('Sarah', 'Johnson', 'sarah@example.com', '2021-03-10', 92000, 1),
('Mike', 'Brown', 'mike@example.com', '2023-05-11', 70000, 2),
('Emma', 'Davis', 'emma@example.com', '2020-07-21', 88000, 3);
SELECT
d.department_name,
COUNT(e.employee_id) AS total_employees,
AVG(e.salary) AS avg_salary,
MAX(e.salary) AS highest_salary
FROM departments d
LEFT JOIN employees e ON d.department_id = e.department_id
GROUP BY d.department_name;
SELECT
first_name,
last_name,
salary,
RANK() OVER (ORDER BY salary DESC) AS salary_rank
FROM employees;
CREATE VIEW employee_summary AS
SELECT
e.employee_id,
e.first_name,
e.last_name,
d.department_name,
e.salary
FROM employees e
JOIN departments d ON e.department_id = d.department_id;
SELECT * FROM employee_summary;
Demonstrates employee, department, payroll, and reporting operations using joins, aggregations, views, and window functions.
SQL Inventory Management
CREATE TABLE suppliers (
supplier_id SERIAL PRIMARY KEY,
supplier_name VARCHAR(100)
);
CREATE TABLE inventory (
item_id SERIAL PRIMARY KEY,
item_name VARCHAR(100),
stock_quantity INTEGER,
reorder_level INTEGER,
supplier_id INTEGER REFERENCES suppliers(supplier_id)
);
INSERT INTO suppliers (supplier_name) VALUES
('Tech Supply Co'),
('Global Parts Ltd');
INSERT INTO inventory (
item_name,
stock_quantity,
reorder_level,
supplier_id
) VALUES
('SSD Drive', 50, 20, 1),
('RAM Module', 15, 25, 1),
('Power Supply', 10, 15, 2);
SELECT
item_name,
stock_quantity,
reorder_level,
CASE
WHEN stock_quantity < reorder_level THEN 'REORDER'
ELSE 'OK'
END AS inventory_status
FROM inventory;
SELECT
s.supplier_name,
COUNT(i.item_id) AS supplied_items
FROM suppliers s
JOIN inventory i
ON s.supplier_id = i.supplier_id
GROUP BY s.supplier_name;
CREATE INDEX idx_inventory_stock
ON inventory(stock_quantity);
SELECT *
FROM inventory
ORDER BY stock_quantity ASC;
Tracks stock levels, suppliers, inventory movement, and reorder alerts.
SQL Customer Segmentation
CREATE TABLE customers (
customer_id SERIAL PRIMARY KEY,
customer_name VARCHAR(100)
);
CREATE TABLE purchases (
purchase_id SERIAL PRIMARY KEY,
customer_id INTEGER REFERENCES customers(customer_id),
purchase_amount DECIMAL(10,2),
purchase_date DATE
);
INSERT INTO customers (customer_name) VALUES
('Alice'),
('Bob'),
('Charlie');
INSERT INTO purchases (
customer_id,
purchase_amount,
purchase_date
) VALUES
(1, 500, '2025-01-01'),
(1, 700, '2025-02-01'),
(2, 100, '2025-02-10'),
(3, 2000, '2025-01-15');
WITH customer_value AS (
SELECT
customer_id,
COUNT(*) AS purchase_count,
SUM(purchase_amount) AS total_spent
FROM purchases
GROUP BY customer_id
)
SELECT
customer_id,
purchase_count,
total_spent,
CASE
WHEN total_spent > 1000 THEN 'VIP'
WHEN total_spent > 300 THEN 'REGULAR'
ELSE 'NEW'
END AS segment
FROM customer_value;
SELECT
customer_id,
total_spent,
NTILE(4) OVER (
ORDER BY total_spent DESC
) AS spending_quartile
FROM (
SELECT
customer_id,
SUM(purchase_amount) AS total_spent
FROM purchases
GROUP BY customer_id
) stats;
Segments customers by purchase behavior, frequency, and lifetime value.
SQL Customer Segmentation
CREATE TABLE customers (
customer_id SERIAL PRIMARY KEY,
customer_name VARCHAR(100)
);
CREATE TABLE purchases (
purchase_id SERIAL PRIMARY KEY,
customer_id INTEGER REFERENCES customers(customer_id),
purchase_amount DECIMAL(10,2),
purchase_date DATE
);
INSERT INTO customers (customer_name) VALUES
('Alice'),
('Bob'),
('Charlie');
INSERT INTO purchases (
customer_id,
purchase_amount,
purchase_date
) VALUES
(1, 500, '2025-01-01'),
(1, 700, '2025-02-01'),
(2, 100, '2025-02-10'),
(3, 2000, '2025-01-15');
WITH customer_value AS (
SELECT
customer_id,
COUNT(*) AS purchase_count,
SUM(purchase_amount) AS total_spent
FROM purchases
GROUP BY customer_id
)
SELECT
customer_id,
purchase_count,
total_spent,
CASE
WHEN total_spent > 1000 THEN 'VIP'
WHEN total_spent > 300 THEN 'REGULAR'
ELSE 'NEW'
END AS segment
FROM customer_value;
SELECT
customer_id,
total_spent,
NTILE(4) OVER (
ORDER BY total_spent DESC
) AS spending_quartile
FROM (
SELECT
customer_id,
SUM(purchase_amount) AS total_spent
FROM purchases
GROUP BY customer_id
) stats;
Segments customers by purchase behavior, frequency, and lifetime value.
SQL Financial Transactions Analysis
CREATE TABLE accounts (
account_id SERIAL PRIMARY KEY,
account_holder VARCHAR(100),
account_type VARCHAR(50)
);
CREATE TABLE transactions (
transaction_id SERIAL PRIMARY KEY,
account_id INTEGER REFERENCES accounts(account_id),
amount DECIMAL(12,2),
transaction_type VARCHAR(20),
transaction_date DATE
);
INSERT INTO accounts (account_holder, account_type) VALUES
('Alice Johnson', 'Savings'),
('Bob Smith', 'Checking');
INSERT INTO transactions (
account_id,
amount,
transaction_type,
transaction_date
) VALUES
(1, 1500, 'deposit', '2025-01-01'),
(1, 300, 'withdrawal', '2025-01-10'),
(2, 2200, 'deposit', '2025-01-03'),
(2, 500, 'withdrawal', '2025-01-15');
SELECT
account_id,
SUM(
CASE
WHEN transaction_type = 'deposit' THEN amount
ELSE -amount
END
) AS current_balance
FROM transactions
GROUP BY account_id;
SELECT
transaction_date,
amount,
SUM(amount) OVER (
ORDER BY transaction_date
) AS running_total
FROM transactions;
Analyzes financial transactions, balances, and monthly spending trends using aggregations and window functions.
SQL Banking System Queries
CREATE TABLE customers (
customer_id SERIAL PRIMARY KEY,
customer_name VARCHAR(100),
email VARCHAR(100)
);
CREATE TABLE bank_accounts (
account_id SERIAL PRIMARY KEY,
customer_id INTEGER REFERENCES customers(customer_id),
balance DECIMAL(12,2)
);
INSERT INTO customers (customer_name, email) VALUES
('John Doe', 'john@example.com'),
('Emma Wilson', 'emma@example.com');
INSERT INTO bank_accounts (
customer_id,
balance
) VALUES
(1, 10000),
(2, 7500);
SELECT
c.customer_name,
b.account_id,
b.balance
FROM customers c
JOIN bank_accounts b
ON c.customer_id = b.customer_id;
SELECT
AVG(balance) AS average_balance,
MAX(balance) AS highest_balance,
MIN(balance) AS lowest_balance
FROM bank_accounts;
Demonstrates customer accounts, transactions, and account summaries.
SQL Order Processing Workflow
CREATE TABLE customers (
customer_id SERIAL PRIMARY KEY,
customer_name VARCHAR(100)
);
CREATE TABLE orders (
order_id SERIAL PRIMARY KEY,
customer_id INTEGER REFERENCES customers(customer_id),
order_status VARCHAR(30),
order_date DATE
);
INSERT INTO customers (customer_name) VALUES
('Alice'),
('Bob');
INSERT INTO orders (
customer_id,
order_status,
order_date
) VALUES
(1, 'Pending', '2025-02-01'),
(1, 'Shipped', '2025-02-02'),
(2, 'Delivered', '2025-02-03');
SELECT
order_status,
COUNT(*) AS total_orders
FROM orders
GROUP BY order_status;
UPDATE orders
SET order_status = 'Completed'
WHERE order_status = 'Delivered';
SELECT *
FROM orders;
Handles order lifecycle, status updates, and customer purchases.
SQL Order Processing Workflow
CREATE TABLE customers (
customer_id SERIAL PRIMARY KEY,
customer_name VARCHAR(100)
);
CREATE TABLE orders (
order_id SERIAL PRIMARY KEY,
customer_id INTEGER REFERENCES customers(customer_id),
order_status VARCHAR(30),
order_date DATE
);
INSERT INTO customers (customer_name) VALUES
('Alice'),
('Bob');
INSERT INTO orders (
customer_id,
order_status,
order_date
) VALUES
(1, 'Pending', '2025-02-01'),
(1, 'Shipped', '2025-02-02'),
(2, 'Delivered', '2025-02-03');
SELECT
order_status,
COUNT(*) AS total_orders
FROM orders
GROUP BY order_status;
UPDATE orders
SET order_status = 'Completed'
WHERE order_status = 'Delivered';
SELECT *
FROM orders;
Handles order lifecycle, status updates, and customer purchases.
SQL Order Processing Workflow
CREATE TABLE customers (
customer_id SERIAL PRIMARY KEY,
customer_name VARCHAR(100)
);
CREATE TABLE orders (
order_id SERIAL PRIMARY KEY,
customer_id INTEGER REFERENCES customers(customer_id),
order_status VARCHAR(30),
order_date DATE
);
INSERT INTO customers (customer_name) VALUES
('Alice'),
('Bob');
INSERT INTO orders (
customer_id,
order_status,
order_date
) VALUES
(1, 'Pending', '2025-02-01'),
(1, 'Shipped', '2025-02-02'),
(2, 'Delivered', '2025-02-03');
SELECT
order_status,
COUNT(*) AS total_orders
FROM orders
GROUP BY order_status;
UPDATE orders
SET order_status = 'Completed'
WHERE order_status = 'Delivered';
SELECT *
FROM orders;
Handles order lifecycle, status updates, and customer purchases.
SQL Healthcare Records Management
CREATE TABLE patients (
patient_id SERIAL PRIMARY KEY,
patient_name VARCHAR(100),
date_of_birth DATE
);
CREATE TABLE appointments (
appointment_id SERIAL PRIMARY KEY,
patient_id INTEGER REFERENCES patients(patient_id),
appointment_date DATE,
doctor_name VARCHAR(100)
);
INSERT INTO patients (
patient_name,
date_of_birth
) VALUES
('Alice Brown', '1990-05-20'),
('David Green', '1985-09-12');
INSERT INTO appointments (
patient_id,
appointment_date,
doctor_name
) VALUES
(1, '2025-03-01', 'Dr. Smith'),
(2, '2025-03-02', 'Dr. Johnson');
SELECT
p.patient_name,
a.appointment_date,
a.doctor_name
FROM patients p
JOIN appointments a
ON p.patient_id = a.patient_id;
SELECT
doctor_name,
COUNT(*) AS total_appointments
FROM appointments
GROUP BY doctor_name;
Stores patients, appointments, and medical records with reporting queries.
SQL University Management System
CREATE TABLE students (
student_id SERIAL PRIMARY KEY,
first_name VARCHAR(50),
last_name VARCHAR(50),
email VARCHAR(100) UNIQUE
);
CREATE TABLE courses (
course_id SERIAL PRIMARY KEY,
course_name VARCHAR(100),
credits INTEGER
);
CREATE TABLE enrollments (
enrollment_id SERIAL PRIMARY KEY,
student_id INTEGER REFERENCES students(student_id),
course_id INTEGER REFERENCES courses(course_id),
enrollment_date DATE
);
INSERT INTO students (first_name, last_name, email) VALUES
('Alice', 'Johnson', 'alice@example.com'),
('Bob', 'Smith', 'bob@example.com');
INSERT INTO courses (course_name, credits) VALUES
('Database Systems', 3),
('Algorithms', 4);
INSERT INTO enrollments (student_id, course_id, enrollment_date) VALUES
(1, 1, '2025-01-10'),
(1, 2, '2025-01-10'),
(2, 1, '2025-01-15');
SELECT
s.first_name,
s.last_name,
c.course_name
FROM students s
JOIN enrollments e
ON s.student_id = e.student_id
JOIN courses c
ON c.course_id = e.course_id
ORDER BY s.first_name;
Manages students, courses, enrollments, and academic reporting.
SQL Library Management Database
CREATE TABLE books (
book_id SERIAL PRIMARY KEY,
title VARCHAR(150),
author VARCHAR(100),
available BOOLEAN DEFAULT TRUE
);
CREATE TABLE members (
member_id SERIAL PRIMARY KEY,
member_name VARCHAR(100)
);
CREATE TABLE borrow_records (
record_id SERIAL PRIMARY KEY,
book_id INTEGER REFERENCES books(book_id),
member_id INTEGER REFERENCES members(member_id),
borrow_date DATE
);
INSERT INTO books (title, author) VALUES
('Clean Code', 'Robert Martin'),
('Design Patterns', 'GoF');
INSERT INTO members (member_name) VALUES
('John Doe'),
('Sarah Brown');
INSERT INTO borrow_records (book_id, member_id, borrow_date) VALUES
(1, 1, '2025-02-01'),
(2, 2, '2025-02-05');
SELECT
m.member_name,
b.title,
br.borrow_date
FROM borrow_records br
JOIN books b
ON br.book_id = b.book_id
JOIN members m
ON br.member_id = m.member_id;
Tracks books, members, and borrowing records.
SQL Hotel Reservation System
CREATE TABLE rooms (
room_id SERIAL PRIMARY KEY,
room_number VARCHAR(10),
room_type VARCHAR(50),
price_per_night DECIMAL(10,2)
);
CREATE TABLE guests (
guest_id SERIAL PRIMARY KEY,
guest_name VARCHAR(100)
);
CREATE TABLE reservations (
reservation_id SERIAL PRIMARY KEY,
guest_id INTEGER REFERENCES guests(guest_id),
room_id INTEGER REFERENCES rooms(room_id),
check_in DATE,
check_out DATE
);
INSERT INTO rooms (room_number, room_type, price_per_night) VALUES
('101', 'Single', 120),
('201', 'Suite', 300);
INSERT INTO guests (guest_name) VALUES
('Alice Johnson'),
('Mark Wilson');
INSERT INTO reservations (guest_id, room_id, check_in, check_out) VALUES
(1, 1, '2025-04-01', '2025-04-05'),
(2, 2, '2025-04-10', '2025-04-15');
SELECT
g.guest_name,
r.room_number,
res.check_in,
res.check_out
FROM reservations res
JOIN guests g
ON g.guest_id = res.guest_id
JOIN rooms r
ON r.room_id = res.room_id;
Handles guests, rooms, reservations, and occupancy reports.
SQL Data Warehouse Operations
CREATE TABLE dim_product (
product_key SERIAL PRIMARY KEY,
product_name VARCHAR(100),
category VARCHAR(50)
);
CREATE TABLE dim_date (
date_key DATE PRIMARY KEY,
year INTEGER,
month INTEGER
);
CREATE TABLE fact_sales (
sales_key SERIAL PRIMARY KEY,
product_key INTEGER REFERENCES dim_product(product_key),
date_key DATE REFERENCES dim_date(date_key),
amount DECIMAL(12,2)
);
INSERT INTO dim_product (product_name, category) VALUES
('Laptop', 'Electronics'),
('Desk', 'Furniture');
INSERT INTO dim_date VALUES
('2025-01-01', 2025, 1),
('2025-02-01', 2025, 2);
INSERT INTO fact_sales (product_key, date_key, amount) VALUES
(1, '2025-01-01', 1500),
(1, '2025-02-01', 1800),
(2, '2025-02-01', 700);
SELECT
dp.category,
SUM(fs.amount) AS total_sales
FROM fact_sales fs
JOIN dim_product dp
ON fs.product_key = dp.product_key
GROUP BY dp.category;
Performs analytical queries and dimensional aggregations.
SQL Audit Trail Reporting
CREATE TABLE users (
user_id SERIAL PRIMARY KEY,
username VARCHAR(50)
);
CREATE TABLE audit_logs (
log_id SERIAL PRIMARY KEY,
user_id INTEGER REFERENCES users(user_id),
action VARCHAR(100),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
INSERT INTO users (username) VALUES
('admin'),
('manager');
INSERT INTO audit_logs (user_id, action) VALUES
(1, 'Created employee record'),
(1, 'Updated salary information'),
(2, 'Generated monthly report');
SELECT
u.username,
a.action,
a.created_at
FROM audit_logs a
JOIN users u
ON a.user_id = u.user_id
ORDER BY a.created_at DESC;
SELECT
u.username,
COUNT(*) AS total_actions
FROM audit_logs a
JOIN users u
ON a.user_id = u.user_id
GROUP BY u.username;
Stores user activity logs and generates audit reports.
SQL Recursive CTE Examples
CREATE TABLE employees (
employee_id SERIAL PRIMARY KEY,
employee_name VARCHAR(100),
manager_id INTEGER REFERENCES employees(employee_id)
);
INSERT INTO employees (employee_name, manager_id) VALUES
('CEO', NULL),
('Engineering Manager', 1),
('Sales Manager', 1),
('Developer A', 2),
('Developer B', 2),
('Sales Executive', 3);
WITH RECURSIVE organization_chart AS (
SELECT
employee_id,
employee_name,
manager_id,
1 AS level
FROM employees
WHERE manager_id IS NULL
UNION ALL
SELECT
e.employee_id,
e.employee_name,
e.manager_id,
oc.level + 1
FROM employees e
JOIN organization_chart oc
ON e.manager_id = oc.employee_id
)
SELECT *
FROM organization_chart
ORDER BY level, employee_name;
Demonstrates hierarchical queries using recursive common table expressions.
SQL Window Functions Analytics
CREATE TABLE monthly_sales (
sale_id SERIAL PRIMARY KEY,
salesperson VARCHAR(100),
sale_month DATE,
revenue DECIMAL(12,2)
);
INSERT INTO monthly_sales (salesperson, sale_month, revenue) VALUES
('John', '2025-01-01', 12000),
('John', '2025-02-01', 15000),
('Sarah', '2025-01-01', 18000),
('Sarah', '2025-02-01', 22000);
SELECT
salesperson,
sale_month,
revenue,
SUM(revenue) OVER (
PARTITION BY salesperson
ORDER BY sale_month
) AS running_total,
LAG(revenue) OVER (
PARTITION BY salesperson
ORDER BY sale_month
) AS previous_month_revenue,
RANK() OVER (
ORDER BY revenue DESC
) AS revenue_rank
FROM monthly_sales
ORDER BY salesperson, sale_month;
Uses ranking, running totals, and lag functions for analytical reporting.
SQL Performance Optimization
CREATE TABLE orders (
order_id SERIAL PRIMARY KEY,
customer_name VARCHAR(100),
order_date DATE,
total_amount DECIMAL(12,2)
);
CREATE INDEX idx_order_date
ON orders(order_date);
CREATE INDEX idx_customer_name
ON orders(customer_name);
INSERT INTO orders (customer_name, order_date, total_amount) VALUES
('Alice', '2025-01-01', 1200),
('Bob', '2025-01-05', 450),
('Alice', '2025-02-01', 850);
CREATE VIEW customer_totals AS
SELECT
customer_name,
COUNT(*) AS total_orders,
SUM(total_amount) AS revenue
FROM orders
GROUP BY customer_name;
SELECT *
FROM customer_totals
ORDER BY revenue DESC;
EXPLAIN ANALYZE
SELECT *
FROM orders
WHERE customer_name = 'Alice';
Illustrates indexes, views, and query optimization techniques.
SQL Advanced Data Migration
CREATE TABLE legacy_customers (
customer_id SERIAL PRIMARY KEY,
full_name VARCHAR(100),
email VARCHAR(100)
);
CREATE TABLE customers (
customer_id SERIAL PRIMARY KEY,
first_name VARCHAR(50),
last_name VARCHAR(50),
email VARCHAR(100)
);
INSERT INTO legacy_customers (full_name, email) VALUES
('Alice Johnson', 'alice@example.com'),
('Bob Smith', 'bob@example.com');
BEGIN;
INSERT INTO customers (
first_name,
last_name,
email
)
SELECT
SPLIT_PART(full_name, ' ', 1),
SPLIT_PART(full_name, ' ', 2),
email
FROM legacy_customers;
COMMIT;
SELECT *
FROM customers;
Shows data migration between legacy and new tables using transactions.
SQL Database Normalization
CREATE TABLE authors (
author_id SERIAL PRIMARY KEY,
author_name VARCHAR(100) NOT NULL
);
CREATE TABLE publishers (
publisher_id SERIAL PRIMARY KEY,
publisher_name VARCHAR(100) NOT NULL
);
CREATE TABLE books (
book_id SERIAL PRIMARY KEY,
title VARCHAR(200) NOT NULL,
author_id INTEGER REFERENCES authors(author_id),
publisher_id INTEGER REFERENCES publishers(publisher_id),
publication_year INTEGER
);
INSERT INTO authors (author_name) VALUES
('Robert Martin'),
('Martin Fowler');
INSERT INTO publishers (publisher_name) VALUES
('Prentice Hall'),
('Addison-Wesley');
INSERT INTO books (
title,
author_id,
publisher_id,
publication_year
) VALUES
('Clean Code', 1, 1, 2008),
('Refactoring', 2, 2, 1999);
SELECT
b.title,
a.author_name,
p.publisher_name,
b.publication_year
FROM books b
JOIN authors a
ON b.author_id = a.author_id
JOIN publishers p
ON b.publisher_id = p.publisher_id
ORDER BY b.publication_year DESC;
Demonstrates normalized database design with relationships and constraints.
Frequently Asked Questions about SQL
What is SQL?
SQL (Structured Query Language) is a standard language for managing and manipulating relational databases, enabling querying, insertion, updating, and deletion of data efficiently.
What are the primary use cases for SQL?
Querying relational data for applications. Data aggregation and reporting. Transaction management in business systems. Analytics and business intelligence. Database schema definition and data integrity enforcement
What are the strengths of SQL?
Standardized and widely supported across RDBMS. Powerful for structured data manipulation. Enables complex queries and analytics. ACID-compliant transactions ensure data reliability. Strong community and documentation support
What are the limitations of SQL?
Less flexible for unstructured or hierarchical data. Complex queries can be hard to optimize. Performance depends on indexing and schema design. Portability issues with vendor-specific SQL extensions. Limited in handling very large-scale distributed data compared to NoSQL
How can I practice SQL typing speed?
CodeSpeedTest offers 22+ real SQL code examples for typing practice. You can measure your WPM, track accuracy, and improve your coding speed with guided exercises.