Grok all the things

grok (v): to understand (something) intuitively.

SQL

👷‍♀️  Professionals

Greetings, curious minds! Today, we're diving into the wonderful world of SQL, the language that makes databases sing and dance. Prepare to embark on a fascinating journey through the quirky characteristics, historical tidbits, and essential concepts that make SQL so intriguing.

A Brief History of SQL 🕰️

Before we plunge into the nitty-gritty, let's take a stroll down memory lane. SQL, or Structured Query Language, first saw the light of day in the early 1970s at IBM. Donald D. Chamberlin and Raymond F. Boyce were the masterminds behind this monumental innovation, originally dubbed SEQUEL (Structured English Query Language). In 1986, SQL became an official standard by ANSI (the American National Standards Institute) , and the rest is history!

Fundamentals of SQL: Gearing Up for Adventure 🏋️‍♂️

SQL is a domain-specific language primarily used to interact with relational databases. It's designed to handle data manipulation and definition tasks, as well as controlling access to databases.

Data Definition Language (DDL) 🌉

DDL commands define, modify, and delete database structures such as tables and indexes. A few examples of DDL commands include:

  • CREATE TABLE
  • ALTER TABLE
  • DROP TABLE
-- Creating a new table named "employees"
CREATE TABLE employees (
    id INT PRIMARY KEY,
    first_name VARCHAR(50),
    last_name VARCHAR(50),
    position VARCHAR(100),
    salary DECIMAL(10, 2)
);

Data Manipulation Language (DML)🔨

DML instructions let you insert, update, and delete data within the database tables. The main DML commands are:

  • SELECT
  • INSERT
  • UPDATE
  • DELETE
-- Inserting a new record into the "employees" table
INSERT INTO employees (id, first_name, last_name, position, salary)
VALUES (1, 'Ada', 'Lovelace', 'Data Analyst', 60000.00);

-- Updating the salary of an existing employee
UPDATE employees
SET salary = 65000.00
WHERE id = 1;

-- Deleting a specific employee record
DELETE FROM employees
WHERE id = 1;

Data Control Language (DCL) 🔐

DCL commands control user access to database objects. The most common DCL instructions are:

  • GRANT
  • REVOKE
-- Granting SELECT and UPDATE permissions on the "employees" table to a specific user
GRANT SELECT, UPDATE ON employees TO some_user;

-- Revoking UPDATE permission from the user
REVOKE UPDATE ON employees FROM some_user;

Joins: Bringing Tables Together 🤝

One of the most magical aspects of SQL is its capacity to connect distinct tables via joins. This powerful feature allows you to combine data from multiple sources with ease.

There are several types of joins, including INNER JOIN, LEFT JOIN, RIGHT JOIN, and FULL OUTER JOIN. Let's examine each one with the help of two tables: orders and customers.

INNER JOIN 🎯

The INNER JOIN returns rows from both tables that meet the specified condition.

SELECT o.id, o.order_date, c.first_name, c.last_name
FROM orders o
INNER JOIN customers c ON o.customer_id = c.id;

LEFT JOIN ↔️

The LEFT JOIN fetches all rows from the left table (orders), as well as matching rows from the right table (customers). If there's no match, NULL values are returned for the right table's columns.

SELECT o.id, o.order_date, c.first_name, c.last_name
FROM orders o
LEFT JOIN customers c ON o.customer_id = c.id;

RIGHT JOIN ↔️

The RIGHT JOIN is the inverse of the LEFT JOIN. It returns all rows from the right table and matching rows from the left table, with NULL values for non-matching left table columns.

SELECT o.id, o.order_date, c.first_name, c.last_name
FROM orders o
RIGHT JOIN customers c ON o.customer_id = c.id;

FULL OUTER JOIN ⭕

The FULL OUTER JOIN combines the results of the LEFT JOIN and RIGHT JOIN. It returns all rows from both tables, with NULL values for non-matching columns.

SELECT o.id, o.order_date, c.first_name, c.last_name
FROM orders o
FULL OUTER JOIN customers c ON o.customer_id = c.id;

Subqueries: Queries within Queries 🤯

Subqueries (a.k.a. inner or nested queries) are queries embedded within other SQL queries. They're incredibly versatile, allowing you to access intermediate results or perform complex filtering. Behold their majesty:

-- Retrieving employees with a salary higher than the average salary
SELECT first_name, last_name, salary
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);

Stored Procedures & User-Defined Functions (UDFs) 🎩

Stored procedures and UDFs are predefined SQL code blocks that can be reused to simplify repetitive tasks. Stored procedures don't return a value by default, whereas UDFs do.

-- Creating a stored procedure that returns all employees with a specific position
CREATE PROCEDURE GetEmployeesByPosition @position VARCHAR(100)
AS
BEGIN
    SELECT first_name, last_name
    FROM employees
    WHERE position = @position;
END;

-- Executing the stored procedure
EXEC GetEmployeesByPosition 'Data Analyst';

-- Creating a user-defined function that calculates the total salary expenses
CREATE FUNCTION TotalSalaryExpenses()
RETURNS DECIMAL(10, 2)
AS
BEGIN
    RETURN (SELECT SUM(salary) FROM employees);
END;

-- Using the user-defined function
SELECT dbo.TotalSalaryExpenses();

Transactions: Keeping Data Safe & Sound 🔒

Transactions are a critical aspect of SQL, ensuring data integrity and consistency. They allow you to bundle multiple SQL statements into a single, atomic unit of work. Key transaction control commands include:

  • BEGIN TRANSACTION
  • COMMIT
  • ROLLBACK
  • SAVEPOINT
-- Starting a new transaction
BEGIN TRANSACTION;

-- Inserting a new employee and updating the total salary expenses
INSERT INTO employees (id, first_name, last_name, position, salary)
VALUES (2, 'Charles', 'Babbage', 'Software Engineer', 70000.00);

UPDATE company_expenses
SET total_salary_expenses = dbo.TotalSalaryExpenses();

-- Committing the transaction
COMMIT;

And there you have it – a whirlwind tour of SQL's captivating landscape! From its inception at IBM to its modern-day ubiquity, SQL has stood the test of time and proven itself an essential tool for data wrangling. Whether you're a database administrator, a developer, or a data scientist, mastery of SQL will undoubtedly serve you well. Embrace the journey and happy querying!

Grok.foo is a collection of articles on a variety of technology and programming articles assembled by James Padolsey. Enjoy! And please share! And if you feel like you can donate here so I can create more free content for you.