Lessons › SQL › Deep Dive: Text, Date & Number Functions
SQL lesson
ABS()
ABS() gives you the absolute value of a number - meaning it drops any negative sign and returns just the size, never the direction.
Try this lesson free →Example
Measuring Retail Return Differences with ABS()
SELECT return_id, category, price_difference, ABS(price_difference) AS abs_difference
FROM returns
ORDER BY abs_difference DESC| return_id | category | price_difference | abs_difference |
|---|---|---|---|
| R2004 | Home | -130.0 | 130.0 |
| R2001 | Electronics | -45.99 | 45.99 |
| R2002 | Clothing | 12.5 | 12.5 |
| R2003 | Beauty | -8.75 | 8.75 |
| R2005 | Grocery | 3.2 | 3.2 |
Step by step
- Run the query without ABS so you can see what the unfiltered values look like.
SELECT return_id, category, price_difference, price_difference FROM returns ORDER BY abs_difference DESC; - ABS returns the value without its sign - always positive.
SELECT return_id, category, price_difference, ABS(price_difference) FROM returns ORDER BY abs_difference DESC; - AS gives the ABS result a friendly column name so the output reads cleanly.
SELECT return_id, category, price_difference, ABS(price_difference) AS abs_difference FROM returns ORDER BY abs_difference DESC;
Practice
1. Using orders, write a query to show the absolute value of revenue (turn negatives into positives).
SELECT ABS(revenue) FROM orders2. Using store_sales, write a query to show the absolute value of revenue (turn negatives into positives).
SELECT ABS(revenue) FROM store_sales3. Using products, write a query to show the absolute value of price (turn negatives into positives).
SELECT ABS(price) FROM products4. Using reviews, write a query to show the absolute value of rating (turn negatives into positives).
SELECT ABS(rating) FROM reviews5. Using employees, write a query to show the absolute value of salary (turn negatives into positives).
SELECT ABS(salary) FROM employeesLearn it by doing. This lesson is a short hands-on level on Bampaa: see it work, then build and write it yourself, with instant feedback.
Try this lesson free →