Populate column with query results in Postgresql - postgresql

Table columns structured like:
longitude, latitude, gid, Hash
-78.885636, 36.854, 1, empty
Using PostgreSQL 9.4 and trying to update column Hash with results of a geohash function:
SELECT ST_GeoHash(ST_SetSRID(ST_MakePoint(longitude::float, latitude::float), 4326))
FROM my_table;
To update the column, I am using:
UPDATE my_table SET Hash = (SELECT ST_GeoHash(ST_SetSRID(ST_MakePoint(longitude::float, latitude::float), 4326))
FROM my_table);
But I get an error:
ERROR: more than one row returned by a subquery used as an expression.
I'm new to this so I may be asking a tedious question. Any help would be appreciated. For now I'll be RTFM-ing.

To update Hash column with a calculated value you need to use this query, where gid is a primary key(probably you need to change it).
UPDATE my_table
SET Hash = my_table_2.geo_hash
FROM
(SELECT gid,
ST_GeoHash(ST_SetSRID(ST_MakePoint(longitude::float, latitude::float), 4326)) as geo_hash
FROM my_table) as my_table_2
WHERE my_table.gid = my_table_2.gid

This worked for me:
UPDATE my_table SET "Hash" = (
SELECT ST_GeoHash(ST_SetSRID(ST_MakePoint(longitude::float, latitude::float), 4326))
FROM my_table p
WHERE my_table.gid = p.gid
);

Related

Sum and average total columns in PostgreSQL

I'm using this query to find duplicate dates but not sure how to sum each duplicate dates, average it and remove duplicate dates.
DB Schema
date_time
datapoint_1
datapoint_2
SQL Query
SELECT date_time, COUNT(date_time)
FROM MYTABLE
GROUP BY date_time
HAVING COUNT(date_time) > 1
ORDER BY COUNT(date_time)
I would create a new table to replace the old one. That is easier and might even perform better:
CREATE TABLE mytable2 (LIKE mytable);
INSERT INTO mytable2 (date_time, datapoint_1, datapoint_2)
SELECT m.date_time, avg(m.datapoint_1), avg(m.datapoint_2)
FROM mytable AS m
GROUP BY m.date_time;
Then you can drop mytable and rename mytable2 to replace it.
To prevent new rows from creating duplicates, you could change the way you insert data:
-- to keep track of counts
ALTER TABLE mytable ADD numval integer DEFAULT 1;
-- to prevent duplicates
ALTER TABLE mytable ADD UNIQUE (date_time);
-- to insert new rows
INSERT INTO mytable (date_time, datapoint_1, datapoint_2)
VALUES ('2021-06-30', 42.0, -34.9)
ON CONFLICT (date_time)
DO UPDATE SET numval = mytable.numval + 1,
datapoint_1 = mytable.datapoint_1 + excluded.datapoint_1,
datapoint_2 = mytable.datapoint_2 + excluded.datapoint_2;
-- to select the averages
SELECT date_time,
datapoint_1 / numval AS datapoint_1,
datapoint_2 / numval AS datapoint_2
FROM mytable;
When you use GROUP BY you can also use aggregate functions to reduce multiple lines to a single one (COUNT, that you used is one of such functions). In your case the query would be:
SELECT date_time, avg(datapoint_1), avg(datapoint_2)
FROM MYTABLE
GROUP BY date_time
For every distinct date_time you will get a single row with the average of datapoint_1 and datapoint_2.

Using SELECT sub-query inside jsonb_array_elements_text function in Postgres

