Lecture Week 3-Databases
Lecture Week 3-Databases
Databases-Week 3
SELECT
SELECT Command
PIVOT Command
• purpose: Transforms rows into columns, often used in reporting.
• Usage: Typically used to aggregate data and restructure it for easier analysis.
SELECT *
FROM (SELECT ProductID, SalesDate, Quantity FROM Sales) AS
SourceTable
PIVOT (SUM(Quantity) FOR SalesDate IN ([2023], [2024])); AS
PivotTable;
ROLLUP
ROLLUP
• Purpose: Creates subtotals that roll up from detailed data to
higher-level data, often used in aggregations.
• Usage: Used with `GROUP BY` to generate subtotals and grand
totals
SELECT category, SUM(sales)
FROM Products
GROUP BY ROLLUP(category);
OFFSET
OFFSET Command
• Purpose: Skips a specified number of rows before starting to return
rows in the result set.
• Usage: Often used with `LIMIT` or `FETCH` to implement pagination.
FETCH more readable than LIMIT
ORDER BY id
OFFSET 10 ROWS FETCH NEXT 5 ROWS ONLY; --LIMIT 5
OFFSET 10
TOP
TOP Command
GROUP BY
JOIN table.
• RIGHT JOIN → Includes unmatched rows from the
right table.
• FULL JOIN → Includes unmatched rows from both
JOIN
tables
• Purpose: Combines •rows
Cross
fromJOIN:
two orenumerate all possible
more tables based combinations
on a related
column between them.
• Types: INNER JOIN, LEFT JOIN, RIGHT JOIN, FULL OUTER JOIN, CROSS JOIN.
Using JOINT without specifying a type defaults into INNER (only match).
FROM Users
SQL Operators
Creating the Database
-- Step 4: Create a 'Products' table
CREATE TABLE Products (
ProductID INT PRIMARY KEY,
and Tables ProductName VARCHAR(100) NOT NULL,
Category VARCHAR(50),
-- Step 1: Create a database
Price DECIMAL(10, 2) CHECK (Price > 0) -- Price must be
CREATE DATABASE ECommerce; greater than 0
);
ng SET email =
Data '[email protected]'
WHERE id = 1;
-- Merge new sales data into the Sales table
Sales
breakdown by product
SELECT u.username, p.ProductName,
Report
SUM(s.Quantity) AS TotalQuantity,
SUM(s.Quantity * p.Price) AS TotalSales
ns
•Explanation of SQL Operations in This Example
1. USE: Switches to the ECommerce database to perform all operations.
2. INSERT: Adds records to the Users, Products, and Sales tables.
3. UPDATE: Modifies the email of a user.
4. DELETE: Removes a record from the Users table.
5. MERGE: Combines data from a source query into the Sales table, either updating or inserting new records
based on conditions.
6. SELECT: Retrieves specific information using filtering, ordering, and grouping functions.
7. PIVOT: Transforms sales data by converting dates from rows to columns.
8. ROLLUP: Aggregates data to calculate subtotals for each product category.
9. OFFSET: Skips the first few rows and fetches the next set of results for pagination.
10.TOP: Limits the number of rows returned by the query.
11.Join: used to combine data from two or more tables based on a related column (INNER, LEFT, RIGHT, FULL,
CROSS)