Skip to content
Advertisement

Get the final price with discount but only if column is not NULL. SQL

I use these sql tables with these columns:

customers:

id name phone adress etc..
1234 Test Name Test Phone Test Adress etc data.

orders:

customerid orderid orderdate
1234 OR_1234 2022-1-1

orderitems: (in this table one customer can have multiple rows(items)

id orderid productid
1 OR_1234 P1

products:

productid productprice currency qty name weight
P1 10 USD 1 TEST 0.2 KG

So in this case if I want to get the FULL price from the order from customer I use this query:

JavaScript

This query is working perfectly. But what if I want to add to this query a discount from discount table:

discount:

id name value status
1 Discount 1 valid

So I think I will need to create one more column in orders table with name for example: discount_code and if the discount_code column is not empty than subtract the discount value from productprice.

SELECT sum( productprice – discount.value ) as fullprice but how can I make this query? Thank you for help!

BTW I use MariaDB

Have a very nice day!

Advertisement

Answer

If you want to subtract only when your new column is not null, you could simply use IF() func inside you SUM()

In very simple example, assuming you added discount_code

JavaScript

You can also run the example here

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement