Received: from malur.postgresql.org ([217.196.149.56]) by arkaria.postgresql.org with esmtps (TLS1.3) tls TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 (Exim 4.94.2) (envelope-from ) id 1vFyG3-004lYk-BA for pgsql-general@arkaria.postgresql.org; Mon, 03 Nov 2025 17:22:19 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.94.2) (envelope-from ) id 1vFyG2-006el5-9G for pgsql-general@arkaria.postgresql.org; Mon, 03 Nov 2025 17:22:17 +0000 Received: from makus.postgresql.org ([2001:4800:3e1:1::229]) by malur.postgresql.org with esmtps (TLS1.3) tls TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 (Exim 4.94.2) (envelope-from ) id 1vFyG1-006ekx-VK for pgsql-general@lists.postgresql.org; Mon, 03 Nov 2025 17:22:16 +0000 Received: from lana.depesz.com ([88.198.49.178] helo=depesz.com) by makus.postgresql.org with esmtps (TLS1.3) tls TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 (Exim 4.96) (envelope-from ) id 1vFyFy-005FfI-2Y for pgsql-general@lists.postgresql.org; Mon, 03 Nov 2025 17:22:16 +0000 DKIM-Signature: v=1; a=rsa-sha256; q=dns/txt; c=relaxed/relaxed; d=depesz.com; s=20170201; h=In-Reply-To:Content-Type:MIME-Version:References:Reply-To: Message-ID:Subject:Cc:To:Sender:From:Date:Content-Transfer-Encoding: Content-ID:Content-Description; bh=OT0SyufRHFASHLzY9roGaIqa0AoSXGxVBtlYfPkqp5Q=; b=bVACfozy0bVpO7ROVMf8xunlum kMBqsQoR4gh8JNM1yzjliwAqy1ok+lwkeFFIoxrS667yh0TL5SiRlJstmL2p1EOPV0ZeXSvh5wHO/ Vv+e9HEsMUBfGBYkDbIwvp2D5V4OdkcjqcPI8kohQ0t9pzAahOou3HSc4/8QpXNhDjI0=; Received: from depesz by depesz.com with local (Exim 4.96) (envelope-from ) id 1vFyFv-008eAe-2S; Mon, 03 Nov 2025 18:22:11 +0100 Date: Mon, 3 Nov 2025 18:22:11 +0100 From: hubert depesz lubaczewski Sender: depesz@depesz.com To: dfgpostgres Cc: pgsql-general@lists.postgresql.org Subject: Re: PG Unpivot ? Message-ID: Reply-To: depesz@depesz.com References: MIME-Version: 1.0 Content-Type: text/plain; charset=utf-8 Content-Disposition: inline In-Reply-To: List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Archived-At: Precedence: bulk On Mon, Nov 03, 2025 at 12:18:55PM -0500, dfgpostgres wrote: > psql (13.2, server 15.3) on linux > > I think they call this "unpivot" in MSSQL ? > > How can I get an sql query to return one line per column with... an ID, > column name and value. the ctid for the id field is fine. > > Example: > dvdb=# create table unpivot (intcol integer, floatcol float, strcol > varchar); > CREATE TABLE > dvdb=# insert into unpivot (intcol,floatcol,strcol) values > (1,1.1,'one'),(2,2.2,'two'),(3,3.3,'three'); > INSERT 0 3 > dvdb=# select * from unpivot; > intcol | floatcol | strcol > --------+----------+-------- > 1 | 1.1 | one > 2 | 2.2 | two > 3 | 3.3 | three > (3 rows) > I want 9 records returned, each row with 3 cols, 1st col is the ctid, > second is the column name, third is the val. I think it should work: select u.ctid, e.* from unpivot u, to_jsonb(u) j, jsonb_each_text(j) e; Best regards, depesz