Concatenating strings in PostgreSQL result - sql

I have an SQL query like this:
SELECT DISTINCT(id) FROM users WHERE ...
and I would like to display the results like that:
user=12355
user=78949
user=9898
user=489891
Basically with "user=" prepended. Is it possible to do this with PostgreSQL? I've tried with STRING_AGG('user=', DISTINCT(id)) but got an error on DISTINCT(id). Any idea?

I'd use a plain GROUP BY for this.
SELECT format('user=%s',id)
FROM users
GROUP BY id;
http://sqlfiddle.com/#!1/39727/3
This will be considerably more efficient than using DISTINCT on the string concatenation.

You should be able to use || for string concatenation:
SELECT DISTINCT('user=' || id)
FROM users
WHERE ...
SQL Fiddle Demo
This might be useful as well:
http://www.postgresql.org/docs/current/static/functions-string.html

The only reason you got an error message from string_agg() is because you forgot the second parameter which is required. This very simple query would just work:
SELECT string_agg('user=' || id, E'\n')
FROM users
WHERE ...
E'\n' .. newline character
Produces one row with the exactly the string you have in your question.
You do not need either DISTINCT or GROUP BY unless you have duplicates in id - in which case you'd need a subquery:
SELECT string_agg('user=' || id, E'\n')
FROM (SELECT id FROM users GROUP BY id) x

Simply
Select concat('user=',id) from users

Related

Snowflake LISTAGG Encapsulate Values

I was wondering if anyone has solved being able to encapsulate values in the LISTAGG function for Snowflake.
I have a table that looks something like this
ID
NAME
1
PC
1
PC,A
2
ER
The following query:
SELECT
ID,
LISTAGG(DISTINCT NAME, ',') AS LIST
FROM TEST_TABLE
will return this table
ID
LIST
1
PC,PC,A
2
ER
My expected result would be:
ID
LIST
1
PC,"PC,A"
2
ER
Does anyone know how to get the expected result?
I thought about testing if the value had a comma and then a CASE WHEN to switch the logic based on that.
We can aggregate using a CASE expression which detects commas, in which case it wraps the value in double quotes.
SELECT
ID,
LISTAGG(DISTINCT CASE WHEN NAME LIKE '%,%'
THEN CONCAT('"', NAME, '"')
ELSE NAME END, ',') AS LIST
FROM TEST_TABLE;
If I had to use listagg, I would have picked a different delimiter, like so..
select listagg(distinct name,'|')
from t;
Personally, I find array_agg easier to work with in cases like yours
select array_agg(distinct name)
from t;

How to use a multi-element string for a IN sql query?

Is it possible to use the input from one field of the database for another query in combination with the IN statement. The point is that in the sting, I use for IN, contains several by comma separated values:
SELECT id, name
FROM refPlant
WHERE id IN (SELECT cover
FROM meta_characteristic
WHERE id = 2);
the string of the subquery is: 1735,1736,1737,1738,1739,1740,1741,1742,1743,1744
The query above give me only the first element of the string. But when I put the string directly in the query, I get all the ten elements:
SELECT id, name
FROM refPlant
WHERE id IN (735,1736,1737,1738,1739,1740,1741,1742,1743,1744);
Is it possible to have all ten elements and not only one with query like the first one.
My sql version is 10.1.16-MariaDB
You can use FIND_IN_SET in the join condition.
SELECT r.id, r.name
FROM refPlant r
JOIN (SELECT * FROM meta_characteristic m WHERE id=2) m
ON FIND_IN_SET(r.id,m.cover) > 0
If you use a sub-query as in the first code snippet you will get a filter for each row returned from it. It will not work when it returns as a single string field.
SELECT id, name
FROM refPlant
WHERE FIND_IN_SET(id, (SELECT cover
FROM meta_charateristic
WHERE id = 2));

How to use multiple values with like in sql

select * from user_table where name in ('123%','test%','dummy%')
How to ensure that this where clause is not an exact match, but a like condition?
In Oracle you can use regexp_like as follows:
select *
from user_table
where regexp_like (name, '^(123|test|dummy)')
The caret (^) requires that the match is at the start of name, and the pipe | acts as an OR.
Be careful though, because with regular expressions you almost certainly lose the benefit of an index that might exist on name.
Use like this,
select *
from user_table
where name LIKE '123%'
OR name LIKE 'test%'
OR name Like 'dummy%';
another option in MySQL
select * from user_table where name REGEXP '^123|^test|^dummy';
To not lose indexed access to rows in Oracle a table collection expression can be used:
SELECT
*
FROM
user_table
JOIN (SELECT column_value filter
FROM table(sys.odcivarchar2list('dummy%', '123%', 'test%'))
) ON user_table.name LIKE filter
The filter expressions must be distinct otherwise you get the same rows from user_table multiple times.

How to properly use LIKE statement in sql query

I have database which contains a field named groupid and group name.
sample data
groupid groupname
123 abc
234 bcr
1237 cde
I like to compare groupid with another inputted data, its size is greater than size of group id.
I tried a query that not return correct answer
SELECT *
FROM mydata
WHERE groupid LIKE '12309098';
My expected answer is abc
What are the changes to made for correct answer
thanks in advance
Since you want the value in the row to be the prefix of your input and not the other way around, you can just turn LIKE around the other way;
SELECT *
FROM mydata
WHERE '12309098' LIKE CONCAT(groupid, '%');
An SQLfiddle to test with;
EDIT: Since you asked about SQLite, there you need to use || for concatenation;
SELECT *
FROM mydata
WHERE '12309098' LIKE `groupid` || '%';
Another SQLfiddle.
You could do like below:
SELECT *
FROM my data
WHERE '12309098' LIKE CONCAT('%', groupid, '%');
You could use something like this. But it is highly subjective to your SQL Server. For Oracle following syntax should be fine
SELECT *
FROM mydata
WHERE groupid LIKE SUBSTR('12309098',1, LENGTH(groupid));
If you are sure that input data will start with 123, then:
SELECT * FROM mydata WHERE groupid LIKE '123%';
If you are sure that input data will contain 123, then:
SELECT * FROM mydata WHERE groupid LIKE '%123%';

How to give the output of the first query(which has two values) as the input to the second?

i get 2 names as the output of the first query....
eg: paul,peter
now this should be the input for the second query,
which has to display paul's and peter's email ids....
For nested queries I would strongly recommend WITH clause. It makes long complex queries order of magnitude easier to understand / construct / modify:
WITH
w_users AS( -- you can name it whatever you want
SELECT id
FROM users
WHERE < long condition here >
),
w_other_subquery AS(
...
)
SELECT email_id
FROM ...
WHERE user_id IN (SELECT id FROM w_users)
You can use like this
LIKE
SELECT USER_ID,EMAIL_ID FROM USERS where user_id IN
(SELECT PRODUCT_MEMBERS FROM PRODUCT WHERE PRODUCT_NAME='ICP/RAA');
Just use the IN clause '=' is used for matching one result
You can use In Command to get result
ex:
SELECT email FROM tableName WHERE (Name IN ('paul', 'peter'))