SQLite IF Exists Clause - sql

How to write IF EXISTS as shown in below query in SQLite? I read somewhere that IF clause doesn't exist in SQLite. What would be a better alternative for this?
if exists (select username from tbl_stats_assigned where username = 'abc' )
select 1 as uname
else
select 0 as uname

Just do it the standard SQL way:
select exists(
select 1
from tbl_stats_assigned
where username = 'abc'
);
Assuming of course that your 1 and 0 are actually boolean values (which SQLite represents with one and zero just like MySQL).
That should work in any SQL database and some even have special optimizations to support that idiom.

Related

checking for boolean true / false result in postgresql query

I am running the following sql query in my web app:
SELECT EXISTS (
SELECT id
FROM user
WHERE membership=1244)
i was expecting true (boolean data) as the result but I'm getting 't' or 'f' for false.
How do I get it to return to my lua code a standard boolean?
I found the following post:
Reading boolean correctly from Postgres by PHP
And so I tried to change my code to something like this:
SELECT EXISTS ::int (
SELECT id
FROM user
WHERE membership=1244)
or
SELECT ::INT (SELECT EXISTS (
SELECT id
FROM user
WHERE membership=1244))
But I'm getting a syntax error.
Can you tell the best way to handle this? Should I be casting the resulting 't' to a boolean somehow? or is there a way to tell postgresql to return true / false instead of 't'/'f'?
Thanks.
You are so close
SELECT EXISTS (SELECT id FROM user WHERE membership=1244)::int
Your first query do indeed return a boolean. A t is shown as the returned value of the query
select exists (select 1);
exists
--------
t
But if you check its type it is a boolean:
select pg_typeof(exists (select 1));
pg_typeof
-----------
boolean
You will have to check with the lua's postgresql driver manual how to properly handle it.
Try it with CASE
select
(case when exists (SELECT id FROM user WHERE membership = 1244)
then 1
else 0
end) as column;
my test fiddle
Your initial query is fine by itself:
SELECT id FROM user WHERE membership=1244
You just need to check if it returns a row or not.

SQLite: detect if a rowid exists

What's the best/right/fastest/most appropriate way to detect if a row with a given rowid exists?
Or by extension, hwo to detect if at least one row matching a given condition exists?
I'm firing quite some of these requests. I am currently using
SELECT 1 FROM table WHERE condition LIMIT 1
looks a bit weird to me, but looks to me like "the least work" for the db, however, my SQL knowledge is spotty.
I would probably do it something like this:
SELECT
CASE
WHEN EXISTS(SELECT NULL FROM table1 WHERE ID=someid)
THEN 1
ELSE 0
END
To Count the rows is not that effective.
To check if something exists is in most cases more effective
Since it's sqlite, you need to use the column name "rowid" to access that id column. Using Craig Ringer's sql, the sqlite version would look like this:
SELECT EXISTS(SELECT 1 FROM table WHERE rowid = insert_number)
Use EXISTS, it sounds perfect for what you are after. e.g.
SELECT *
FROM T1
WHERE EXISTS (SELECT 1 FROM T2 WHERE T2.X = T1.X AND T2.Y = 1)
It is effectly the same as LIMIT 1 but is generally optimised better.
One could test
select true from table where id = id1
You can for example use
SELECT COUNT(*) FROM table WHERE ID = whatever

TSQL NOT EXISTS Why is this query so slow?

Debugging an app which queries SQL Server 05, can't change the query but need to optimise things.
Running all the selects seperately are quick <1sec, eg: select * from acscard, select id from employee... When joined together it takes 50 seconds.
Is it better to set uninteresting accesscardid fields to null or to '' when using EXISTS?
SELECT * FROM ACSCard
WHERE NOT EXISTS
( SELECT Id FROM Employee
WHERE Employee.AccessCardId = ACSCard.acs_card_number )
AND NOT EXISTS
( SELECT Id FROM Visit
WHERE Visit.AccessCardId = ACSCard.acs_card_number )
ORDER by acs_card_id
Do you have indexes on Employee.AccessCardId, Visit.AccessCardId, and ACSCard.acs_card_number?
The SELECT clause is not evaluated in an EXISTS clause. This:
WHERE EXISTS(SELECT 1/0
FROM EMPLOYEE)
...should raise an error for dividing by zero, but it won't. But you need to put something in the SELECT clause for it to be a valid query - it doesn't matter if it's NULL or a zero length string.
In SQL Server, NOT EXISTS (and NOT IN) are better than the LEFT JOIN/IS NULL approach if the columns being compared are not nullable (the values on either side can not be NULL). The columns compared should be indexed, if they aren't already.

Postgresql case and testing boolean fields

First: I'm running postgresql 8.2 and testing my queries on pgAdmin.
I have a table with some fields, say:
mytable(
id integer,
mycheck boolean,
someText varchar(200));
Now, I want a query similary to this:
select id,
case when mycheck then (select name from tableA)
else (select name from tableB) end as mySpecialName,
someText;
I tried to run and get this:
ERROR: CASE types character varying and boolean cannot be matched
SQL state: 42804
And even trying to fool postgresql with
case (mycheck::integer) when 0 then
didn't work.
So, my question is: since sql doesn't have if, only case, how I'm suppose to do an if with a boolean field?
Your problem is a mismatch in your values (expressions after then and else), not your predicate (expression after when). Make sure that select name from tableA and select name from tableB return the same result type. mycheck is supposed to be a boolean.
I ran this query on PostgreSQL 9.0beta2, and (except for having to add from mytable to the SELECT statement as well as creating tables tableA and tableB), and it didn't yield any type errors. However, I get an error message much like the one you described when I run the following:
select case when true
then 1
else 'hello'::text
end;
The above yields:
ERROR: CASE types text and integer cannot be matched
I just ran this fine on PostgreSQL 8:
select id,
case when mycheck = true then (...)
else (...),
someText;

How to select an empty result set?

Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
I'm using a stored procedure in MySQL, with a CASE statement.
In the ELSE clause of the CASE ( equivalent to default: ) I want to select and return an empty result set, thus avoiding to throw an SQL error by not handling the ELSE case, and instead return an empty result set as if a regular query would have returned no rows.
So far I've managed to do so using something like:
Select NULL From users Where False
But I have to name an existing table, like 'users' in this example.
It works, but I would prefer a way that doesn't break if eventually the table name used is renamed or dropped.
I've tried Select NULL Where False but it doesn't work.
Using Select NULL does not return an empty set, but one row with a column named NULL and with a NULL value.
There's a dummy-table in MySQL called 'dual', which you should be able to use.
select
1
from
dual
where
false
This will always give you an empty result.
This should work on most DBs, tested on Postgres and Netezza:
SELECT NULL LIMIT 0;
T-SQL (MSSQL):
SELECT Top 0 1;
How about
SELECT * FROM (SELECT 1) AS TBL WHERE 2=3
Checked in myphp, and it also works in sqlite and probably in any other db engine.
This will probably work across all databases.
SELECT * FROM (SELECT NULL AS col0) AS inner0 WHERE col0 IS NOT NULL;
SELECT TOP 0 * FROM [dbo].[TableName]
This is a reasonable approach to constant scan operator.
SELECT NULL WHERE FALSE;
it works in postgresql ,mysql, subquery in mysql.
How about this?
SELECT 'MyName' AS EmptyColumn
FROM dual
WHERE 'Me' = 'Funny'
SELECT * FROM (SELECT NULL) WHERE 0
In PostgreSQL a simple
SELECT;
works. You won't even get any columns labeled 'unknown'.
Note however, it still says 1 row retrieved.