👓

SQLiteで吐き出したテーブルの末尾に任意の値のレコードを追加する

2021/12/26に公開

データベースに手を加えることなく、SQLiteで吐き出したテーブルの末尾に任意の値を持ったレコードを追加して出力するためのTips。

3秒で説明

出力したいテーブルと同じ形式のテーブルをSELECT文で作って、UNION ALLで接続する。

具体的な例

a) DBから出力したテーブル(テーブル名ex

SELECT * FROM ex
id name email
1 foo foo@example.com
2 bar bar@example.com
3 baz baz@example.com

b) DBに存在しない任意のレコード(追記したいもの)

SELECT  "99" AS "id",
	"test" AS "name",
	"test@example.com" AS "email"
id name email
99 test test@example.com

a) に b) を追加して出力

SELECT * FROM ex
UNION ALL
SELECT  "99" AS "id",
	"test" AS "name",
	"test@example.com" AS "email"
id name email
1 foo foo@example.com
2 bar bar@example.com
3 baz baz@example.com
99 test test@example.com

できると何が嬉しいの?

DMに変更を施さず、クエリのみで任意のデータが追加されたテーブルを吐き出せる。

例えば、Redashなどでメール配信のためにメールアドレスを抽出するとき、Excelで手作業で毎回末尾にテスト用に自分のアドレスを追記したりしている場合、クエリでの出力時点でそれが追記されたデータが吐き出されるので工数を減らすことができる。

参考:もっと追加したい時

面倒だけど1レコードづつUNION ALLでくっつける。

SELECT * FROM ex
UNION ALL
SELECT  "991" AS "id",
	"test1" AS "name",
	"test2@example.com" AS "email"
SELECT  "992" AS "id",
	"test2" AS "name",
	"test2@example.com" AS "email"
id name email
1 foo foo@example.com
2 bar bar@example.com
3 baz baz@example.com
99 test1 test1@example.com
99 test2 test2@example.com

Discussion