Databases & Backend · 15 min read

SQL Queries, Schema Design & Database Indexing Guide

Everything you need to write performant SQL queries, design normalized relational schemas, and eliminate bottlenecks with B-tree indexes.

1. Core CRUD & Filtering Operations

Standard relational SQL operations for querying, filtering, and sorting records.

terminal / code snippet
-- Create table with constraints
CREATE TABLE users (
    id SERIAL PRIMARY KEY,
    email VARCHAR(255) UNIQUE NOT NULL,
    is_active BOOLEAN DEFAULT TRUE,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);

-- Select active users sorted by registration date
SELECT id, email, created_at
FROM users
WHERE is_active = TRUE AND email LIKE '%@gmail.com'
ORDER BY created_at DESC
LIMIT 20 OFFSET 0;

2. Visual Guide to SQL JOINs

Combine data across multiple relational tables efficiently.

terminal / code snippet
-- INNER JOIN: Returns only rows with matches in both tables
SELECT u.email, o.order_id, o.amount
FROM users u
INNER JOIN orders o ON u.id = o.user_id;

-- LEFT JOIN: Returns all users, plus orders if they exist
SELECT u.email, COUNT(o.id) AS total_orders
FROM users u
LEFT JOIN orders o ON u.id = o.user_id
GROUP BY u.id, u.email;

4. Database Indexing & EXPLAIN ANALYZE

Indexes avoid slow sequential table scans on million-row tables.

terminal / code snippet
-- Create a B-Tree index on foreign key or search column
CREATE INDEX idx_orders_user_created ON orders (user_id, created_at DESC);

-- Analyze query execution plan
EXPLAIN ANALYZE
SELECT * FROM orders WHERE user_id = 452 ORDER BY created_at DESC;

Frequently Asked Questions

What is the difference between WHERE and HAVING in SQL?

WHERE filters rows before any aggregation takes place, while HAVING filters aggregated grouped rows after GROUP BY is applied.

When should you NOT add an index to a database column?

Do not index columns with very low cardinality (e.g. boolean flags with only true/false values) or tables with heavy write/insert workloads where index maintenance overhead hurts throughput.

Want Hands-On Practice with Autograded Feedback?

Don't just read guides—practice writing code with DoxaTech's automated challenge tests. Receive real-time feedback on every Git commit.

Start Coding on DoxaTech