PostgreSQL UNNEST Array and Insert Into New Table - postgresql

I have an array column I want to unnest, split the element values, and copy into another table. For example:
id | col1
-----------------
1 | '{"a:1", "b:2"}'
I'd like to insert into a new table that looks like:
table1_id | col1 | col2
------------------------
1 | 'a' | 1
1 | 'b' | 2

You can issue an insert from this select:
select id as table1_id,
(string_to_array(ary, ':'))[1] as col1,
(string_to_array(ary, ':'))[2] as col2
from table1
cross join lateral unnest(col1) as u(ary);
db<>fiddle here

Related

Creating a partial index based on declared variables inside a DO block

I have a table on which I want to have two different partial unique indexes that include unique constraints on different columns, based on a the value of another column in the table (which is a foreign key). Here's an example:
id | col1 | col2 | col3 | col4
------------------------------
1 | 3 | 4 | 'a' | 13
2 | 2 | 2 | 'b' | 431
3 | 3 | 4 | 'b' | 18
4 | 10 | 8 | 'b' | 211
Let's say in this table I want:
to put a partial index on all the rows where col4=13 OR col4=18 with a unique constraint on col1, col2, and col3
to put a partial index on all the rows where col4<>13 AND col4<>18 with a unique constraint on col1 and col2
The problem is that I want to do this based on the value of a column in another table since col4 is a foreign key. This SO post asks a similar question but there isn't really a solution. Here is what I've done with pl/pgsql:
DO
$$
DECLARE
-- typical subquery
option1_id INTEGER := (SELECT id FROM option_table WHERE name = 'option1');
option2_id INTEGER := (SELECT id FROM option_table WHERE name = 'option2');
BEGIN
RAISE INFO '%, %', option1_id, option2_id;
-- option1
CREATE UNIQUE INDEX option1_index ON ex_table (col1, col2) WHERE (
col4 NOT IN (option1_id, option1_id)
);
-- option2
CREATE UNIQUE INDEX option2_index ON ex_table (col1, col2, col3) WHERE (
reference_type IN (option1_id, option2_id)
);
-- this works!
CREATE UNIQUE INDEX this_works ON ex_table (col1, col2, col3) WHERE (
reference_type IN (13, 18)
);
END
$$;
Here is the error that I'm getting:
ERROR: column "option1_id" does not exist
I know the variables are properly declared because the RAISE INFO is returning INFO: 13, 18
DDL statements doesn't support parametrization - you cannot to use any variables there. You should to use dynamic SQL (in this case without clause USING):
EXECUTE format('CREATE UNIQUE INDEX ... WHERE reference_type IN (%L, %L)', option1_id, option2_id);

PostgreSQL mass insert into a table?

I need to mass insert all the values from col_a into another table. I can do it one at a time like this:
INSERT INTO table_2 (col_a_id)
SELECT 'col_a_id'
FROM table_1
WHERE col_a = 'x';
But is there a way I can just insert all the columns?
EDIT
Lets say I have this table:
Col_a | Col_b |
------------------------
1 | a |
2 | b |
3 | c |
Instead of checking what is in col_a can I just insert each instance of col_a into a table? so I'll have 1, 2 & 3 in table_2?
INSERT INTO table_2 (col1, col2, col3, .... , coln)
SELECT col1, col2, col3, .... , coln
FROM table_1
WHERE col_a = 'x';
Note: String are separated by single quote
SELECT 'this is a string'
Fieldname use double quote:
SELECT "myFieldName", "col1"
EDIT:
If you want check all columns for 'x'
WHERE 'x' IN (col1, col2, col3, .... , coln)

How do we get all columns which are the part of sortkey in Redshift

