Postgresql SQL: How check boolean field with null and True,False Value? - postgresql-9.1

In my database table I am having one boolean column. which have some transaction with will False, True and Null.
These are the cases I have tried:
Case:1
select * from table_name where
boolean_column is null;
works well. Give the result with all transaction having null value for that column.
Case:2
select *from table_name where boolean_column = False;
Works well. Gives result with all the transaction having False value for that column.
Case:3
This is requirement which does not works. I want all the transaction having value False and Null.
I have tried these.
i) select *from table_name where boolean_column is False or Null;
Which only gives the result for False it does not shows null records.
ii) select *from table_name where boolean_column is Null or False;
*Which only gives the result for null it does not shows records with False value. *
iii) select *from table_name where boolean_column is Null or boolean_column = False;
This is simply display all the transaction does not applied any condition at all.
How can this issue be resolved?

There are 3 states for boolean in PG: true, false and unknown (null). Explained here: Postgres boolean datatype
Therefore you need only query for NOT TRUE:
SELECT * from table_name WHERE boolean_column IS NOT TRUE;

I'm not expert enough in the inner workings of Postgres to know why your query with the double condition in the WHERE clause be not working. But one way to get around this would be to use a UNION of the two queries which you know do work:
SELECT * FROM table_name WHERE boolean_column IS NULL
UNION
SELECT * FROM table_name WHERE boolean_column = FALSE
You could also try using COALESCE:
SELECT * FROM table_name WHERE COALESCE(boolean_column, FALSE) = FALSE
This second query will replace all NULL values with FALSE and then compare against FALSE in the WHERE condition.

On PostgreSQL you can use:
SELECT * FROM table_name WHERE (boolean_column IS NULL OR NOT boolean_column)

select *from table_name where boolean_column is False or Null;
Is interpreted as "( boolean_column is False ) or (null)".
It returns only rows where boolean_column is False as the second condition is always false.
select *from table_name where boolean_column is Null or False;
Same reason. Interpreted as "(boolean_column is Null) or (False)"
select *from table_name where boolean_column is Null or boolean_column = False;
This one is valid and returns 2 rows: false and null.
I just created the table to confirm. You might have typoed somewhere.

Resurrecting this to post the DISTINCT FROM option, which has been around since Postgres 8. The approach is similar to Brad Dre's answer. In your case, your select would be something like
SELECT *
FROM table_name
WHERE boolean_column IS DISTINCT FROM TRUE

#Brad Dre's answer is the least code and same efficiency as this one, but potentially harder to understand for future developers. Chris's third and Dmitry's answers already covered this, but I wanted to add an answer with a bit more background.
In the OP's words:
"I want all the transactions having value False and Null."
Re-worded in almost-sql:
"I want all the transactions where the value is False or the value is Null."
Re-worded into SQL:
SELECT *
FROM transactions
WHERE
value IS FALSE
OR value IS NULL;
Often writing the code to be as close as natural language as possible will give future developers hints on the intention of the initial developer. The issue with #Brad Dre's anwser is a future developer might not think of the NULL case in Brad's code, or might have thought Brad forgot about it.

Related

Incorrect default value passed to the SQL Server database

