CASE query in postgres does not return expected output - postgresql

In my Postgres database, I am trying to execute the below query:
with
user_details as
(
SELECT username
FROM user_management WHERE username = 'admin'
)
select (case
when user_details.username is NOT NULL then 'user found'
else
'no user found' end) as username from user_details
The above query will return the username and works as expected. But if I pass the username that does not exist in the database, then I expect the CASE query to return 'no user found' but the query does not return anything at all.
But when I tried to execute the below query:
select (case
when (SELECT username
FROM user_management WHERE username = 'sadmin') is not null then 'user found'
else
'no user found' end) as username
It works as expected and returns the 'no user found'.
Why didn't I get the expected output when using the WITH query in the first case? Is there something with the WITH queries that I am missing?

When you're selecting the output from user_details , you're getting 0 rows , that is the reason you're not seeing any o/p in final result. And in the 2nd query , you're selecting the o/p from sub-query which is null then producing user not found. You might run into an error like this
ERROR: more than one row returned by a subquery used as an expression .
When there is more user having the same username. So your query should look like this
select (case
when exists(SELECT username
FROM user_management WHERE username = 'sadmin') then 'user found'
else
'no user found' end) as username

I assume that the column username is unique in the table user_management, so the CTE returns either 1 row when the username exists in the table or nothing if it does not exist.
Maybe you think that the CTE returns NULL in the case where the username does not exist in the table, but it is not.
So if the CTE returns 1 row (the username exists) then your code works fine, but if it returns nothing then your SELECT statement that selects from user_details will also return nothing, because there are no rows to select from.
Use aggregation so that you will get 1 row in the results even if the user does not exist:
SELECT COALESCE(MAX(username), 'no user found') username
FROM user_management
WHERE username = 'admin'
See the demo.

Related

Error while Parsing SQL query string PostgreSQL?

I tried to execute code below.
var sqlText = "SELECT user_id, role_id FROM app_user WHERE user_roles ?? role_id::text AND role_is_active = 'Y' AND user_id = :user_id";
queryExecute( sqlText, {user_id: { value: 24, cfsqltype: "integer" }}, {datasource : "test_db"});
Each time I tried to run the query the error message occurred.
Detail: Lesser number (1) of positional parameters are defined for sql query':' [SELECT user_id, role_id FROM app_user WHERE user_roles ?? role_id::text AND role_is_active = 'Y' AND user_id = ?]
Message: Error while Parsing SQL query string.
I tried executing the query in DBeaver and worked as expected. Then I tried eliminating the parameters in the Where clause. Once I removed the user_roles ?? role_id::text the query executed just fine. I'm wondering why query is failing to execute with this filter user_roles ?? role_id::text in it? Is there something that I have to change? Thank you.

Eloquent how to return null

I have the following query:
SELECT null as id, null as cost, null as title FROM books LIMIT 1
It returns one single record.
Using Eloquent, I've tried
$listagem = Book::where('id','=',-1)->get();// there is no id = -1
$listagem = Livro::select('NULL as id' ,'NULL as cost', 'NULL as title')->get();
(...)
but nothing works.
What is the correct sintax?
Thanks

I get error when i try to $_GET for VALUES

