Q:

How to save query in psql by terminal

I created a query in PSQL and run and would like to save it.
Query example:
CREATE VIEW total_revenue_per_customer AS SELECT
customers.id, customers.first_name, customers.last_name,
SUM(items.price) FROM customers                                                          
INNER JOIN purchases ON customers.id = purchases.customer_id
INNER JOIN items ON purchases.item_id = items.id
GROUP BY customers.id;

What is the commando to save my query by terminal?

A:

To start, I create an empty text file in my working directory:
filename.txt     ("remember to give permission to edit and modify")

Now, using the psql meta-command,\o we can arrange for future query results to be written to the provided filename.
\o filename.txt

Displayed above, we can see one variation of the easy syntax structure is:
\o filename.txt

creating my query and run
CREATE VIEW total_revenue_per_customer AS SELECT
customers.id, customers.first_name, customers.last_name,
SUM(items.price) FROM customers                                                          
INNER JOIN purchases ON customers.id = purchases.customer_id
INNER JOIN items ON purchases.item_id = items.id
GROUP BY customers.id;

Saved in out.txt
Since the \o meta-command is still active in the query buffer, you can clear it out, by issuing another \o meta-command, and continue on with normal activity, without writing anything else to the specified file.