I have set my column to int not null default 1... but whenever I save my record, it sets default value for that record to be 0.
I am not setting it anywhere. I don't know where I am making a mistake.
I have debugged my code , and when I am passing new entity object it is setting default value for not null to 0 .May be it is something with LINQ, But I don't know how to handle it.I don't want to explicitly assign value.
Thanks!
For sql-server, you can use SQL Server Profiler to catch all the scripts you run into the DB.
This may show you some details
Try running this query, replacing the 'myTable' and 'myColumn' values with your actual TABLE and COLUMN names, and see what's returned:
SELECT
OBJECT_NAME(C.object_id) AS [Table Name]
,C.Name AS [Column Name]
,DC.Name AS [Constraint Name]
,DC.Type_Desc AS [Constraint Type]
,DC.Definition AS [Default Value]
FROM sys.default_constraints DC
INNER JOIN sys.Columns C
ON DC.parent_column_id = C.column_id
AND DC.parent_object_id = C.object_id
WHERE OBJECT_NAME(DC.parent_object_id) = 'myTable'
AND COL_NAME(DC.parent_object_id,DC.parent_column_id) = 'myColumn'
;
Should return something like this:
[Table Name] [Column Name] [Constraint Name] [Constraint Type] [Default Value]
-------------------------------------------------------------------------------------------
myTable myColumn DF_myTable_myColumn DEFAULT_CONSTRAINT ('0')
If the [Default Value] returned is indeed (1), then it means that you have set the constraint properly and something else is at play here. It might be a trigger, or some other automated DML that you've forgotten/didn't know about, or something else entirely.
I am not the world's biggest fan of using a TRIGGER, but in a case like this, it could be handy. I find that one of the best uses for a TRIGGER is debugging little stuff like this - because it lets you see what values are being passed into a table without having to scroll through mountains of profiler data. You could try something like this (again, switching out the myTable and myColumn values with your actual table and column names):
CREATE TABLE Default_Check
(
Action_Time DATETIME NOT NULL DEFAULT GETDATE()
,Inserted_Value INT
);
CREATE TRIGGER Checking_Default ON myTable
AFTER INSERT, UPDATE
AS
BEGIN
INSERT INTO Default_Check (Inserted_Value)
SELECT I.myColumn
FROM Inserted I
;
END
;
This trigger would simply list the date/time of an update/insert done against your table, as well as the inserted value. After creating this, you could run a single INSERT statement, then check:
SELECT * FROM Default_Check;
If you see one row, only one action (insert/update) was done against the table. If you see two, something you don't expect is happening - you can check to see what. You will also see here when the 0 was inserted/updated.
When you're done, just make sure you DROP the trigger:
DROP TRIGGER Checking_Default;
You'll want to DROP the table, too, once it's become irrelevant:
DROP TABLE Default_Check;
If all of this still didn't help you, let me know.
In VB use
Property VariableName As Integer? = Nothing
And
In C# use
int? value = 0;
if (value == 0)
{
value = null;
}
Please check My Example:
create table emp ( ids int null, [DOJ] datetime NOT null)
ALTER TABLE [dbo].[Emp] ADD CONSTRAINT DF_Emp_DOJ DEFAULT (GETDATE()) FOR [DOJ]
1--Not working for Default Values
insert into emp
select '1',''
2 ---working for Default Values
insert into emp(ids) Values(13)
select * From emp

how to show record from null column

I have to use from sqlite DB and I insert many data in my sqlite file. now I want execute records that has "NULL". in oder word I want to see records that are "NULL".
when I execute this code I nothing get.
select * from table1 where ParentID = NULL
//or this select * from table1 where ParentID = 'NULL'
this is my sqlite file :
I want execute folder1 with checking ParentID (I need only check ParentID column)
NULL is never equal to anything, including NULL. You need to use IS instead.
SELECT * FROM table1 WHERE ParentID IS NULL
You have to use the following:
select * from table1 where ParentID is NULL
NULL values represent missing unknown data.By default, a table column can hold NULL values.NULL values are treated differently from other values.
SELECT * FROM table1 WHERE ParentID IS NULL
Always use IS NULL to look for NULL values.
You should use IS NULL. (The comparison operators = and <> both give UNKNOWN with NULL on either side of the expression.)
SELECT * FROM table1 WHERE ParentID IS NULL;

SQL: Not equal operator Problem