I need to get all columns, which are the part of sortkey in Redshift.
I tried get information using "select * from svv_table_info" but it have only the information of one column only. Can you let me know, how do I get all columns which are the part of Sortkey for a table.
Thanks,
Sanjeev
Thanks all for your help. I already tried "pg_table_def" table to get sortkey and distkey information but I have seen only pg_catalog and Public schema, I just go through the Amazon developer guide and found we need to add schema to search path using below commands:-
show search_path;
set search_path to '$user', 'public', 'NewSchema';
After adding the "NewSchema" in search path I can see sortkey and distkey information for this schema in pg_table_def
Thanks,
Sanjeev
Sanjeev,
A table called pg_table_def has information about the columns.
In the example below, I created a simple table with four columns and used 2 of these columns as my sort key.
As you can see in my query results the "sort key" field shows a number other than 0 if the column is part of a sort key.
dev=# drop table tb1;
DROP TABLE
dev=# create table tb1 (col1 integer, col2 integer, col3 integer, col4 integer) distkey(col1) sortkey(col2, col4);
CREATE TABLE
dev=# select * from pg_table_def where tablename = 'tb1';
schemaname | tablename | column | type | encoding | distkey | sortkey | notnull
------------+-----------+--------+---------+----------+---------+---------+---------
public | tb1 | col1 | integer | none | t | 0 | f
public | tb1 | col2 | integer | none | f | 1 | f
public | tb1 | col3 | integer | none | f | 0 | f
public | tb1 | col4 | integer | none | f | 2 | f
(4 rows)
What about:
select "column", type, encoding, distkey, sortkey, "notnull"
from pg_table_def
where tablename = 'YOURTABLE'
and sortkey <> 0;

T-SQL One column in multiple columns select query

I have a simple problem that I have not been able to find a solution to and I'm hoping someone on StackOverflow can help.
I currently have an example query as shown below
SELECT ID
, ColumnName
FROM Table
If I run this query I get the following result:
==================
ID | ColumnName
------------------
1 | One_Two_Three
2 | Four_Five_Six
==================
The result I'm after is as follows:
========================
ID | Col1 | Col2 | Col3
------------------------
1 | One | Two | Three
2 | Four | Five | Six
========================
Your assistence is appreciated.
Have a look at this example
DECLARE #Table1 TABLE
([ID] int, [ColumnName] varchar(13))
INSERT INTO #Table1
([ID], [ColumnName])
VALUES
(1, 'One_Two_Three'),
(2, 'Four_Five_Six')
;WITH Vals AS (
SELECT *,
CAST('<d>' + REPLACE([ColumnName], '_', '</d><d>') + '</d>' AS XML) ColumnValue
FROM #Table1
)
SELECT v.*,
A.B.value('.', 'varchar(max)')
FROM Vals v CROSS APPLY
ColumnValue.nodes('/d') A(B)
SQL Fiddle DEMO

How get file name from full path in select?

I have a table A as:
Col1 Col2
1 D:\Akagane2\Source\SubModule\ExtractText.vb
2 D:\Akagane2\Source\SubModule\ExtractText.vb
I want select output a table has data as
Col1 Col2
1 ExtractText.vb
2 ExtractText.vb
Select in postgresql,
Can you help me ?
Something like
SELECT RIGHT('D:\Akagane2\Source\SubModule\ExtractText.vb', POSITION('\' in REVERSE('D:\Akagane2\Source\SubModule\ExtractText.vb')) -1 );
On PostgreSQL.
mole=> CREATE TABLE A (Col1 INTEGER, Col2 VARCHAR);
CREATE TABLE
mole=> INSERT INTO A VALUES (1, 'D:\Akagane2\Source\SubModule\ExtractText.vb');
INSERT 0 1
mole=> INSERT INTO A VALUES (2, 'D:\Akagane2\Source\SubModule\ExtractText.vb');
INSERT 0 1
mole=> SELECT * FROM A;
col1 | col2
------+---------------------------------------------
1 | D:\Akagane2\Source\SubModule\ExtractText.vb
2 | D:\Akagane2\Source\SubModule\ExtractText.vb
(2 rows)
mole=> SELECT Col1, REGEXP_REPLACE(Col2, '.*\\', '') AS col2 FROM A;
col1 | col2
------+----------------
1 | ExtractText.vb
2 | ExtractText.vb
(2 rows)