I have the following query
SELECT DISTINCT ON (user_id) user_id, timestamp
FROM entries
WHERE user_id in (1,2)
AND entry_type IN(
SELECT jsonb_array_elements_text(
SELECT entry_types
FROM users INNER JOIN orgs
ON org_id = orgs.id
WHERE users.id = 1
)
);
I'm getting a syntax error at or near select
syntax error at or near "select" LINE 1: ... entry_type in( select
jsonb_array_elements_text(select ent.
The field entry_types is a JSONB field, so I am trying to convert it to text in order to use it in the WHERE IN clause.
PostgreSQL 13.0
This sub-query within jsonb_array_elements_text
SELECT entry_types
FROM users INNER JOIN orgs
ON org_id = orgs.id
WHERE users.id = 1
Returns a single JSONB entry like this:
entry_types
--------------------------------------------
["type1", "type2", "type3"]
I'm simply trying to use the array of text values returned there as the criteria inside the WHERE IN clause.
The syntax error seems to point somewhere else, so maybe I am wrong, but the problem I see is a missing pair of parentheses around the subquery:
jsonb_array_elements_text((SELECT ...))

Calling a function on every row returned by a subquery

I need to run the following query to extract the values of my raster records in a specific point.
select st_value((select rast from mytable),
(select st_GeomFromText('POINT(30.424 -1.978)', 4326)))
But I encounter with the following error:
ERROR: more than one row returned by a subquery used as an expression
SQL state: 21000
It needs just one record for this function but I need to extract values of all of records.
If a subquery returns multiple rows, you must either use it in a common table expression (CTE / WITH query) and FROM alias, or use FROM (SELECT ...) alias. In this case, though, it looks like it's simpler than that:
select st_value(rast, st_GeomFromText('POINT(30.424 -1.978)', 4326))
FROM mytable;
Both subqueries appear to be unnecessary.
If you truly needed the subquery you'd write something syntactically like:
WITH sq(rast) AS ( SELECT rast FROM mytable )
SELECT st_value(rast, st_GeomFromText('POINT(30.424 -1.978)', 4326))
FROM sq;
or
SELECT st_value(rast, st_GeomFromText('POINT(30.424 -1.978)', 4326))
FROM (SELECT rast FROM mytable) sq(rast);
Try:
Select st_value(rast),
st_GeomFromText('POINT(30.424 -1.978)', 4326)
from mytable
If you have a function with multiple columns, you can do something like this
SELECT (info).column1, (info).column2, (info).column3
FROM (select st_value(rast, st_GeomFromText('POINT(30.424 -1.978)', 4326)) AS info
FROM mytable
) AS foo

T-SQL Update table columns using function

I have the following table:
RecordID
Name
Col1
Col2
....
ColN
The RecordID is BIGINT PRIMARY KEY CLUSTERED IDENTITY(1,1) and RecordID and Name are initialized. The other columns are NULLs.
I have a function which returns information about the other columns by Name.
To initialized my table I use the following algorithm:
Create a LOOP
Get a row, select its Name value
Execute the function using the selected name, and store its result
in temp variables
Insert the temp variables in the table
Move to the next record
Is there a way to do this without looping?
Cross apply was basically built for this
SELECT D.deptid, D.deptname, D.deptmgrid
,ST.empid, ST.empname, ST.mgrid
FROM Departments AS D
CROSS APPLY fn_getsubtree(D.deptmgrid) AS ST;
Using APPLY
UPDATE some_table
SET some_row = another_row,
some_row2 = another_row/2
FROM some_table st
CROSS APPLY
(SELECT TOP 1 another_row FROM another_table at WHERE at.shared_id=st.shared_id)
WHERE ...
using cross apply in an update statement
You can simply say the following if you already have the records in the table.
UPDATE MyTable
SET
col1 = dbo.col1Method(Name),
col2 = dbo.col2Method(Name),
...
While inserting new records, assuming RecordID is auto-generated, you can say
INSERT INTO MyTable(Name, Col1, Col2, ...)
VALUES(#Name, dbo.col1Method(#Name), dbo.col2Method(#name), ...)
where #Name contains the value for the Name column.

PostgreSQL Record Reordering using Update with a Sub-Select

I found this solution on the SQL Server forum on how to reorder records in a table.
UPDATE SomeTable
SET rankcol = SubQuery.Sort_Order
FROM
(
SELECT IDCol, Row_Number() OVER (ORDER BY ValueCOL) as SORT_ORDER
FROM SomeTable
) SubQuery
INNER JOIN SomeTable ON
SubQuery.IDCol = SomeTable.IDCol
When I try doing the same on PostgreSQL, I get an error message -
ERROR: table name "sometable" specified more than once
Any help will be appreciated.
Thanks!
You don`t need to explicitly join SomeTable, how cool is that? :)
UPDATE SomeTable
SET rankcol = SubQuery.Sort_Order
FROM
(
SELECT IDCol, Row_Number() OVER (ORDER BY ValueCOL) as SORT_ORDER
FROM SomeTable
) SubQuery
where SubQuery.IDCol = SomeTable.IDCol
remark: Postgres is case insensitive, better use lower-case, like row_number, sort_order, id_col , etc.