-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpostgresql.html
1034 lines (931 loc) · 31.4 KB
/
postgresql.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="generator" content="pandoc" />
<meta http-equiv="X-UA-Compatible" content="IE=EDGE" />
<title>PostgreSQL Commands</title>
<script src="site_libs/header-attrs-2.28/header-attrs.js"></script>
<script src="site_libs/jquery-3.6.0/jquery-3.6.0.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link href="site_libs/bootstrap-3.3.5/css/bootstrap.min.css" rel="stylesheet" />
<script src="site_libs/bootstrap-3.3.5/js/bootstrap.min.js"></script>
<script src="site_libs/bootstrap-3.3.5/shim/html5shiv.min.js"></script>
<script src="site_libs/bootstrap-3.3.5/shim/respond.min.js"></script>
<style>h1 {font-size: 34px;}
h1.title {font-size: 38px;}
h2 {font-size: 30px;}
h3 {font-size: 24px;}
h4 {font-size: 18px;}
h5 {font-size: 16px;}
h6 {font-size: 12px;}
code {color: inherit; background-color: rgba(0, 0, 0, 0.04);}
pre:not([class]) { background-color: white }</style>
<script src="site_libs/jqueryui-1.13.2/jquery-ui.min.js"></script>
<link href="site_libs/tocify-1.9.1/jquery.tocify.css" rel="stylesheet" />
<script src="site_libs/tocify-1.9.1/jquery.tocify.js"></script>
<script src="site_libs/navigation-1.1/tabsets.js"></script>
<link href="site_libs/highlightjs-9.12.0/default.css" rel="stylesheet" />
<script src="site_libs/highlightjs-9.12.0/highlight.js"></script>
<link href="site_libs/font-awesome-6.4.2/css/all.min.css" rel="stylesheet" />
<link href="site_libs/font-awesome-6.4.2/css/v4-shims.min.css" rel="stylesheet" />
<style type="text/css">
code{white-space: pre-wrap;}
span.smallcaps{font-variant: small-caps;}
span.underline{text-decoration: underline;}
div.column{display: inline-block; vertical-align: top; width: 50%;}
div.hanging-indent{margin-left: 1.5em; text-indent: -1.5em;}
ul.task-list{list-style: none;}
</style>
<style type="text/css">code{white-space: pre;}</style>
<script type="text/javascript">
if (window.hljs) {
hljs.configure({languages: []});
hljs.initHighlightingOnLoad();
if (document.readyState && document.readyState === "complete") {
window.setTimeout(function() { hljs.initHighlighting(); }, 0);
}
}
</script>
<link rel="stylesheet" href="styles.css" type="text/css" />
<style type = "text/css">
.main-container {
max-width: 940px;
margin-left: auto;
margin-right: auto;
}
img {
max-width:100%;
}
.tabbed-pane {
padding-top: 12px;
}
.html-widget {
margin-bottom: 20px;
}
button.code-folding-btn:focus {
outline: none;
}
summary {
display: list-item;
}
details > summary > p:only-child {
display: inline;
}
pre code {
padding: 0;
}
</style>
<style type="text/css">
.dropdown-submenu {
position: relative;
}
.dropdown-submenu>.dropdown-menu {
top: 0;
left: 100%;
margin-top: -6px;
margin-left: -1px;
border-radius: 0 6px 6px 6px;
}
.dropdown-submenu:hover>.dropdown-menu {
display: block;
}
.dropdown-submenu>a:after {
display: block;
content: " ";
float: right;
width: 0;
height: 0;
border-color: transparent;
border-style: solid;
border-width: 5px 0 5px 5px;
border-left-color: #cccccc;
margin-top: 5px;
margin-right: -10px;
}
.dropdown-submenu:hover>a:after {
border-left-color: #adb5bd;
}
.dropdown-submenu.pull-left {
float: none;
}
.dropdown-submenu.pull-left>.dropdown-menu {
left: -100%;
margin-left: 10px;
border-radius: 6px 0 6px 6px;
}
</style>
<script type="text/javascript">
// manage active state of menu based on current page
$(document).ready(function () {
// active menu anchor
href = window.location.pathname
href = href.substr(href.lastIndexOf('/') + 1)
if (href === "")
href = "index.html";
var menuAnchor = $('a[href="' + href + '"]');
// mark the anchor link active (and if it's in a dropdown, also mark that active)
var dropdown = menuAnchor.closest('li.dropdown');
if (window.bootstrap) { // Bootstrap 4+
menuAnchor.addClass('active');
dropdown.find('> .dropdown-toggle').addClass('active');
} else { // Bootstrap 3
menuAnchor.parent().addClass('active');
dropdown.addClass('active');
}
// Navbar adjustments
var navHeight = $(".navbar").first().height() + 15;
var style = document.createElement('style');
var pt = "padding-top: " + navHeight + "px; ";
var mt = "margin-top: -" + navHeight + "px; ";
var css = "";
// offset scroll position for anchor links (for fixed navbar)
for (var i = 1; i <= 6; i++) {
css += ".section h" + i + "{ " + pt + mt + "}\n";
}
style.innerHTML = "body {" + pt + "padding-bottom: 40px; }\n" + css;
document.head.appendChild(style);
});
</script>
<!-- tabsets -->
<style type="text/css">
.tabset-dropdown > .nav-tabs {
display: inline-table;
max-height: 500px;
min-height: 44px;
overflow-y: auto;
border: 1px solid #ddd;
border-radius: 4px;
}
.tabset-dropdown > .nav-tabs > li.active:before, .tabset-dropdown > .nav-tabs.nav-tabs-open:before {
content: "\e259";
font-family: 'Glyphicons Halflings';
display: inline-block;
padding: 10px;
border-right: 1px solid #ddd;
}
.tabset-dropdown > .nav-tabs.nav-tabs-open > li.active:before {
content: "\e258";
font-family: 'Glyphicons Halflings';
border: none;
}
.tabset-dropdown > .nav-tabs > li.active {
display: block;
}
.tabset-dropdown > .nav-tabs > li > a,
.tabset-dropdown > .nav-tabs > li > a:focus,
.tabset-dropdown > .nav-tabs > li > a:hover {
border: none;
display: inline-block;
border-radius: 4px;
background-color: transparent;
}
.tabset-dropdown > .nav-tabs.nav-tabs-open > li {
display: block;
float: none;
}
.tabset-dropdown > .nav-tabs > li {
display: none;
}
</style>
<!-- code folding -->
<style type="text/css">
#TOC {
margin: 25px 0px 20px 0px;
}
@media (max-width: 768px) {
#TOC {
position: relative;
width: 100%;
}
}
@media print {
.toc-content {
/* see https://github.com/w3c/csswg-drafts/issues/4434 */
float: right;
}
}
.toc-content {
padding-left: 30px;
padding-right: 40px;
}
div.main-container {
max-width: 1200px;
}
div.tocify {
width: 20%;
max-width: 260px;
max-height: 85%;
}
@media (min-width: 768px) and (max-width: 991px) {
div.tocify {
width: 25%;
}
}
@media (max-width: 767px) {
div.tocify {
width: 100%;
max-width: none;
}
}
.tocify ul, .tocify li {
line-height: 20px;
}
.tocify-subheader .tocify-item {
font-size: 0.90em;
}
.tocify .list-group-item {
border-radius: 0px;
}
</style>
</head>
<body>
<div class="container-fluid main-container">
<!-- setup 3col/9col grid for toc_float and main content -->
<div class="row">
<div class="col-xs-12 col-sm-4 col-md-3">
<div id="TOC" class="tocify">
</div>
</div>
<div class="toc-content col-xs-12 col-sm-8 col-md-9">
<div class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-bs-toggle="collapse" data-target="#navbar" data-bs-target="#navbar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="index.html">Paul Rougieux</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>
<a href="index.html">
<span class="fa fa-home"></span>
Home
</a>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
<span class="fa fa-wrench"></span>
Tools
<span class="caret"></span>
</a>
<ul class="dropdown-menu" role="menu">
<li>
<a href="bash.html">Bash</a>
</li>
<li>
<a href="communication.html">Communication</a>
</li>
<li>
<a href="debian.html">Debian</a>
</li>
<li>
<a href="docker.html">Docker</a>
</li>
<li>
<a href="git.html">Git</a>
</li>
<li>
<a href="latex_and_lyx.html">Latex and Lyx</a>
</li>
<li>
<a href="markdown.html">Markdown</a>
</li>
<li>
<a href="mysql.html">MySQL</a>
</li>
<li>
<a href="postgresql.html">PostgreSQL</a>
</li>
<li>
<a href="publish.html">Publish</a>
</li>
<li>
<a href="python.html">Python</a>
</li>
<li>
<a href="R.html">R</a>
</li>
<li>
<a href="vim.html">Vim</a>
</li>
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
<span class="fa fa-microchip"></span>
Algos
<span class="caret"></span>
</a>
<ul class="dropdown-menu" role="menu">
<li>
<a href="carbon_budget_model.html">Carbon Budget Model</a>
</li>
<li>
<a href="musical_scales.html">Musical scales</a>
</li>
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
<span class="fa fa-line-chart"></span>
Data
<span class="caret"></span>
</a>
<ul class="dropdown-menu" role="menu">
<li>
<a href="explore.html">Explore</a>
</li>
<li>
<a href="datasources.html">Sources</a>
</li>
</ul>
</li>
<li>
<a href="events.html">
<span class="fa fa-users"></span>
Events
</a>
</li>
<li>
<a href="publications.html">
<span class="fa fa-book"></span>
Publications
</a>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
</ul>
</div><!--/.nav-collapse -->
</div><!--/.container -->
</div><!--/.navbar -->
<div id="header">
<h1 class="title toc-ignore">PostgreSQL Commands</h1>
</div>
<p>This document explains the installation and configuration of the
PostgreSQL database engine.</p>
<div id="install-postgresql" class="section level1">
<h1>Install PostgreSQL</h1>
<p>Install PostgreSQL</p>
<pre><code>sudo apt install postgresql postgresql-client</code></pre>
<p>Debian wiki explains <a href="https://wiki.debian.org/PostgreSql">how
to install and set up PostgreSQL</a>.</p>
<div id="change-the-listening-port" class="section level2">
<h2>Change the listening port</h2>
<p>In case you need to change the listening port (for example when I had
to test postgresql on docker containers while keeping postgresql running
locally) Edit the configuration file
<code>/etc/postgresql/13/main/postgresql.conf</code> and change the port
definition as follows</p>
<pre><code>port = 5433</code></pre>
</div>
</div>
<div id="start-and-stop-the-server" class="section level1">
<h1>Start and stop the server</h1>
<pre><code>sudo service postgresql start
sudo service postgresql stop</code></pre>
</div>
<div id="create-a-user-and-a-database" class="section level1">
<h1>Create a user and a database</h1>
<p>Add system users at the regular bash shell before you can add them in
postgresql. I call this user “rdb” because I plan to use R to connect to
the database and “R” cannot be used as a user name according to system
policy.</p>
<pre><code>sudo adduser rdb --disabled-password </code></pre>
<p><strong>Login as the postgres user!</strong></p>
<pre><code>sudo -i -u postgres
# In case postgresql is not on the default port 5432
export PGPORT=5433</code></pre>
<p>Now logged in as <code>postgres@machine_name</code> in the regular
bash shell:</p>
<ol style="list-style-type: decimal">
<li><p>Create a user with the same name as the system user created
above</p>
<p>createuser –pwprompt rdb # Create a user for myself createuser
paul</p></li>
</ol>
<p>See also <code>~/.pgpass</code> to store the password.</p>
<ol start="2" style="list-style-type: decimal">
<li><p>Create a database owned by that user</p>
<p>createdb -O rdb tradeflows createdb -O rdb biotrade createdb -O paul
tradeflows_migrated</p></li>
</ol>
<p>Note: createdb is a wrapper around the SQL command
<code>CREATE DATABASE</code>. At the postgreSQL command prompt, you can
use</p>
<pre><code>create database biotrade;</code></pre>
<ol start="3" style="list-style-type: decimal">
<li><p>Grant rights to another user. First connect to the database</p>
<pre><code> psql -d biotrade -h localhost -U rdb</code></pre>
<p>Then grand privileges</p>
<pre><code> GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA raw_comtrade TO paul;</code></pre></li>
</ol>
</div>
<div id="connect-to-a-database" class="section level1">
<h1>Connect to a database</h1>
<div id="configuration-file-.pgpass" class="section level2">
<h2>Configuration file ~/.pgpass</h2>
<p>This is the preferred way to connect to the database for scripts.
Create a <code>~/.pgpass</code> file to store the connection details for
that user:</p>
<pre><code>echo 'localhost:*:tradeflows:rdb:localhost' >> ~/.pgpass</code></pre>
<p>Secure the file:</p>
<pre><code>chmod 600 ~/.pgpass</code></pre>
<p>The <code>~/.pgpass</code> file should contain lines of the following
format:</p>
<pre><code>hostname:port:database:username:password</code></pre>
<blockquote>
<p>“Each of the first four fields can be a literal value, or
<code>*</code>, which matches anything.”</p>
</blockquote>
<p>Therefore I use <code>*</code> for the port so that it matches any
ports.</p>
</div>
<div id="service-file-.pg_service.conf" class="section level2">
<h2>Service file ~/.pg_service.conf</h2>
<p>The <a
href="https://www.postgresql.org/docs/current/libpq-pgservice.html">postgresql
service file</a> enables “connection parameters to be associated with a
single service name”. You can specify the database connection parameters
in a file called <code>~/.pg_service.conf</code> in you home.</p>
<pre><code># Trade database
[biotrade]
host=localhost
port=5432
user=rdb
dbname=biotrade
password=localhost</code></pre>
<p>And you would then connect to the database with:</p>
<pre><code>psql service=biotrade</code></pre>
</div>
<div id="connect-to-the-database" class="section level2">
<h2>Connect to the database</h2>
<p>Using the credentials stored in <code>~/.pgpass</code></p>
<pre><code>psql -d tradeflows -h localhost -U rdb
psql -d biotrade -h localhost -U rdb </code></pre>
<p>Specifying the port (normally not necessary if it’s specified in
<code>~/.pgpass</code>)</p>
<pre><code>psql -d biotrade -h localhost -U rdb -p 5433</code></pre>
<p>It’s possible to specify a connection URI of the form:</p>
<pre><code>psql postgresql://rdb@localhost:5432/biotrade
# And since I have a URL set as an environmental variable
psql $BIOTRADE_DATABASE_URL</code></pre>
<p><a
href="https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-PARAMKEYWORDS">Postgresql
connection URIs</a></p>
<blockquote>
<p>“It is possible to specify multiple host components, each with an
optional port component, in a single URI. A URI of the form
postgresql://host1:port1,host2:port2,host3:port3/ is equivalent to a
connection string of the form host=host1,host2,host3
port=port1,port2,port3. As further described below, each host will be
tried in turn until a connection is successfully established.”</p>
</blockquote>
</div>
<div id="connect-by-changing-the-user-at-the-system-level"
class="section level2">
<h2>Connect by changing the user at the system level</h2>
<p>Login as the user who is the owner of that database</p>
<pre><code>sudo -i -u rdb</code></pre>
<p>Connect to the database</p>
<pre><code>psql tradeflows</code></pre>
</div>
</div>
<div id="data-types" class="section level1">
<h1>Data types</h1>
<div id="character" class="section level2">
<h2>Character</h2>
<p><a
href="https://www.postgresql.org/docs/8.4/datatype-character.html">Datatype
character</a>:</p>
<table>
<thead>
<tr class="header">
<th>Name</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>character varying(n), varchar(n)</td>
<td>variable-length with limit</td>
</tr>
<tr class="even">
<td>character(n), char(n)</td>
<td>fixed-length, blank padded</td>
</tr>
<tr class="odd">
<td>text</td>
<td>variable unlimited length</td>
</tr>
</tbody>
</table>
<p>Tip:</p>
<blockquote>
<p>“There is no performance difference among these three types, apart
from increased storage space when using the blank-padded type, and a few
extra CPU cycles to check the length when storing into a
length-constrained column. While character(n) has performance advantages
in some other database systems, there is no such advantage in
PostgreSQL; in fact character(n) is usually the slowest of the three
because of its additional storage costs. In most situations text or
character varying should be used instead.”</p>
</blockquote>
<p><a href="https://stackoverflow.com/a/20334221/2641825">SO
answer</a></p>
<blockquote>
<p>“Generally, there is no downside to using text in terms of
performance/memory. On the contrary: text is the optimum. Other types
have more or less relevant downsides. text is literally the”preferred”
type among string types in the Postgres type system, which can affect
function or operator type resolution.”</p>
</blockquote>
<p><a href="https://stackoverflow.com/a/4849030/2641825">differences
between text and varchar</a></p>
<blockquote>
<p>To sum it all up: - char(n) – takes too much space when dealing with
values shorter than n (pads them to n), and can lead to subtle errors
because of adding trailing spaces, plus it is problematic to change the
limit - varchar(n) – it’s problematic to change the limit in live
environment (requires exclusive lock while altering table) - varchar –
just like text - text – for me a winner – over (n) data types because it
lacks their problems, and over varchar – because it has distinct
name</p>
</blockquote>
<p>In SQLite as well, character(n) doesn’t seem to have any performance
advantage.</p>
<p><a href="https://www.sqlite.org/datatype3.html">SQLite data
types</a></p>
<blockquote>
<p>Note that numeric arguments in parentheses that following the type
name (ex: “VARCHAR(255)”) are ignored by SQLite - SQLite does not impose
any length restrictions (other than the large global SQLITE_MAX_LENGTH
limit) on the length of strings, BLOBs or numeric values.</p>
</blockquote>
</div>
</div>
<div id="delete-data" class="section level1">
<h1>Delete data</h1>
<div id="delete-content-from-a-table" class="section level2">
<h2>Delete content from a table</h2>
<p>Keep the table structure but delete it’s content. Delete oil products
from the Comtrade monthly table:</p>
<pre><code># Check results
select distinct(product_code) from raw_comtrade.monthly where product_code like '15%';
# Delete
DELETE FROM raw_comtrade.monthly WHERE product_code like '15%';
DELETE FROM raw_comtrade.monthly WHERE product_code like '44%';</code></pre>
</div>
<div id="drop-a-db-schema-or-table" class="section level2">
<h2>Drop a db, schema or table</h2>
<p>Drop a database</p>
<pre><code>postgres=# drop database databasename;</code></pre>
<p>Drop a schema</p>
<pre><code>psql -d tradeflows -h localhost -U rdb -c "DROP SCHEMA raw_comext"
ERROR: cannot drop schema raw_comext because other objects depend on it
DETAIL: table raw_comext.monthly depends on schema raw_comext
HINT: Use DROP ... CASCADE to drop the dependent objects too.</code></pre>
<p>Drop a schema and all its table with a drop in cascade</p>
<pre><code>psql -d tradeflows -h localhost -U rdb -c "DROP SCHEMA raw_comext CASCADE"</code></pre>
<p>Drop a table</p>
<pre><code>drop table raw_comtrade.yearly;</code></pre>
</div>
</div>
<div id="optimize" class="section level1">
<h1>Optimize</h1>
<div id="indexes" class="section level2">
<h2>Indexes</h2>
</div>
<div id="partial-indexes" class="section level2">
<h2>Partial indexes</h2>
<p>Create a partial index on the first 4 characters of the product
code</p>
<pre><code>CREATE INDEX ix_raw_comtrade_yearly_product_code_prefix_4
ON raw_comtrade.yearly (LEFT(product_code, 4));</code></pre>
<p>The database structure is defined as SQLAlchemy objects, then later
translated in either SQLite or PostGreSQL dialect. Show the database
structure as defined in PostGreSQL:</p>
<pre><code>pg_dump --schema-only -t raw_comtrade.yearly $BIOTRADE_DATABASE_URL > table_structure_dump.sql</code></pre>
<p>Create an additional index to speed up query on the first 4 digits of
the product code (it doesn’t actually speed things up, left here for
information purposes).</p>
<pre><code>psql $BIOTRADE_DATABASE_URL
CREATE INDEX ix_raw_comtrade_yearly_product_code_prefix_4
ON raw_comtrade.yearly (LEFT(product_code, 4));</code></pre>
<p>Remove an index</p>
<pre><code>SET search_path TO raw_comtrade, public;
DROP INDEX ix_raw_comtrade_yearly_product_code_prefix_4;</code></pre>
</div>
</div>
<div id="rename" class="section level1">
<h1>Rename</h1>
<div id="rename-a-table" class="section level2">
<h2>Rename a table</h2>
<p>Rename a table to another name with <code>_backup</code> at the
end</p>
<pre><code>ALTER TABLE raw_comtrade.yearly RENAME TO yearly_backup;
ALTER TABLE raw_comtrade.monthly RENAME TO monthly_backup;
ALTER TABLE raw_comtrade.product RENAME TO product_backup;</code></pre>
</div>
<div id="rename-a-schema" class="section level2">
<h2>Rename a schema</h2>
<p>Rename a schema</p>
<pre><code>ALTER SCHEMA raw_comtrade RENAME TO raw_comtrade_backup;</code></pre>
</div>
</div>
<div id="dump" class="section level1">
<h1>Dump</h1>
<p>Examples copied from <code>man pg_dump</code>. To dump a database
called mydb into a SQL-script file:</p>
<pre><code>$ pg_dump mydb > db.sql</code></pre>
<p>To reload such a script into a (freshly created) database named
newdb:</p>
<pre><code>$ psql -d newdb -f db.sql</code></pre>
<div id="remove-statements" class="section level2">
<h2>Remove statements</h2>
<p>The dump contained the following two statements which I removed:</p>
<pre><code>SET default_tablespace = '';
SET default_with_oids = false;</code></pre>
<p>I removed default table space because the official documentation for
<a
href="https://www.postgresql.org/docs/current/manage-ag-tablespaces.html">table
spaces</a> says it doesn’t make sense to have more than one table space
per system.</p>
<p>I removed default_with_oids because <a
href="https://dba.stackexchange.com/questions/101281/what-is-the-relevance-of-set-default-with-oids-true-in-a-postgresql-dump">this
posrt</a> explains that it’s used to enable a legacy feature.</p>
</div>
<div id="duplicate-a-table" class="section level2">
<h2>Duplicate a table</h2>
<p>Duplicate a table:</p>
<pre><code>create table raw_comtrade.monthly_copy as (select * from raw_comtrade.monthly);</code></pre>
</div>
</div>
<div id="help" class="section level1">
<h1>Help</h1>
<p>Help about psql commands:</p>
<p>?</p>
<p>Help about SQL commands:</p>
<pre><code>\h
\h select</code></pre>
</div>
<div id="information" class="section level1">
<h1>Information</h1>
<div id="list-schemas-tables-columns" class="section level2">
<h2>List schemas, tables, columns</h2>
<p>List databases</p>
<pre><code>\l</code></pre>
<p>Connect to a database</p>
<pre><code>\c db_name</code></pre>
<p>List schemas</p>
<pre><code>\dn</code></pre>
<p>List tables</p>
<pre><code>\dt</code></pre>
<p>List tables for a particular schema i<a
href="https://dba.stackexchange.com/questions/40045/how-do-i-list-all-schemas-in-postgresql">list
all tables in schema</a></p>
<pre><code>\dt raw_comext.*;
\dt raw_comtrade.*;
\dt raw_faostat*;</code></pre>
</div>
<div id="describe-data-types" class="section level2">
<h2>Describe data types</h2>
<p>Describe a table to show the table structure, including column names
and data types</p>
<pre><code>\d raw_comtrade.yearly;
\d raw_comtrade.monthly;</code></pre>
</div>
</div>
<div id="load-data-into-the-database" class="section level1">
<h1>Load data into the database</h1>
<div id="sql-files" class="section level2">
<h2>SQL files</h2>
<p>Read commands from a file with the <code>-f</code> argument:</p>
<pre><code>psql -d biotrade -h localhost -U rdb -f ~/rp/biotrade/biotrade/config_data/comtrade.sql</code></pre>
</div>
</div>
<div id="mariadbmysql-and-postgresql" class="section level1">
<h1>MariaDB/MySQL and PostgreSQL</h1>
<div id="compare-commands" class="section level2">
<h2>Compare commands</h2>
<p>Compare common commands between MariaDB and PostgreSQL.</p>
<table>
<thead>
<tr class="header">
<th>MariaDB/MySQL</th>
<th>PostgreSQL</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>show databases;</td>
<td>\l</td>
</tr>
<tr class="even">
<td>connect db_name;</td>
<td>\c db_name</td>
</tr>
<tr class="odd">
<td>show tables;</td>
<td>\dt</td>
</tr>
<tr class="even">
<td></td>
<td></td>
</tr>
<tr class="odd">
<td></td>
<td></td>
</tr>
</tbody>
</table>
</div>
<div id="migrate-from-mysql-into-postgresql" class="section level2">
<h2>Migrate from MySQL into PostgreSQL</h2>
<ul>
<li>ipostgresql.org <a
href="https://wiki.postgresql.org/wiki/Converting_from_other_Databases_to_PostgreSQL#MySQL">converting
from other databases to postgreSQL</a></li>
<li><a href="https://github.com/dimitri/pgloader">pgloader</a></li>
</ul>
<p>Transfer data from MySQL to PostgreSQL:</p>
<pre><code>pgloader mysql://user@localhost/sakila postgresql:///pagila</code></pre>
<p>For my own database I used:</p>
<pre><code>sudo su postgres
createdb -O paul tradeflows_migrated
exit # Go back to user "paul"
pgloader mysql://paul@localhost/tradeflows postgresql:///tradeflows_migrated</code></pre>
</div>
</div>
<div id="select" class="section level1">
<h1>SELECT</h1>
<p>Connect to the database (with the credentials defined in
<code>~/.pgpass</code>)</p>
<pre><code>psql biotrade</code></pre>
<p>postgresql.org the <a
href="https://www.postgresql.org/docs/13/queries-table-expressions.html#QUERIES-WHERE">WHERE
Clause</a></p>
<p>Here are some examples of WHERE clauses:</p>
<pre><code>SELECT ... FROM fdt WHERE c1 > 5
SELECT ... FROM fdt WHERE c1 IN (1, 2, 3)
SELECT ... FROM fdt WHERE c1 IN (SELECT c1 FROM t2)
SELECT ... FROM fdt WHERE c1 IN (SELECT c3 FROM t2 WHERE c2 = fdt.c1 + 10)
SELECT ... FROM fdt WHERE c1 BETWEEN (SELECT c3 FROM t2 WHERE c2 = fdt.c1 + 10) AND 100
SELECT ... FROM fdt WHERE EXISTS (SELECT c1 FROM t2 WHERE c2 > fdt.c1)</code></pre>
<p>When using string values, single quotes are required (otherwise the
<code>ERROR: column "02" does not exist</code> is returned)</p>
<pre><code>select distinct(reporter) from raw_comtrade.yearly_hs2 where commodity_code = '02';</code></pre>
<div id="like" class="section level2">
<h2>Like</h2>
<p>Select product codes that start with <code>"15"</code></p>
<pre><code>select distinct(product_code) from raw_comtrade.monthly where product_code like '15%';</code></pre>
</div>
<div id="in" class="section level2">
<h2>In</h2>
<p>Select product codes within a list, then group by and count</p>
<pre><code>biotrade=> SELECT product_code, count(*) FROM raw_comtrade.yearly WHERE
product_code IN ('230400', '150710', '120190') group by product_code;
product_code | count
--------------+-------
120190 | 29727
150710 | 33790
230400 | 49398</code></pre>
</div>
</div>
<div id="road-map" class="section level1">
<h1>Road map</h1>
<p>postgresql.org <a
href="https://www.postgresql.org/developer/roadmap/">Roadmap</a></p>
</div>
<div id="schemas" class="section level1">
<h1>Schemas</h1>
<p>Create a schema</p>
<pre><code>create schema raw_comtrade;</code></pre>
<p>List schemas</p>
<pre><code>\dn</code></pre>
<p>Official documentation postgresql.org <a
href="https://www.postgresql.org/docs/current/ddl-schemas.html">schemas</a></p>
<blockquote>
<p>“A database contains one or more named schemas, which in turn contain
tables. Schemas also contain other kinds of named objects, including
data types, functions, and operators. The same object name can be used
in different schemas without conflict; for example, both schema1 and
myschema can contain tables named mytable. Unlike databases, schemas are
not rigidly separated: a user can access objects in any of the schemas
in the database they are connected to, if they have privileges to do
so.”</p>
</blockquote>
<blockquote>
<p>“There are several reasons why one might want to use schemas:”</p>
</blockquote>
<ul>
<li>“To allow many users to use one database without interfering with
each other.”</li>
<li>“To organize database objects into logical groups to make them more
manageable.”</li>
<li>“Third-party applications can be put into separate schemas so they
do not collide with the names of other objects.”</li>
</ul>
<blockquote>
<p>“Schemas are analogous to directories at the operating system level,
except that schemas cannot be nested.”</p>
</blockquote>
</div>
<div id="tables" class="section level1">
<h1>Tables</h1>
<p>List tables for a particular schema:</p>
<pre><code>\dt raw_comtrade.*;</code></pre>
<div id="export-a-table-structure" class="section level2">
<h2>Export a table structure</h2>
<p><a
href="https://stackoverflow.com/questions/2593803/how-to-generate-the-create-table-sql-statement-for-an-existing-table-in-postgr">Export
the create statement for an existing table</a></p>
<pre><code>pg_dump -t 'raw_comtrade.yearly_2_digit' --schema-only biotrade >> /tmp/comtrade_yearly.sql</code></pre>
</div>
</div>
<div id="blogs-and-other-resources" class="section level1">
<h1>Blogs and other resources</h1>
<p>Dimitri Fontaine 2014 <a
href="https://tapoueh.org/blog/2014/05/why-is-pgloader-so-much-faster/">Why
is pgloader faster ?</a></p>
<blockquote>
<p>“In searching for a modern programming language the best candidate I
found was actually Common Lisp.”</p>
</blockquote>
<p>See also a more detailed quote under the <a href="lisp.html">Lisp
page</a>.</p>
<p><a
href="https://en.wikipedia.org/wiki/SQL#Standardization_history">Wikipedia</a>
paragraph on the pronunciation</p>
<blockquote>
<p>“The original standard declared that the official pronunciation
for”SQL” was an initialism: /ˌɛsˌkjuːˈɛl/ (“ess cue el”). Regardless,
many English-speaking database professionals (including Donald
Chamberlin himself) use the acronym-like pronunciation of /ˈsiːkwəl/
(“sequel”), mirroring the language’s prerelease development name,
“SEQUEL”.”</p>
</blockquote>
</div>
</div>
</div>
</div>
<script>
// add bootstrap table styles to pandoc tables
function bootstrapStylePandocTables() {
$('tr.odd').parent('tbody').parent('table').addClass('table table-condensed');
}
$(document).ready(function () {
bootstrapStylePandocTables();
});
</script>
<!-- tabsets -->
<script>
$(document).ready(function () {
window.buildTabsets("TOC");
});
$(document).ready(function () {
$('.tabset-dropdown > .nav-tabs > li').click(function () {
$(this).parent().toggleClass('nav-tabs-open');
});
});
</script>
<!-- code folding -->
<script>
$(document).ready(function () {
// temporarily add toc-ignore selector to headers for the consistency with Pandoc
$('.unlisted.unnumbered').addClass('toc-ignore')
// move toc-ignore selectors from section div to header
$('div.section.toc-ignore')