I am using a not equal operator <> in my sql statement but it doesn't retrieve any record which is not equal to the selected date.
CODE:
Command = New SqlCommand("SELECT * FROM [Products] WHERE [ParkingStartDate] <> #StartDate", myConn)
Command.Parameters.AddWithValue("#StartDate", StartDate1)
This won't return anything if either of the following is true:
StartDate1 is a NULL
ParkingStartDate for all values is a NULL or equal to StartDate1 (obvious one)
Check that you are passing a non-NULL value in StartDate1 and there are records satisfying your condition.
If the values are null you would have to do
Command = New SqlCommand("SELECT * FROM [Products] WHERE [ParkingStartDate] <> #StartDate OR ParkingStartDate is null", myConn)
Command.Parameters.AddWithValue("#StartDate", StartDate1)
First stop using that <> operator.
Use instead != (NOT EQUAL)
run this statement in sql. it will return zero results. to illustrate my point.
select '1' where NULL <> 0
instead use
where columname != #startdate or columnname is null
One important thing to take into consideration when dealing with querying based on date is that the date in SQL Server is treated as exact as the date you send in. So, if you pass in a full date/time, like 2011-10-24 14:35:29, it will return all dates that are not that exact date. If you are looking for a particular portion of that date to be selected against, you need to only give that portion of the date. Using the DATEPART command will help here also.
If the value is undefined, it is not included in <> or != clause.
Along with these you can use sql function 'COALESCE()' to include rows having undefined cells.
"SELECT * FROM [Products] WHERE COALESCE([ParkingStartDate],'') <> #StartDate OR ParkingStartDate is null"
Hope it will help you.
My recommendation would be to try with NULLIF operator. Modify your query to be like :
SELECT * FROM [Products] WHERE NULLIF([ParkingStartDate], #StartDate) IS NOT NULL OR ParkingStartDate is NULL
Hope this helps.

insert/select with a condition

I'm not sure if this is possible but is there a way to select A unless its null then select B instead?
I am writing a trigger, my code is
insert into tbl_a(userid, obj)
select p.author, new.id
FROM user_comment AS p
WHERE p.id=new.parent
however new.parent is a nullable long (i'll switch to foreign key once supported in system.data.sqlite)
if its null i get 0 results and no insert. I would like to use join media as m on m.id=new.media_id and return m.user_id if new.parent is null. So how do i write the select to return m.author if parent isnt null (which i'll return p.author like the above)
You can use IFNULL(col1, col2). If col1 is not null, it is returned. If col1 is null, col2 is returned.

How do I use a boolean field in a where clause in SQLite?

It seems like a dumb question, and yet. It could be my IDE that's goofing me up. Here's the code (this is generated from DbLinq):
SELECT pics$.Caption, pics$.Id, pics$.Path, pics$.Public, pics$.Active, portpics$.PortfolioID
FROM main.Pictures pics$
inner join main.PortfolioPictures portpics$ on pics$.Id = portpics$.PictureId
WHERE portpics$.PortfolioId = 1 AND pics$.Id > 0
--AND pics$.Active = 1 AND pics$.Public = 1
ORDER BY pics$.Id
If I run this query I get three rows back, with two boolean fields called Active and Public. Adding in the commented out line returns no rows. Changing the line to any of the following:
pics$.Active = 'TRUE'
pics$.Active = 't'
pics$.Active = boolean(1)
It doesn't work. Either errors or no results. I've googled for this and found a dearth of actual SQL queries out there. And here we are.
So: how do I use a boolean field in a where clause in SQLite?
IDE is SQLite Administrator.
Update: Well, I found the answer. SQLite Administrator will let you make up your own types apparently; the create SQL that gets generated looks like this:
CREATE TABLE [Pictures] ([Id] INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
[Path] VARCHAR(50) UNIQUE NOT NULL,[Caption] varchAR(50) NULL,
[Public] BOOLEAN DEFAULT '0' NOT NULL,[Active] BOOLEAN DEFAULT '1' NOT NULL)
The fix for the query is
AND pics$.Active = 'Y' AND pics$.Public = 'Y'
The real issue here is, as the first answerer pointed out, there is no boolean type in SQLite. Not an issue, but something to be aware of. I'm using DbLinq to generate my data layer; maybe it shouldn't allow mapping of types that SQLite doesn't support. Or it should map all types that aren't native to SQLite to a string type.
You don't need to use any comparison operator in order to compare a boolean value in your where clause.
If your 'boolean' column is named is_selectable, your where clause would simply be:
WHERE is_selectable
SQLite does not have the boolean type: What datatypes does SQLite support?
The commented-out line as it is should work, just use integer values of 1 and 0 in your data to represent a boolean.
SQLite has no built-in boolean type - you have to use an integer instead. Also, when you're comparing the value to 'TRUE' and 't', you're comparing it to those values as strings, not as booleans or integers, and therefore the comparison will always fail.
Source: http://www.sqlite.org/datatype3.html
--> This Will Give You Result having False Value of is_online field
select * from device_master where is_online!=1
--> This Will Give You Result having True Value of is_online field
select * from device_master where is_online=1

Resources