LO1: MS SQL server
Databases-Week 3
SELECT
SELECT Command
• Purpose: Retrieves data from one or more tables.
• Usage: Queries the database to extract and display data
based on conditions.
SELECT username, age FROM Users WHERE
age > 18;
PIVOT
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
SELECT username FROM Users
ORDER BY id
OFFSET 10 ROWS FETCH NEXT 5 ROWS ONLY; --LIMIT 5
OFFSET 10
TOP
TOP Command
• Purpose: Limits the number of rows returned by a query.
• Usage: Fetches only the top `N` rows from a result set, often used to
retrieve the first few rows of a large dataset.
SELECT TOP 5 username, age FROM Users ORDER BY
age DESC;
GROUP BY
GROUP BY
• Purpose: Groups rows that have the same values in
specified columns into summary rows, often used with
aggregate functions like SUM, COUNT, AVG, etc.
• Usage: To create summaries or totals based on column
values.
SELECT age, COUNT(*) FROM Users GROUP
BY age;
• LEFT JOIN → Includes unmatched rows from the left
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).
SELECT Users.username, Orders.order_id
FROM Users
INNER JOIN Orders ON Users.id = Orders.user_id;
Ecommerce Database
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
);
-- Step 2: Use the newly created database
-- Step 5: Create a 'Sales' table
USE ECommerce;
CREATE TABLE Sales (
SaleID INT PRIMARY KEY,
-- Step 3: Create a 'Users' table ProductID INT,
CREATE TABLE Users ( UserID INT,
id INT PRIMARY KEY, Quantity INT CHECK (Quantity > 0),
username VARCHAR(50) NOT NULL UNIQUE, SalesDate DATE DEFAULT GETDATE(),
FOREIGN KEY (ProductID) REFERENCES Products(ProductID),
email VARCHAR(100) NOT NULL UNIQUE,
FOREIGN KEY (UserID) REFERENCES Users(id)
age INT CHECK (age > 18), -- Age must be greater than 18
);
status VARCHAR(20) DEFAULT 'active' -- Default status is
'active'
-- Step 6: Create an index on the SalesDate for fast querying
);
CREATE INDEX idx_salesdate ON Sales (SalesDate);
Inserting Data into the Tables
-- Step 1: Insert data into the Users table
INSERT INTO Users (id, username, email, age) -- Step 3: Insert data into the
VALUES (1, 'john_doe', '
[email protected]', Sales table
25),
INSERT INTO Sales (SaleID,
(2, 'jane_smith', '
[email protected]', 30),
ProductID, UserID, Quantity,
(3, 'alice_jones', '
[email protected]', 22); SalesDate)
-- Step 2: Insert data into the Products table VALUES (1, 101, 1, 1, '2024-09-
INSERT INTO Products (ProductID, 01'),
ProductName, Category, Price)
(2, 102, 2, 2, '2024-09-02'),
VALUES (101, 'Laptop', 'Electronics', 1200.00),
(3, 103, 3, 1, '2024-09-03');
(102, 'Smartphone', 'Electronics', 800.00),
(103, 'Tablet', 'Electronics', 500.00);
-- Update a user's email
Updati UPDATE Users
ng SET email =
Data '[email protected]'
WHERE id = 1;
-- Merge new sales data into the Sales table
MERGE INTO Sales AS target
USING (SELECT 102 AS ProductID, 2 AS UserID, 3 AS Quantity,
'2024-09-04' AS SalesDate) AS source
Mergin ON (target.ProductID = source.ProductID AND target.UserID =
source.UserID)
WHEN MATCHED THEN
g Data UPDATE SET target.Quantity = source.Quantity, target.SalesDate =
source.SalesDate
WHEN NOT MATCHED THEN
INSERT (SaleID, ProductID, UserID, Quantity, SalesDate)
VALUES (4, source.ProductID, source.UserID, source.Quantity,
source.SalesDate);
Selecting Data with Different
Queries
-- Simple SELECT to retrieve all users -- PIVOT to transform sales data (Sales per
SELECT * FROM Users; product per day)
SELECT *
-- SELECT specific columns and records FROM (SELECT ProductID, SalesDate,
Quantity FROM Sales)
SELECT username, email FROM Users WHERE age >
20; PIVOT (SUM(Quantity) FOR SalesDate IN
([2024-09-01], [2024-09-02], [2024-09-03]))
AS PivotTable;
-- SELECT with OFFSET for pagination (skip the first
row)
SELECT * FROM Users ORDER BY id OFFSET 1 ROWS
-- Using ROLLUP to aggregate sales by
FETCH NEXT 2 ROWS ONLY; product category
SELECT Category, SUM(Price) AS TotalSales
-- SELECT TOP N rows FROM Products
SELECT TOP 2 * FROM Products ORDER BY Price GROUP BY ROLLUP(Category);
DESC;
Deleting Data
-- Delete a specific user from
the Users table
DELETE FROM Users WHERE id
= 3;
Creating a -- Get total sales for each user along with a
Sales
breakdown by product
SELECT u.username, p.ProductName,
Report
SUM(s.Quantity) AS TotalQuantity,
SUM(s.Quantity * p.Price) AS TotalSales
with FROM Sales s
Constraint JOIN Users u ON s.UserID = u.id
s and JOIN Products p ON s.ProductID = p.ProductID
Aggregatio GROUP BY u.username, p.ProductName;
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)