Why Utility Functions Matter in PostgreSQL
📖 Scenario: You are managing a small online bookstore database. You often need to calculate the total price of books including tax and apply discounts. Writing the same calculation repeatedly in your queries is tiring and error-prone.Utility functions help by letting you write the calculation once and reuse it everywhere easily.
🎯 Goal: Create a utility function in PostgreSQL that calculates the final price of a book after applying tax and discount. Then use this function in a query to get the final prices for all books.
📋 What You'll Learn
Create a table
books with columns id, title, and priceInsert three books with exact titles and prices
Create a utility function
calculate_final_price that takes price, tax_rate, and discount as inputs and returns the final priceWrite a SELECT query that uses
calculate_final_price to show each book's title and final price with 10% tax and 5% discount💡 Why This Matters
🌍 Real World
Utility functions are used in real databases to avoid repeating complex calculations and to keep queries clean and consistent.
💼 Career
Knowing how to write and use utility functions is important for database developers and analysts to write maintainable and efficient SQL code.
Progress0 / 4 steps