Introduction to SQL

repository·main·Indexed 19 days ago

https://github.com/bobbyiliev/introduction-to-sql

An open-source educational resource and eBook providing a comprehensive introduction to SQL and relational databases. Designed for developers, DevOps/SysOps engineers, and system administrators, it covers MySQL installation across Ubuntu/Debian, macOS, and Windows, basic syntax, data retrieval (SELECT, JOIN, Sub Queries), data manipulation (INSERT, UPDATE, DELETE), and advanced utility topics like the MySQL dump command.

Tokens
19.3K
Snippets
96
Records
118
Agent score
64%

What's inside introduction-to-sql

  1. What is Materialize?

    main

    Materialize is a streaming database designed for real-time analytics. Unlike traditional SQL engines that run queries against static snapshots, Materialize maintains the answers to SQL queries over time using materialized views. As new data flows in from various sources, the views are incrementally updated.

    Supported input sources include:

    • Streaming sources: e.g., Kafka
    • Object stores: e.g., S3
    • Database change feeds: e.g., PostgreSQL
    • Files: CSV, JSON, and unstructured files like logs.
  2. What is a SQL Subquery and how does it work?

    main

    A subquery is a SQL query nested inside a larger (parent) query. The inner query executes first, and its results are passed to the outer query to be used in filtering or data manipulation.

    Subqueries can be placed in the following clauses:

    • SELECT clause: To return specific values for each row.
    • FROM clause: To treat the subquery result as a temporary table.
    • WHERE clause: To filter rows based on the results of the inner query (the most common usage).

    Subqueries can be nested within SELECT, INSERT, UPDATE, or DELETE statements, and can even be nested inside other subqueries.

  3. Use the HAVING clause to filter grouped results

    main

    The HAVING clause is used to specify conditions that filter which groups appear in the result set. Unlike the WHERE clause, which imposes conditions on individual columns/rows, HAVING is specifically designed to work with aggregate functions and must follow the GROUP BY clause in a query.

    Syntax:

    SELECT column_name(s)
    FROM table_name
    WHERE condition
    GROUP BY column_name(s)
    HAVING condition
    ORDER BY column_name(s);
    SELECT column_name(s)
    FROM table_name
    WHERE condition
    GROUP BY column_name(s)
    HAVING condition
    ORDER BY column_name(s);
  4. Understand and use SQL Triggers

    main

    A trigger is a stored procedure in a database that is automatically invoked when a specific event occurs, such as INSERT, UPDATE, or DELETE.

    Triggers are commonly used to:

    • Validate data before it is stored (using before triggers).
    • Perform automated tasks after data changes (using after triggers), such as logging changes or updating related tables.

    Trigger Levels

    • Row-level triggers (for each row): The trigger executes for every individual row affected by the DML operation.
    • Column-level triggers (for each column): The trigger executes when a specific column is affected.
    create trigger [trigger_name] 
    [before | after]  
    {insert | update | delete}  
    on [table_name]  
    [for each row | for each column]  
    [trigger_body] 
  5. Use DDL (Data Definition Language) to manage database schema

    main

    DDL commands are used to create, modify, and delete the structure of database objects like tables, indexes, and views. These are typically used by administrators rather than general application users.

    Available DDL commands:

    • CREATE: Creates a new database or object (e.g., CREATE TABLE).
    • DROP: Deletes an existing object from the database.
    • ALTER: Modifies the structure of an existing object (e.g., adding a column).
    • TRUNCATE: Removes all records from a table and releases the allocated space.
    • COMMENT: Adds comments to the data dictionary.
    • RENAME: Renames an existing object or column.
    -- Create a table
    CREATE TABLE Persons (
        PersonID int,
        LastName varchar(255),
        FirstName varchar(255),
        Address varchar(255),
        City varchar(255)
    );
    
    -- Alter a table to add a column
    ALTER TABLE Persons ADD Age int;
    
    -- Rename a column
    ALTER TABLE Persons RENAME COLUMN Age TO Year;
    
    -- Remove all records from a table
    TRUNCATE TABLE Persons;
    
    -- Delete an entire object
    DROP TABLE table_name;
  6. Convert LEFT JOIN to RIGHT JOIN

    main

    A LEFT JOIN and a RIGHT JOIN are functionally equivalent. You can convert a LEFT JOIN into a RIGHT JOIN by swapping the order of the tables in the FROM and JOIN clauses.

    • TableA LEFT JOIN TableB is the same as TableB RIGHT JOIN TableA.
    -- Original LEFT JOIN
    SELECT users.*, posts.*
    FROM posts
    LEFT JOIN users 
    ON posts.user_id = users.id;
    
    -- Equivalent RIGHT JOIN
    SELECT users.*, posts.*
    FROM users
    RIGHT JOIN posts 
    ON posts.user_id = users.id;
  7. Understand Candidate Keys

    main

    A Candidate Key is a minimal Super Key. This means it is a set of attributes that uniquely identifies a tuple, but if you were to remove any attribute from the set, it would no longer be unique. Candidate Keys are the specific sets of attributes that are 'candidates' to become the Primary Key.

    Example: If a Customer relation has the following Super Keys:

    • [CustomerID]
    • [CustomerID, CustomerName]
    • [CustomerName, CustomerAddress]

    The Candidate Keys would be [CustomerID] and [CustomerName, CustomerAddress], because the second one is a minimal set that provides uniqueness.

  8. Implement Referential Integrity with Foreign Keys

    main

    A Foreign Key is an attribute (or set of attributes) in one relation (the referencing relation) that refers to the Primary Key of another relation (the referenced relation).

    Key Rules:

    • Foreign keys implement referential integrity.
    • The values in the foreign key column must exist in the Primary Key column of the referenced table.
    • A relation can have multiple foreign keys.

    Example: If you have a Customer table (referenced) and an Orders table (referencing):

    • Customer Primary Key: CustomerID
    • Orders structure: (Order ID, Customer ID, Order Date, ...)
    • In this case, Customer ID in the Orders table is a Foreign Key referencing CustomerID in the Customer table. This ensures an order cannot be placed for a customer that does not exist.
  9. Use the UNION ALL clause to combine SELECT statements including duplicates

    main

    The UNION ALL operator combines the result sets of two or more SELECT statements, but unlike UNION, it includes duplicate rows in the final output. This is often faster because the database does not need to perform the extra step of checking for and removing duplicates.

    Just like the UNION clause, UNION ALL requires that all SELECT statements have the same number of columns, the same number of expressions, and compatible data types in the same order.

    SELECT id, name, amount, date
       FROM customers
       LEFT JOIN orders
       ON customers.id = orders.customer_id
    UNION ALL
       SELECT id, name, amount, date
       FROM customers
       RIGHT JOIN orders
       ON customers.id = orders.customer_id;
  10. Use SQL Aggregate Functions

    main

    SQL aggregation collects a set of values to return a single value. An aggregate function groups multiple rows together based on certain criteria to form a single value of significant meaning.

    Supported aggregate functions include:

    • AVG(): Calculates the average of the values in a given column.
    • SUM(): Calculates the sum of values in a given column.
    • COUNT(): Returns the count of entries/values in a given column.
    • MAX(): Returns the maximum value from the column.
    • MIN(): Returns the minimum value from the column.