Create and Use a User-Defined Function in SQL
📖 Scenario: You work at a retail company that wants to calculate the discounted price for products based on a fixed discount rate.They want to reuse this calculation easily in their database queries.
🎯 Goal: Create a user-defined function in SQL that calculates the discounted price given an original price and a discount rate.Then use this function to find the discounted prices of products in a sample table.
📋 What You'll Learn
Create a table called
products with columns product_id (integer) and price (decimal).Insert three products with prices: 100.00, 200.00, and 300.00.
Create a user-defined function called
calculate_discount that takes original_price and discount_rate as inputs and returns the discounted price.Use the
calculate_discount function in a SELECT query to show product IDs and their discounted prices with a discount rate of 0.1 (10%).💡 Why This Matters
🌍 Real World
Retail companies often need to apply discounts to product prices dynamically in their databases for sales and promotions.
💼 Career
Knowing how to create and use user-defined functions in SQL helps database developers and analysts write reusable, clear, and maintainable code.
Progress0 / 4 steps