Is this the right way to run a logical test in SQL?

Suppose the “boolean field” is active (tiny int, with 0 or 1)

# Find all active users select * from users where active # Find all inactive users select * from users where NOT active 

In words, can the "NOT" operator be applied directly to a logical field?

+41
sql boolean-expression
May 13 '09 at 18:59
source share
7 answers

A boolean in SQL is a bit field. This means 1 or 0. The correct syntax is:

 select * from users where active = 1 /* All Active Users */ 

or

 select * from users where active = 0 /* All Inactive Users */ 
+44
May 13, '09 at 19:01
source share

With Postgres you can use

 select * from users where active 

or

 select * from users where active = 't' 

If you want to use an integer value, you should consider it as a string. You cannot use an integer value.

 select * from users where active = 1 -- Does not work select * from users where active = '1' -- Works 
+11
May 13, '09 at 19:13
source share

MS SQL 2008 can also use the string version of true or false ...

 select * from users where active = 'true' -- or -- select * from users where active = 'false' 
+7
May 13 '09 at 19:08
source share

In SQL Server, you usually use. I do not know other database engines.

 select * from users where active = 0 
+6
May 13 '09 at 19:00
source share

I personally prefer to use char (1) with the values ​​'Y' and 'N' for databases that don't have a native type for boolean. Letters are more users than numbers, which suggest that those who read it will now match 1, and 0 corresponds to false.

'Y' and 'N' are also displayed well when using (N) sleep mode.

+2
May 13 '09 at 19:30
source share

PostgreSQL supports boolean types, so your SQL query will work fine in PostgreSQL.

0
May 14 '09 at 1:44
source share

If you are using SQLite3, be careful:

Only "t" or "f" is required. Not 1 or 0. Not TRUE OR FALSE.

Just studied hard.

-one
Mar 01 '17 at 3:09 on
source share



All Articles