Skip to content
AstralSurgeLearnings XP 0 Streak 0
AstralSurgeLearnings

SQL Basics

Structured Query Language (SQL) is the standard declarative programming language used to interact with Relational Database Management Systems (RDBMS) such as PostgreSQL, MySQL, SQL Server, and Oracle. SQL enables developers to define database schemas, retrieve targeted records, combine datasets across tables, and guarantee data consistency.

1. Relational Database Foundations

  • Tables, Rows, and Columns: A relational database stores information in structured two-dimensional tables. Each row (record) represents an individual entity instance, while each column (field) enforces a specific data type (INT, VARCHAR, BOOLEAN, TIMESTAMP).
  • Primary Key (PK): A unique identifier assigned to every row in a table that guarantees non-null, distinct identification.
  • Foreign Key (FK): A column referencing the primary key of another table, establishing relational integrity across datasets.

2. Data Definition: Creating Tables

CREATE TABLE customers (
    customer_id SERIAL PRIMARY KEY,
    first_name VARCHAR(50) NOT NULL,
    last_name VARCHAR(50) NOT NULL,
    email VARCHAR(100) UNIQUE NOT NULL,
    country VARCHAR(50) DEFAULT 'USA',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

3. Querying and Filtering Data (DQL)

The SELECT statement extracts data, while the WHERE clause filters rows based on conditional predicates:

-- Select explicit columns rather than using SELECT *
SELECT first_name, last_name, email
FROM customers
WHERE country = 'Germany' 
  AND email LIKE '%@gmail.com'
ORDER BY last_name ASC
LIMIT 10;

4. Combining Tables with JOIN Operations

Relational modeling separates data into normalized tables. Use joins to link records together based on related keys:

  • INNER JOIN: Returns only rows that match in both tables.
  • LEFT (OUTER) JOIN: Returns all rows from the left table and matched rows from the right table (filling in NULL for unmatched rows).
SELECT c.customer_id, c.first_name, o.order_id, o.total_amount
FROM customers c
INNER JOIN orders o ON c.customer_id = o.customer_id
WHERE o.order_date >= '2025-01-01';

5. Aggregations and Summaries

Group and analyze records using aggregate functions (COUNT, SUM, AVG, MAX, MIN). Use HAVING to filter aggregate calculations:

SELECT c.country, COUNT(o.order_id) AS total_orders, AVG(o.total_amount) AS avg_spend
FROM customers c
JOIN orders o ON c.customer_id = o.customer_id
GROUP BY c.country
HAVING COUNT(o.order_id) > 50
ORDER BY avg_spend DESC;

6. Modifying Data (DML)

  • INSERT: INSERT INTO customers (first_name, last_name, email) VALUES ('Alex', 'Smith', 'alex@example.com');
  • UPDATE: UPDATE customers SET country = 'Canada' WHERE customer_id = 42; (Always include a WHERE clause to avoid overwriting all rows).
  • DELETE: DELETE FROM customers WHERE customer_id = 42;

7. Production SQL Best Practices

  • Avoid SELECT *: Request only the columns required by your application to minimize network overhead and database I/O.
  • Index Lookup Columns: Place B-tree indexes on foreign keys and frequently queried filter columns to prevent full table scans.
  • Prevent SQL Injection: Always execute SQL using parameterized queries or PreparedStatements; never concatenate user input into SQL strings.

0 Comments