I have a query like this -
select unnest(string_to_array(news_article.news_category_id, ',')):: int rowz
from news_article) where rowz=1;
this query is not working because of putting rowz=1 in the query ? How to do it if I want only that result where rowz= 1 after unnest.
When i do this -
select unnest(string_to_array(na.news_category_id, ','))::int rowz from news_article;
My table is -
Create table news_article(
id bigserial NOT NULL PRIMARY KEY,
news_headline character varying(70) NOT NULL,
news_content_src character varying(240) NOT NULL,
news_language_id integer NOT NULL,
news_category_id character varying(50) NOT NULL,
news_publisher_id integer NOT NULL references news_publishers(pub_id),
news_date timestamp WITH TIME ZONE Default now()
);
Then it gives me this result -
rowz
1
2
1
3
2
To convert an ARRAY into a set of rows, also known as "flattening," use the UNNEST operator. UNNEST takes an ARRAY and returns a table with a single row for each element in the ARRAY . Because UNNEST destroys the order of the ARRAY elements, you may wish to restore order to the table.
We can pass an array with the help of where IN clause.
The UNNEST function returns a result table that includes a row for each element of the specified array. If there are multiple ordinary array arguments specified, the number of rows will match the array with the largest cardinality.
You should use the WHERE clause to filter the records and fetching only the necessary records. The WHERE clause is not only used in the SELECT statement, but it is also used in the UPDATE, DELETE statement, etc., which we would examine in the subsequent chapters.
This answers your question:
SELECT * FROM
(SELECT unnest(string_to_array(news_article.news_category_id, ',')):: int rowz
FROM news_article) AS categories
WHERE rowz = 1;
The trick is that you unnest
the array into a set of records which you then use as a sub-query.
The result, however, looks silly. Do you perhaps want all details of news articles which have a news_category_id = 1
, possibly among other categories? In that case:
SELECT a.*
FROM news_article a
JOIN (SELECT id, unnest(string_to_array(news_article.news_category_id, ',')):: int rowz
FROM news_article) AS c ON c.id = a.id
WHERE c.rowz = 1;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With