DBMS-TONMOY
DBMS-TONMOY
ROLL NO : 2200290120181
DBMS- LAB - 7
DATE FUNCTIONS
CREATE TABLE Products (
Description VARCHAR(20),
Profit_percent INT(6),
Unit_measure VARCHAR(10),
Qty_on_hand INT(6),
Reorder_lvl INT(6),
Last_ordered_date DATE
);
VALUES
('P00123', 'Wireless Mouse', 25, 'pcs', 150, 50, 25.99, 18.00, '2024-10-01'),
('P00456', 'Bluetooth Speaker', 30, 'pcs', 80, 20, 49.99, 35.00, '2024-09-15'),
('P00789', 'Laptop Stand', 20, 'pcs', 200, 100, 29.99, 22.50, '2024-08-25'),
('P01012', 'USB-C Cable', 15, 'pcs', 500, 150, 9.99, 5.00, '2024-10-05'),
('P01134', 'Smartphone Case', 40, 'pcs', 300, 80, 19.99, 12.00, '2024-11-07');
Write SQL query on date column for table on date column (e.g., Last_ordered_date).
SELECT *
FROM Products
2. DATEADD: Fetch products where the last order date was more than 30 days ago
SELECT *
FROM Products
WHERE Last_ordered_date < DATE_SUB(CURRENT_DATE, INTERVAL 30 DAY);
3. DATEDIFF: Fetch products where it has been more than 60 days since the last order
SELECT *
FROM Products
WHERE DATEDIFF(CURRENT_DATE, Last_ordered_date) > 60;
4. YEAR, MONTH, DAY: Fetch products that were last ordered in a specific month and year
SELECT *
FROM Products
WHERE YEAR(Last_ordered_date) = 2024
AND MONTH(Last_ordered_date) = 9;
5. GETDATE: Fetch products that were last ordered within the last week
SELECT *
FROM Products
WHERE Last_ordered_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 WEEK);
6. DATEPART: Fetch products that were last ordered on a weekend (Saturday or Sunday)
8. EXTRACT: Fetch products where the order month is January (for databases that support EXTRACT)
SELECT *
FROM Products
WHERE MONTH(Last_ordered_date) = 1;
9. DATE_TRUNC: Group products by month and count orders per month (for databases that support
DATE_TRUNC)
11. Adding and Subtracting Dates: Fetch products where the last order date is within the next 10 days
(for planning purposes)
SELECT *
FROM Products
WHERE DAYOFWEEK(Last_ordered_date) = 2; -- 2 = Monday in MySQL
13. Calculating Age of Last Order: Find the number of days since each product's last order
14. ISDATE: Check if a date field is valid (for databases that support ISDATE)
SELECT *
FROM Products
WHERE STR_TO_DATE(Last_ordered_date, '%Y-%m-%d') IS NOT NULL;
15. Extract Quarter: Fetch products last ordered in the first quarter of the year
CONSTRAINTS
Add various constraints to the Products table schema for ensuring data integrity:
1. Primary Key Constraint: Ensure that Product_no is unique and serves as the primary key
3. Check Constraints:
● Sell_price should be greater than or equal to Cost_price (to ensure no loss on sale).
4. Default Constraints:
6. Foreign Key Constraint (if there is another table related to Products, such as Suppliers)
8. Index for Faster Searches: Create an index on Last_ordered_date for faster querying by date