Menas
Menas

Reputation: 1249

How to evaluate a logical expression in a column in SQL

let's say I have a database table "ACCOUNTS" where it only has 3 fields:

  1. ACCOUNT_NUMBER (BIGINT)
  2. CREDIT (BIGINT)
  3. DEBIT (BIGINT)

And I simply want to make a query that will show only two columns:

  1. ACCOUNT_NUMBER (BIGINT)
  2. "BALANCED" (A boolean value. True if Credit == Debit, false otherwise)

How do I make such a query?

I tried using the equal operator (=) but it doesn't accept it

SELECT 
    ACCOUNT_NUMBER, 
    CREDIT = DEBIT as "BALANCED"
FROM ACCOUNTS;

Upvotes: 1

Views: 573

Answers (3)

Amit Verma
Amit Verma

Reputation: 2490

you can return bit in SQL instead of Boolean. Use case statement for this.

-- For SQL Server SELECT ACCOUNT_NUMBER, CAST(CASE WHEN DEBIT =CREDIT THEN 1 ELSE 0 END AS BIT) Balanced FROM ACCOUNTS;

-- For Oracle SELECT ACCOUNT_NUMBER, CASE WHEN DEBIT =CREDIT THEN 1 ELSE 0 END Balanced FROM ACCOUNTS;

Upvotes: 0

Marko Ivkovic
Marko Ivkovic

Reputation: 1290

Use CASE like this:

SELECT 
    ACCOUNT_NUMBER, 
    CASE CREDIT WHEN 'DEBIT' THEN 1
    ELSE 0 END AS "BALANCED"
FROM ACCOUNTS;

If it does not fit 0 and 1, change to other values, but this is logic how to do it.

Upvotes: 1

Littlefoot
Littlefoot

Reputation: 142710

There's no Boolean datatype in Oracle's SQL, so you'll have to live with its string (or numeric) representation, such as

select account_number,
       case when credit = debit then 'true'
            else 'false'
       end as balanced
from accounts

Upvotes: 2

Related Questions