mirror of
https://github.com/jbranchaud/til
synced 2026-01-05 08:08:02 +00:00
Add Write A Query Result To File as a postgres til
This commit is contained in:
@@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/).
|
|||||||
For a steady stream of TILs from a variety of rocketeers, checkout
|
For a steady stream of TILs from a variety of rocketeers, checkout
|
||||||
[til.hashrocket.com](https://til.hashrocket.com/).
|
[til.hashrocket.com](https://til.hashrocket.com/).
|
||||||
|
|
||||||
_527 TILs and counting..._
|
_528 TILs and counting..._
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -329,6 +329,7 @@ _527 TILs and counting..._
|
|||||||
- [Using Intervals To Offset Time](postgres/using-intervals-to-offset-time.md)
|
- [Using Intervals To Offset Time](postgres/using-intervals-to-offset-time.md)
|
||||||
- [Who Is The Current User](postgres/who-is-the-current-user.md)
|
- [Who Is The Current User](postgres/who-is-the-current-user.md)
|
||||||
- [Word Count for a Column](postgres/word-count-for-a-column.md)
|
- [Word Count for a Column](postgres/word-count-for-a-column.md)
|
||||||
|
- [Write A Query Result To File](postgres/write-a-query-result-to-file.md)
|
||||||
|
|
||||||
### Rails
|
### Rails
|
||||||
|
|
||||||
|
|||||||
29
postgres/write-a-query-result-to-file.md
Normal file
29
postgres/write-a-query-result-to-file.md
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
# Write A Query Result To File
|
||||||
|
|
||||||
|
Generally when writing a query in `psql` a statement will be terminated with
|
||||||
|
a semicolon. An alternative approach is to end it with a `\g` instead. This
|
||||||
|
will also send the query to the Postgres server for execution.
|
||||||
|
|
||||||
|
```sql
|
||||||
|
select 1 \g
|
||||||
|
```
|
||||||
|
|
||||||
|
If a filename is included after the `\g`, then the result of the query will
|
||||||
|
be written to that file instead of output to the `psql` session.
|
||||||
|
|
||||||
|
```sql
|
||||||
|
> select 1, 2, 3 \g query_result.txt
|
||||||
|
```
|
||||||
|
|
||||||
|
If we `cat` that file, we can see the query result.
|
||||||
|
|
||||||
|
```sql
|
||||||
|
Time: 4.293 ms
|
||||||
|
> \! cat query_result.txt
|
||||||
|
?column? | ?column? | ?column?
|
||||||
|
----------+----------+----------
|
||||||
|
1 | 2 | 3
|
||||||
|
(1 row)
|
||||||
|
```
|
||||||
|
|
||||||
|
See `man psql` for more details.
|
||||||
Reference in New Issue
Block a user