this is the code ia m trying to make work but apparently this is not a viable lining of code:
$sql = "INSERT INTO users (name, pass)
VALUES ('$_GET['user'], '$_GET['pword']')";
error i get:
errorError: INSERT INTO users (name, pass) VALUES ('test', '123')
Unknown column 'pass' in 'field list'
First make sure you have passed column on your users table in the database
I'd rewrite your codes as follows
$username = $_GET['user'];
$password = md5( $_GET['pword']);
$sql = "INSERT INTO users (name, pass) VALUES ($username,$password)";

group by error with postgres and pomm orm

I want to execute the following SQL query :
SELECT date, COUNT(id_customers)
FROM event
WHERE event_id = 3
GROUP BY date
When I try this query in my database, it works perfectly. But in my code I get an error which I can't resolve.
I use symfony2 with the orm pomm. It's Postgresql.
Here is my code :
$sql = "SELECT e.date, COUNT(id_customers) FROM event e WHERE event_id = $* GROUP BY e.date";
return $this->query($sql, [$eventId])->extract();
Here is the error :
request.CRITICAL: Uncaught PHP Exception InvalidArgumentException:
"No such field 'id'. Existing fields are {date, count}"
at /home/vagrant/sourcefiles/vendor/pomm-project/model-manager/sources/lib/Model/FlexibleEntity/FlexibleContainer.php line 64
{"exception":" [object] (InvalidArgumentException(code: 0): No such field 'id'.
Existing fields are {date, count}
at /home/vagrant/sourcefiles/vendor/pomm-project/model-manager/sources/lib/Model/FlexibleEntity/FlexibleContainer.php:64)"} []
So I tried to had the id in my select, by I get this error :
request.CRITICAL: Uncaught PHP Exception
PommProject\Foundation\Exception\SqlException: "
SQL error state '42803' [ERROR] ==== ERROR: column "e.id" must appear in the GROUP BY clause or be used in an aggregate function LINE 1: SELECT e.id, e.date, COUNT(id_customers) FROM event e WHERE ... ^
==== «PREPARE === SELECT e.id, e.date, COUNT(id_customers) FROM event e WHERE event_id = $1 GROUP BY e.date ===»." at /home/vagrant/sourcefiles/vendor/pomm-project/foundation/sources/lib/Session/Connection.php line 327 {"exception":"[object] (PommProject\Foundation\Exception\SqlException(code: 0): \nSQL error state '42803' [ERROR]\n====\nERROR: column \"e.id\" must appear in the GROUP BY clause or be used in an aggregate function\nLINE 1: SELECT e.id, e.date, COUNT(id_customers) FROM event e WHERE ...\n ^\n\n====\n«PREPARE ===\nSELECT e.id, e.date, COUNT(id_customers) FROM event e WHERE event_id = $1 GROUP BY e.date\n ===». at /home/vagrant/sourcefiles/vendor/pomm-project/foundation/sources/lib/Session/Connection.php:327)"} []
The only thing that works is when I had the id in the group by, but this is not the result I want.
Someone can explain me why this is working in the database and not in the php ?
this is because you are fetching flexible entities without their primary key. There is an identity mapper behind the scene that ensure fetching twice the same entity will return the same instance.
In this case, you do not need to fetch entities (hence the extract after the query). So you can just use the QueryManager pooler to return converted arrays like the following:
$sql = "SELECT e.date, COUNT(id_customers) FROM event e WHERE event_id = $* GROUP BY e.date";
// Return an iterator that fetches converted arrays on demand:
return $this
->getSession()
->getQueryManager()
->query($sql, [$eventId])
;
i think its because the alias,
try this
$sql = "SELECT e.date, COUNT(e.id_customers) FROM event e WHERE event_id = $* GROUP BY e.date";
return $this->query($sql, [$eventId])->extract();
This is exactly how GROUP BY works in PostgreSQL:
When GROUP BY is present, it is not valid for the SELECT list
expressions to refer to ungrouped columns except within aggregate
functions, since there would be more than one possible value to return
for an ungrouped column.
It means that each field in your query either must be present in GROUP BY statement or handled by any of the aggregation functions. This is one of the differences between GROUP BY in MySQL and PostreSQL.
In other words you can add id at GROUP BY statement and do not worry about it ;)

How do I look for part of a string in a field and if it exists replace it with another field?

I'm building a case in my query where if a field is either blank or has the substring 'Name Not Found' then the field in question should be replaced with the value of another field.
This is what I have so far:
CASE WHEN [Salesperson1 Name] = '' THEN [Salesperson Name (Primary)]
WHEN CONTAINS([Salesperson1 Name], 'Name Not Found') THEN [Salesperson Name (Primary)]
ELSE [Salesperson1 Name]
END,
but when I run the query I get this message:
Msg 7601, Level 16, State 2, Line 19
Cannot use a CONTAINS or FREETEXT predicate on table or indexed view 'staging_leads_rr' because it is not full-text indexed.
How could I get this done? What am I doing wrong? I'm not sure what the error message means, because I'm new to writing stuff in T-SQL.
The Contains function relates to the Full-Text search functionality of SQL Server which is more suited for large scale text processing. See reference here: https://msdn.microsoft.com/en-us/library/ms142571.aspx
In order to do this simply you should use something more like the charindex function, which returns a positive value relating to the first character position of the search string if the string is indeed found and 0 if not : https://msdn.microsoft.com/en-us/library/ms186323.aspx
Then your query would look more like this;
CASE WHEN [Salesperson1 Name] = '' THEN [Salesperson Name (Primary)]
WHEN CHARINDEX( 'Name Not Found', [Salesperson1 Name]) > 0 THEN [Salesperson Name (Primary)]
ELSE [Salesperson1 Name]
END,
You could try replacing the call to CONTAINS with the LIKE operator:
CASE WHEN [Salesperson1 Name] = ''
THEN [Salesperson Name (Primary)]
WHEN [Salesperson1 Name] LIKE '%Name Not Found%'
THEN [Salesperson Name (Primary)]
ELSE [Salesperson1 Name]
END
If you really want to use CONTAINS then you will have to create a full text index on the [Salesperson1 Name] column, q.v. this helpful SO post.