]> granicus.if.org Git - postgresql/blob - doc/FAQ
Update FAQ from Robert Treat
[postgresql] / doc / FAQ
1
2                 Frequently Asked Questions (FAQ) for PostgreSQL
3                                        
4    Last updated: Mon Mar 29 00:07:11 EST 2004
5    
6    Current maintainer: Bruce Momjian (pgman@candle.pha.pa.us)
7    
8    The most recent version of this document can be viewed at
9    http://www.PostgreSQL.org/docs/faqs/FAQ.html.
10    
11    Platform-specific questions are answered at
12    http://www.PostgreSQL.org/docs/index.html.
13      _________________________________________________________________
14    
15                              General Questions
16                                       
17    1.1) What is PostgreSQL? How is it pronounced?
18    1.2) What is the copyright on PostgreSQL?
19    1.3) What Unix platforms does PostgreSQL run on?
20    1.4) What non-Unix ports are available?
21    1.5) Where can I get PostgreSQL?
22    1.6) Where can I get support?
23    1.7) What is the latest release?
24    1.8) What documentation is available?
25    1.9) How do I find out about known bugs or missing features?
26    1.10) How can I learn SQL?
27    1.11) Is PostgreSQL Y2K compliant?
28    1.12) How do I join the development team?
29    1.13) How do I submit a bug report?
30    1.14) How does PostgreSQL compare to other DBMSs?
31    1.15) How can I financially assist PostgreSQL?
32    
33                            User Client Questions
34                                       
35    2.1) Are there ODBC drivers for PostgreSQL?
36    2.2) What tools are available for using PostgreSQL with Web pages?
37    2.3) Does PostgreSQL have a graphical user interface?
38    2.4) What languages are available to communicate with PostgreSQL?
39    
40                           Administrative Questions
41                                       
42    3.1) How do I install PostgreSQL somewhere other than
43    /usr/local/pgsql?
44    3.2) When I start postmaster, I get a Bad System Call or core dumped
45    message. Why?
46    3.3) When I try to start postmaster, I get IpcMemoryCreate errors.
47    Why?
48    3.4) When I try to start postmaster, I get IpcSemaphoreCreate errors.
49    Why?
50    3.5) How do I control connections from other hosts?
51    3.6) How do I tune the database engine for better performance?
52    3.7) What debugging features are available?
53    3.8) Why do I get "Sorry, too many clients" when trying to connect?
54    3.9) What is in the pgsql_tmp directory?
55    3.10) Why do I need to do a dump and restore to upgrade PostgreSQL
56    releases?
57    
58                            Operational Questions
59                                       
60    4.1) What is the difference between binary cursors and normal cursors?
61    4.2) How do I SELECT only the first few rows of a query? A random row?
62    4.3) How do I get a list of tables or other things I can see in psql?
63    4.4) How do you remove a column from a table, or change it's data
64    type?
65    4.5) What is the maximum size for a row, a table, and a database?
66    4.6) How much database disk space is required to store data from a
67    typical text file?
68    4.7) How do I find out what tables, indexes, databases, and users are
69    defined?
70    4.8) My queries are slow or don't make use of the indexes. Why?
71    4.9) How do I see how the query optimizer is evaluating my query?
72    4.10) What is an R-tree index?
73    4.11) What is the Genetic Query Optimizer?
74    4.12) How do I perform regular expression searches and
75    case-insensitive regular expression searches? How do I use an index
76    for case-insensitive searches?
77    4.13) In a query, how do I detect if a field is NULL?
78    4.14) What is the difference between the various character types?
79    4.15.1) How do I create a serial/auto-incrementing field?
80    4.15.2) How do I get the value of a SERIAL insert?
81    4.15.3) Don't currval() and nextval() lead to a race condition with
82    other users?
83    4.15.4) Why aren't my sequence numbers reused on transaction abort?
84    Why are there gaps in the numbering of my sequence/SERIAL column?
85    4.16) What is an OID? What is a TID?
86    4.17) What is the meaning of some of the terms used in PostgreSQL?
87    4.18) Why do I get the error "ERROR: Memory exhausted in
88    AllocSetAlloc()"?
89    4.19) How do I tell what PostgreSQL version I am running?
90    4.20) Why does my large-object operations get "invalid large obj
91    descriptor"?
92    4.21) How do I create a column that will default to the current time?
93    4.22) Why are my subqueries using IN so slow?
94    4.23) How do I perform an outer join?
95    4.24) How do I perform queries using multiple databases?
96    4.25) How do I return multiple rows or columns from a function?
97    4.26) Why can't I reliably create/drop temporary tables in PL/PgSQL
98    functions?
99    4.27) What replication options are available?
100    4.28) What encryption options are available?
101    
102                             Extending PostgreSQL
103                                       
104    5.1) I wrote a user-defined function. When I run it in psql, why does
105    it dump core?
106    5.2) How can I contribute some nifty new types and functions to
107    PostgreSQL?
108    5.3) How do I write a C function to return a tuple?
109    5.4) I have changed a source file. Why does the recompile not see the
110    change?
111      _________________________________________________________________
112    
113                              General Questions
114                                       
115     1.1) What is PostgreSQL? How is it pronounced?
116     
117    PostgreSQL is pronounced Post-Gres-Q-L. An audio file is available at
118    http://www.postgresql.org/postgresql.mp3 for those would like to hear
119    the pronunciation.
120    
121    PostgreSQL is an enhancement of the POSTGRES database management
122    system (and is still sometimes reffered to as simply "Postgres"), a
123    next-generation DBMS research prototype. While PostgreSQL retains the
124    powerful data model and rich data types of POSTGRES, it replaces the
125    PostQuel query language with an extended subset of SQL. PostgreSQL is
126    free and the complete source is available.
127    
128    PostgreSQL development is performed by a team of developers who all
129    subscribe to the PostgreSQL development mailing list. The current
130    coordinator is Marc G. Fournier (scrappy@PostgreSQL.org). (See section
131    1.6 on how to join). This team is now responsible for all development
132    of PostgreSQL. It is a community project and is not controlled by any
133    company. To get involved, see the developer's FAQ at
134    http://www.PostgreSQL.org/docs/faqs/FAQ_DEV.html
135    
136    The authors of PostgreSQL 1.01 were Andrew Yu and Jolly Chen. Many
137    others have contributed to the porting, testing, debugging, and
138    enhancement of the code. The original Postgres code, from which
139    PostgreSQL is derived, was the effort of many graduate students,
140    undergraduate students, and staff programmers working under the
141    direction of Professor Michael Stonebraker at the University of
142    California, Berkeley.
143    
144    The original name of the software at Berkeley was Postgres. When SQL
145    functionality was added in 1995, its name was changed to Postgres95.
146    The name was changed at the end of 1996 to PostgreSQL.
147    
148     1.2) What is the copyright on PostgreSQL?
149     
150    PostgreSQL is subject to the following COPYRIGHT:
151    
152    PostgreSQL Data Base Management System
153    
154    Portions copyright (c) 1996-2004, PostgreSQL Global Development Group
155    Portions Copyright (c) 1994-6 Regents of the University of California
156    
157    Permission to use, copy, modify, and distribute this software and its
158    documentation for any purpose, without fee, and without a written
159    agreement is hereby granted, provided that the above copyright notice
160    and this paragraph and the following two paragraphs appear in all
161    copies.
162    
163    IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY
164    FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
165    INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND
166    ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF CALIFORNIA HAS BEEN
167    ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
168    
169    THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
170    INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
171    MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE
172    PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF
173    CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,
174    UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
175    
176    The above is the BSD license, the classic open-source license. It has
177    no restrictions on how the source code may be used. We like it and
178    have no intention of changing it.
179    
180     1.3) What Unix platforms does PostgreSQL run on?
181     
182    In general, any modern Unix-compatible platform should be able to run
183    PostgreSQL. The platforms that had received explicit testing at the
184    time of release are listed in the installation instructions.
185    
186     1.4) What non-Unix ports are available?
187     
188    Client
189    
190    It is possible to compile the libpq C library, psql, and other
191    interfaces and client applications to run on MS Windows platforms. In
192    this case, the client is running on MS Windows, and communicates via
193    TCP/IP to a server running on one of our supported Unix platforms. A
194    file win32.mak is included in the distribution for making a Win32
195    libpq library and psql. PostgreSQL also communicates with ODBC
196    clients.
197    
198    Server
199    
200    The database server can run on Windows NT and Win2k using Cygwin, the
201    Cygnus Unix/NT porting library. See pgsql/doc/FAQ_MSWIN in the
202    distribution or the MS Windows FAQ at
203    http://www.PostgreSQL.org/docs/faqs/text/FAQ_MSWIN.
204    
205    A native port to MS Win NT/2000/XP is currently being worked on. For
206    more details on the current status of PostgreSQL on Windows see
207    http://techdocs.postgresql.org/guides/Windows and
208    http://momjian.postgresql.org/main/writings/pgsql/win32.html.
209    
210    There is also a Novell Netware 6 port at http://forge.novell.com.
211    
212     1.5) Where can I get PostgreSQL?
213     
214    The primary anonymous ftp site for PostgreSQL is
215    ftp://ftp.PostgreSQL.org/pub. For mirror sites, see our main web site.
216    
217     1.6) Where can I get support?
218     
219    The main mailing list is: pgsql-general@PostgreSQL.org. It is
220    available for discussion of matters pertaining to PostgreSQL. To
221    subscribe, send mail with the following lines in the body (not the
222    subject line):
223     subscribe
224     end
225
226    to pgsql-general-request@PostgreSQL.org.
227    
228    There is also a digest list available. To subscribe to this list, send
229    email to: pgsql-general-digest-request@PostgreSQL.org with a body of:
230     subscribe
231     end
232
233    Digests are sent out to members of this list whenever the main list
234    has received around 30k of messages.
235    
236    The bugs mailing list is available. To subscribe to this list, send
237    email to pgsql-bugs-request@PostgreSQL.org with a body of:
238     subscribe
239     end
240
241    There is also a developers discussion mailing list available. To
242    subscribe to this list, send email to
243    pgsql-hackers-request@PostgreSQL.org with a body of:
244     subscribe
245     end
246
247    Additional mailing lists and information about PostgreSQL can be found
248    via the PostgreSQL WWW home page at:
249    
250      http://www.PostgreSQL.org
251      
252    There is also an IRC channel on Freenode and EFNet, channel
253    #PostgreSQL. You can use the Unix command irc -c '#PostgreSQL' "$USER"
254    irc.phoenix.net. or irc -c '#PostgreSQL' "$USER" irc.freenode.net.
255    
256    A list of commercial support companies is available at
257    http://techdocs.postgresql.org/companies.php.
258    
259     1.7) What is the latest release?
260     
261    The latest release of PostgreSQL is version 7.4.2.
262    
263    We plan to have major releases every six to eight months.
264    
265     1.8) What documentation is available?
266     
267    Several manuals, manual pages, and some small test examples are
268    included in the distribution. See the /doc directory. You can also
269    browse the manuals online at http://www.PostgreSQL.org/docs.
270    
271    There are two PostgreSQL books available online at
272    http://www.PostgreSQL.org/docs/awbook.html and
273    http://www.commandprompt.com/ppbook/. There is a list of PostgreSQL
274    books available for purchase at
275    http://techdocs.PostgreSQL.org/techdocs/bookreviews.php. There is also
276    a collection of PostgreSQL technical articles at
277    http://techdocs.PostgreSQL.org/.
278    
279    psql has some nice \d commands to show information about types,
280    operators, functions, aggregates, etc.
281    
282    Our web site contains even more documentation.
283    
284     1.9) How do I find out about known bugs or missing features?
285     
286    PostgreSQL supports an extended subset of SQL-92. See our TODO list
287    for known bugs, missing features, and future plans.
288    
289     1.10) How can I learn SQL?
290     
291    The PostgreSQL book at http://www.PostgreSQL.org/docs/awbook.html
292    teaches SQL. There is another PostgreSQL book at
293    http://www.commandprompt.com/ppbook. There is a nice tutorial at
294    http://www.intermedia.net/support/sql/sqltut.shtm, at
295    http://ourworld.compuserve.com/homepages/graeme_birchall/HTM_COOK.HTM,
296    and at http://sqlcourse.com.
297    
298    Another one is "Teach Yourself SQL in 21 Days, Second Edition" at
299    http://members.tripod.com/er4ebus/sql/index.htm
300    
301    Many of our users like The Practical SQL Handbook, Bowman, Judith S.,
302    et al., Addison-Wesley. Others like The Complete Reference SQL, Groff
303    et al., McGraw-Hill.
304    
305     1.11) Is PostgreSQL Y2K compliant?
306     
307    Yes, we easily handle dates past the year 2000 AD, and before 2000 BC.
308    
309     1.12) How do I join the development team?
310     
311    First, download the latest source and read the PostgreSQL Developers
312    documentation on our web site, or in the distribution. Second,
313    subscribe to the pgsql-hackers and pgsql-patches mailing lists. Third,
314    submit high quality patches to pgsql-patches.
315    
316    There are about a dozen people who have commit privileges to the
317    PostgreSQL CVS archive. They each have submitted so many high-quality
318    patches that it was impossible for the existing committers to keep up,
319    and we had confidence that patches they committed were of high
320    quality.
321    
322     1.13) How do I submit a bug report?
323     
324    Please visit the PostgreSQL BugTool page at
325    http://www.PostgreSQL.org/bugs/bugs.php, which gives guidelines and
326    directions on how to submit a bug report.
327    
328    Also check out our ftp site ftp://ftp.PostgreSQL.org/pub to see if
329    there is a more recent PostgreSQL version or patches.
330    
331     1.14) How does PostgreSQL compare to other DBMSs?
332     
333    There are several ways of measuring software: features, performance,
334    reliability, support, and price.
335    
336    Features
337           PostgreSQL has most features present in large commercial DBMSs,
338           like transactions, subselects, triggers, views, foreign key
339           referential integrity, and sophisticated locking. We have some
340           features they do not have, like user-defined types,
341           inheritance, rules, and multi-version concurrency control to
342           reduce lock contention.
343           
344    Performance
345           PostgreSQL has performance similar to other commercial and open
346           source databases. it is faster for some things, slower for
347           others. In comparison to MySQL or leaner database systems, we
348           are faster for multiple users, complex queries, and a
349           read/write query load. MySQL is faster for simple SELECT
350           queries done by a few users. Of course, MySQL does not have
351           most of the features mentioned in the Features section above.
352           We are built for reliability and features, and we continue to
353           improve performance in every release. There is an interesting
354           Web page comparing PostgreSQL to MySQL at
355           http://openacs.org/philosophy/why-not-mysql.html Also, MySQL is
356           is a company that distributes its products via open source, and
357           requires a commercial license for close-source software, not an
358           open source development community like PostgreSQL.
359           
360    Reliability
361           We realize that a DBMS must be reliable, or it is worthless. We
362           strive to release well-tested, stable code that has a minimum
363           of bugs. Each release has at least one month of beta testing,
364           and our release history shows that we can provide stable, solid
365           releases that are ready for production use. We believe we
366           compare favorably to other database software in this area.
367           
368    Support
369           Our mailing lists provide contact with a large group of
370           developers and users to help resolve any problems encountered.
371           While we cannot guarantee a fix, commercial DBMSs do not always
372           supply a fix either. Direct access to developers, the user
373           community, manuals, and the source code often make PostgreSQL
374           support superior to other DBMSs. There is commercial
375           per-incident support available for those who need it. (See FAQ
376           section 1.6.)
377           
378    Price
379           We are free for all use, both commercial and non-commercial.
380           You can add our code to your product with no limitations,
381           except those outlined in our BSD-style license stated above.
382           
383     1.15) How can I financially assist PostgreSQL?
384     
385    PostgreSQL has had a first-class infrastructure since we started in
386    1996. This is all thanks to Marc Fournier, who has created and managed
387    this infrastructure over the years.
388    
389    Quality infrastructure is very important to an open-source project. It
390    prevents disruptions that can greatly delay forward movement of the
391    project.
392    
393    Of course, this infrastructure is not cheap. There are a variety of
394    monthly and one-time expenses that are required to keep it going. If
395    you or your company has money it can donate to help fund this effort,
396    please go to http://store.pgsql.com/shopping/ and make a donation.
397    
398    Although the web page mentions PostgreSQL, Inc, the "contributions"
399    item is solely to support the PostgreSQL project and does not fund any
400    specific company. If you prefer, you can also send a check to the
401    contact address.
402      _________________________________________________________________
403    
404    Also, if you have a success story about PostgreSQL, please submit it
405    to our advocacy site at http://advocacy.postgresql.org.
406    
407                            User Client Questions
408                                       
409     2.1) Are there ODBC drivers for PostgreSQL?
410     
411    There are two ODBC drivers available, PsqlODBC and OpenLink ODBC.
412    
413    You can download PsqlODBC from
414    http://gborg.postgresql.org/project/psqlodbc/projdisplay.php.
415    
416    OpenLink ODBC can be gotten from http://www.openlinksw.com. It works
417    with their standard ODBC client software so you'll have PostgreSQL
418    ODBC available on every client platform they support (Win, Mac, Unix,
419    VMS).
420    
421    They will probably be selling this product to people who need
422    commercial-quality support, but a freeware version will always be
423    available. Please send questions to postgres95@openlink.co.uk.
424    
425     2.2) What tools are available for using PostgreSQL with Web pages?
426     
427    A nice introduction to Database-backed Web pages can be seen at:
428    http://www.webreview.com
429    
430    For Web integration, PHP is an excellent interface. It is at
431    http://www.php.net.
432    
433    For complex cases, many use the Perl interface and CGI.pm or mod_perl.
434    
435     2.3) Does PostgreSQL have a graphical user interface?
436     
437    Yes, there are several graphical interfaces to PostgreSQL available.
438    These include PgAccess http://www.pgaccess.org), PgAdmin III
439    (http://www.pgadmin.org, RHDB Admin (http://sources.redhat.com/rhdb/ )
440    and Rekall ( http://www.thekompany.com/products/rekall/, proprietary).
441    There is also PhpPgAdmin ( http://phppgadmin.sourceforge.net/ ), a
442    web-based interface to PostgreSQL.
443    
444    See http://techdocs.postgresql.org/guides/GUITools for a more detailed
445    list.
446    
447     2.4) What languages are able to communicate with PostgreSQL?
448     
449    Most popular programming languages contain an interface to PostgreSQL.
450    Check your programming language's list of extension modules.
451    
452    The following interfaces are included in the PostgreSQL distribution:
453      * C (libpq)
454      * Embedded C (ecpg)
455      * Java (jdbc)
456      * Python (PyGreSQL)
457      * TCL (libpgtcl)
458        
459    Additional interfaces are available at http://gborg.postgresql.org in
460    the Drivers/Interfaces section.
461      _________________________________________________________________
462    
463                           Administrative Questions
464                                       
465     3.1) How do I install PostgreSQL somewhere other than /usr/local/pgsql?
466     
467    Specify the --prefix option when running configure.
468    
469     3.2) When I start postmaster, I get a Bad System Call or core dumped
470     message. Why?
471     
472    It could be a variety of problems, but first check to see that you
473    have System V extensions installed in your kernel. PostgreSQL requires
474    kernel support for shared memory and semaphores.
475    
476     3.3) When I try to start postmaster, I get IpcMemoryCreate errors. Why?
477     
478    You either do not have shared memory configured properly in your
479    kernel or you need to enlarge the shared memory available in the
480    kernel. The exact amount you need depends on your architecture and how
481    many buffers and backend processes you configure for postmaster. For
482    most systems, with default numbers of buffers and processes, you need
483    a minimum of ~1 MB. See the PostgreSQL Administrator's Guide for more
484    detailed information about shared memory and semaphores.
485    
486     3.4) When I try to start postmaster, I get IpcSemaphoreCreate errors. Why?
487     
488    If the error message is IpcSemaphoreCreate: semget failed (No space
489    left on device) then your kernel is not configured with enough
490    semaphores. Postgres needs one semaphore per potential backend
491    process. A temporary solution is to start postmaster with a smaller
492    limit on the number of backend processes. Use -N with a parameter less
493    than the default of 32. A more permanent solution is to increase your
494    kernel's SEMMNS and SEMMNI parameters.
495    
496    Inoperative semaphores can also cause crashes during heavy database
497    access.
498    
499    If the error message is something else, you might not have semaphore
500    support configured in your kernel at all. See the PostgreSQL
501    Administrator's Guide for more detailed information about shared
502    memory and semaphores.
503    
504     3.5) How do I control connections from other hosts?
505     
506    By default, PostgreSQL only allows connections from the local machine
507    using Unix domain sockets. Other machines will not be able to connect
508    unless you turn on tcpip_sockets in the postgresql.conf and enable
509    host-based authentication by modifying the file $PGDATA/pg_hba.conf
510    accordingly. This will allow TCP/IP connections.
511    
512     3.6) How do I tune the database engine for better performance?
513     
514    Certainly, indexes can speed up queries. The EXPLAIN ANALYZE command
515    allows you to see how PostgreSQL is interpreting your query, and which
516    indexes are being used.
517    
518    If you are doing many INSERTs, consider doing them in a large batch
519    using the COPY command. This is much faster than individual INSERTS.
520    Second, statements not in a BEGIN WORK/COMMIT transaction block are
521    considered to be in their own transaction. Consider performing several
522    statements in a single transaction block. This reduces the transaction
523    overhead. Also, consider dropping and recreating indexes when making
524    large data changes.
525    
526    There are several tuning options. You can disable fsync() by starting
527    postmaster with a -o -F option. This will prevent fsync()s from
528    flushing to disk after every transaction.
529    
530    You can also use the postmaster -B option to increase the number of
531    shared memory buffers used by the backend processes. If you make this
532    parameter too high, the postmaster may not start because you have
533    exceeded your kernel's limit on shared memory space. Each buffer is 8K
534    and the default is 64 buffers.
535    
536    You can also use the backend -S option to increase the maximum amount
537    of memory used by the backend process for temporary sorts. The -S
538    value is measured in kilobytes, and the default is 512 (i.e. 512K).
539    
540    You can also use the CLUSTER command to group data in tables to match
541    an index. See the CLUSTER manual page for more details.
542    
543     3.7) What debugging features are available?
544     
545    PostgreSQL has several features that report status information that
546    can be valuable for debugging purposes.
547    
548    First, by running configure with the --enable-cassert option, many
549    assert()s monitor the progress of the backend and halt the program
550    when something unexpected occurs.
551    
552    Both postmaster and postgres have several debug options available.
553    First, whenever you start postmaster, make sure you send the standard
554    output and error to a log file, like:
555     cd /usr/local/pgsql
556     ./bin/postmaster >server.log 2>&1 &
557
558    This will put a server.log file in the top-level PostgreSQL directory.
559    This file contains useful information about problems or errors
560    encountered by the server. Postmaster has a -d option that allows even
561    more detailed information to be reported. The -d option takes a number
562    that specifies the debug level. Be warned that high debug level values
563    generate large log files.
564    
565    If postmaster is not running, you can actually run the postgres
566    backend from the command line, and type your SQL statement directly.
567    This is recommended only for debugging purposes. Note that a newline
568    terminates the query, not a semicolon. If you have compiled with
569    debugging symbols, you can use a debugger to see what is happening.
570    Because the backend was not started from postmaster, it is not running
571    in an identical environment and locking/backend interaction problems
572    may not be duplicated.
573    
574    If postmaster is running, start psql in one window, then find the PID
575    of the postgres process used by psql. Use a debugger to attach to the
576    postgres PID. You can set breakpoints in the debugger and issue
577    queries from psql. If you are debugging postgres startup, you can set
578    PGOPTIONS="-W n", then start psql. This will cause startup to delay
579    for n seconds so you can attach to the process with the debugger, set
580    any breakpoints, and continue through the startup sequence.
581    
582    The postgres program has -s, -A, and -t options that can be very
583    useful for debugging and performance measurements.
584    
585    You can also compile with profiling to see what functions are taking
586    execution time. The backend profile files will be deposited in the
587    pgsql/data/base/dbname directory. The client profile file will be put
588    in the client's current directory. Linux requires a compile with
589    -DLINUX_PROFILE for proper profiling.
590    
591     3.8) Why do I get "Sorry, too many clients" when trying to connect?
592     
593    You need to increase postmaster's limit on how many concurrent backend
594    processes it can start.
595    
596    The default limit is 32 processes. You can increase it by restarting
597    postmaster with a suitable -N value or modifying postgresql.conf.
598    
599    Note that if you make -N larger than 32, you must also increase -B
600    beyond its default of 64; -B must be at least twice -N, and probably
601    should be more than that for best performance. For large numbers of
602    backend processes, you are also likely to find that you need to
603    increase various Unix kernel configuration parameters. Things to check
604    include the maximum size of shared memory blocks, SHMMAX; the maximum
605    number of semaphores, SEMMNS and SEMMNI; the maximum number of
606    processes, NPROC; the maximum number of processes per user, MAXUPRC;
607    and the maximum number of open files, NFILE and NINODE. The reason
608    that PostgreSQL has a limit on the number of allowed backend processes
609    is so your system won't run out of resources.
610    
611     3.9) What is in the pgsql_tmp directory?
612     
613    This directory contains temporary files generated by the query
614    executor. For example, if a sort needs to be done to satisfy an ORDER
615    BY and the sort requires more space than the backend's -S parameter
616    allows, then temporary files are created here to hold the extra data.
617    
618    The temporary files are usually deleted automatically, but might
619    remain if a backend crashes during a sort. A stop and restart of the
620    postmaster will remove files from those directories.
621    
622     3.10) Why do I need to do a dump and restore to upgrade between major
623     PostgreSQL releases?
624     
625    The PostgreSQL team makes only small changes between minor releases,
626    so upgrading from 7.2 to 7.2.1 does not require a dump and restore.
627    However, major releases (e.g. from 7.2 to 7.3) often change the
628    internal format of system tables and data files. These changes are
629    often complex, so we don't maintain backward compatability for data
630    files. A dump outputs data in a generic format that can then be loaded
631    in using the new internal format.
632    
633    In releases where the on-disk format does not change, the pg_upgrade
634    script can be used to upgrade without a dump/restore. The release
635    notes mention whether pg_upgrade is available for the release.
636      _________________________________________________________________
637    
638                            Operational Questions
639                                       
640     4.1) What is the difference between binary cursors and normal cursors?
641     
642    See the DECLARE manual page for a description.
643    
644     4.2) How do I SELECT only the first few rows of a query? A random row?
645     
646    See the FETCH manual page, or use SELECT ... LIMIT....
647    
648    The entire query may have to be evaluated, even if you only want the
649    first few rows. Consider using a query that has an ORDER BY. If there
650    is an index that matches the ORDER BY, PostgreSQL may be able to
651    evaluate only the first few records requested, or the entire query may
652    have to be evaluated until the desired rows have been generated.
653    
654    To SELECT a random row, use:
655     SELECT col
656     FROM tab
657     ORDER BY random()
658     LIMIT 1;
659
660     4.3) How do I get a list of tables or other things I can see in psql?
661     
662    Use the \dt command to see tables in psql. For a complete list of
663    commands inside psql you can use \?. Alternatively you can read the
664    source code for psql in file pgsql/src/bin/psql/describe.c, it
665    contains SQL commands that generate the output for psql's backslash
666    commands. You can also start psql with the -E option so it will print
667    out the queries it uses to execute the commands you give. PostgreSQL
668    also provides an SQLi compliant INFORMATION SCHEMA interface you can
669    query to get information about the database.
670    
671     4.4) How do you remove a column from a table, or change its data type?
672     
673    DROP COLUMN functionality was added in release 7.3 with ALTER TABLE
674    DROP COLUMN. In earlier versions, you can do this:
675     BEGIN;
676     LOCK TABLE old_table;
677     SELECT ...  -- select all columns but the one you want to remove
678     INTO TABLE new_table
679     FROM old_table;
680     DROP TABLE old_table;
681     ALTER TABLE new_table RENAME TO old_table;
682     COMMIT;
683
684    To change the data type of a column, do this:
685     BEGIN;
686     ALTER TABLE tab ADD COLUMN new_col new_data_type;
687     UPDATE tab SET new_col = CAST(old_col AS new_data_type);
688     ALTER TABLE tab DROP COLUMN old_col;
689     COMMIT;
690
691    You might then want to do VACUUM FULL tab to reclaim the disk space
692    used by the expired rows.
693    
694     4.5) What is the maximum size for a row, a table, and a database?
695     
696    These are the limits:
697     Maximum size for a database?             unlimited (32 TB databases exist)
698     Maximum size for a table?                32 TB
699     Maximum size for a row?                  1.6TB
700     Maximum size for a field?                1 GB
701     Maximum number of rows in a table?       unlimited
702     Maximum number of columns in a table?    250-1600 depending on column types
703     Maximum number of indexes on a table?    unlimited
704
705    Of course, these are not actually unlimited, but limited to available
706    disk space and memory/swap space. Performance may suffer when these
707    values get unusually large.
708    
709    The maximum table size of 32 TB does not require large file support
710    from the operating system. Large tables are stored as multiple 1 GB
711    files so file system size limits are not important.
712    
713    The maximum table size and maximum number of columns can be quadrupled
714    by increasing the default block size to 32k.
715    
716     4.6) How much database disk space is required to store data from a typical
717     text file?
718     
719    A PostgreSQL database may require up to five times the disk space to
720    store data from a text file.
721    
722    As an example, consider a file of 100,000 lines with an integer and
723    text description on each line. Suppose the text string avergages
724    twenty bytes in length. The flat file would be 2.8 MB. The size of the
725    PostgreSQL database file containing this data can be estimated as 6.4
726    MB:
727     36 bytes: each row header (approximate)
728     24 bytes: one int field and one text field
729    + 4 bytes: pointer on page to tuple
730    ----------------------------------------
731     64 bytes per row
732
733    The data page size in PostgreSQL is 8192 bytes (8 KB), so:
734
735    8192 bytes per page
736    -------------------   =  128 rows per database page (rounded down)
737      64 bytes per row
738
739    100000 data rows
740    --------------------  =  782 database pages (rounded up)
741       128 rows per page
742
743 782 database pages * 8192 bytes per page  =  6,406,144 bytes (6.4 MB)
744
745    Indexes do not require as much overhead, but do contain the data that
746    is being indexed, so they can be large also.
747    
748    NULLs are stored as bitmaps, so they use very little space.
749    
750     4.7) How do I find out what tables, indexes, databases, and users are
751     defined?
752     
753    psql has a variety of backslash commands to show such information. Use
754    \? to see them. There are also system tables beginning with pg_ that
755    describe these too. Also, psql -l will list all databases.
756    
757    Also try the file pgsql/src/tutorial/syscat.source. It illustrates
758    many of the SELECTs needed to get information from the database system
759    tables.
760    
761     4.8) My queries are slow or don't make use of the indexes. Why?
762     
763    Indexes are not automatically used by every query. Indexes are only
764    used if the table is larger than a minimum size, and the query selects
765    only a small percentage of the rows in the table. This is because the
766    random disk access caused by an index scan can be slower than a
767    straight read through the table, or sequential scan.
768    
769    To determine if an index should be used, PostgreSQL must have
770    statistics about the table. These statistics are collected using
771    VACUUM ANALYZE, or simply ANALYZE. Using statistics, the optimizer
772    knows how many rows are in the table, and can better determine if
773    indexes should be used. Statistics are also valuable in determining
774    optimal join order and join methods. Statistics collection should be
775    performed periodically as the contents of the table change.
776    
777    Indexes are normally not used for ORDER BY or to perform joins. A
778    sequential scan followed by an explicit sort is usually faster than an
779    index scan of a large table.
780    However, LIMIT combined with ORDER BY often will use an index because
781    only a small portion of the table is returned. In fact, though MAX()
782    and MIN() don't use indexes, it is possible to retrieve such values
783    using an index with ORDER BY and LIMIT:
784     SELECT col
785     FROM tab
786     ORDER BY col [ DESC ]
787     LIMIT 1;
788
789    If you believe the optimizer is incorrect in choosing a sequential
790    scan, use SET enable_seqscan TO 'off' and run tests to see if an index
791    scan is indeed faster.
792    
793    When using wild-card operators such as LIKE or ~, indexes can only be
794    used in certain circumstances:
795      * The beginning of the search string must be anchored to the start
796        of the string, i.e.
797           + LIKE patterns must not start with %.
798           + ~ (regular expression) patterns must start with ^.
799      * The search string can not start with a character class, e.g.
800        [a-e].
801      * Case-insensitive searches such as ILIKE and ~* do not utilise
802        indexes. Instead, use functional indexes, which are described in
803        section 4.12.
804      * The default C locale must be used during initdb.
805        
806     4.9) How do I see how the query optimizer is evaluating my query?
807     
808    See the EXPLAIN manual page.
809    
810     4.10) What is an R-tree index?
811     
812    An R-tree index is used for indexing spatial data. A hash index can't
813    handle range searches. A B-tree index only handles range searches in a
814    single dimension. R-trees can handle multi-dimensional data. For
815    example, if an R-tree index can be built on an attribute of type
816    point, the system can more efficiently answer queries such as "select
817    all points within a bounding rectangle."
818    
819    The canonical paper that describes the original R-tree design is:
820    
821    Guttman, A. "R-trees: A Dynamic Index Structure for Spatial
822    Searching." Proceedings of the 1984 ACM SIGMOD Int'l Conf on Mgmt of
823    Data, 45-57.
824    
825    You can also find this paper in Stonebraker's "Readings in Database
826    Systems".
827    
828    Built-in R-trees can handle polygons and boxes. In theory, R-trees can
829    be extended to handle higher number of dimensions. In practice,
830    extending R-trees requires a bit of work and we don't currently have
831    any documentation on how to do it.
832    
833     4.11) What is the Genetic Query Optimizer?
834     
835    The GEQO module speeds query optimization when joining many tables by
836    means of a Genetic Algorithm (GA). It allows the handling of large
837    join queries through nonexhaustive search.
838    
839     4.12) How do I perform regular expression searches and case-insensitive
840     regular expression searches? How do I use an index for case-insensitive
841     searches?
842     
843    The ~ operator does regular expression matching, and ~* does
844    case-insensitive regular expression matching. The case-insensitive
845    variant of LIKE is called ILIKE.
846    
847    Case-insensitive equality comparisons are normally expressed as:
848     SELECT *
849     FROM tab
850     WHERE lower(col) = 'abc';
851
852    This will not use an standard index. However, if you create a
853    functional index, it will be used:
854     CREATE INDEX tabindex ON tab (lower(col));
855
856     4.13) In a query, how do I detect if a field is NULL?
857     
858    You test the column with IS NULL and IS NOT NULL.
859    
860     4.14) What is the difference between the various character types?
861     
862 Type            Internal Name   Notes
863 --------------------------------------------------
864 VARCHAR(n)      varchar         size specifies maximum length, no padding
865 CHAR(n)         bpchar          blank padded to the specified fixed length
866 TEXT            text            no specific upper limit on length
867 BYTEA           bytea           variable-length byte array (null-byte safe)
868 "char"          char            one character
869
870    You will see the internal name when examining system catalogs and in
871    some error messages.
872    
873    The first four types above are "varlena" types (i.e., the first four
874    bytes on disk are the length, followed by the data). Thus the actual
875    space used is slightly greater than the declared size. However, these
876    data types are also subject to compression or being stored out-of-line
877    by TOAST, so the space on disk might also be less than expected.
878    VARCHAR(n) is best when storing variable-length strings and it limits
879    how long a string can be. TEXT is for strings of unlimited length,
880    with a maximum of one gigabyte.
881    
882    CHAR(n) is for storing strings that are all the same length. CHAR(n)
883    pads with blanks to the specified length, while VARCHAR(n) only stores
884    the characters supplied. BYTEA is for storing binary data,
885    particularly values that include NULL bytes. All the types described
886    here have similar performance characteristics.
887    
888     4.15.1) How do I create a serial/auto-incrementing field?
889     
890    PostgreSQL supports a SERIAL data type. It auto-creates a sequence.
891    For example, this:
892     CREATE TABLE person (
893         id   SERIAL,
894         name TEXT
895     );
896
897    is automatically translated into this:
898     CREATE SEQUENCE person_id_seq;
899     CREATE TABLE person (
900         id   INT4 NOT NULL DEFAULT nextval('person_id_seq'),
901         name TEXT
902     );
903
904    See the create_sequence manual page for more information about
905    sequences. You can also use each row's OID field as a unique value.
906    However, if you need to dump and reload the database, you need to use
907    pg_dump's -o option or COPY WITH OIDS option to preserve the OIDs.
908    
909     4.15.2) How do I get the value of a SERIAL insert?
910     
911    One approach is to retrieve the next SERIAL value from the sequence
912    object with the nextval() function before inserting and then insert it
913    explicitly. Using the example table in 4.15.1, an example in a
914    pseudo-language would look like this:
915     new_id = execute("SELECT nextval('person_id_seq')");
916     execute("INSERT INTO person (id, name) VALUES (new_id, 'Blaise Pascal')");
917
918    You would then also have the new value stored in new_id for use in
919    other queries (e.g., as a foreign key to the person table). Note that
920    the name of the automatically created SEQUENCE object will be named
921    <table>_<serialcolumn>_seq, where table and serialcolumn are the names
922    of your table and your SERIAL column, respectively.
923    
924    Alternatively, you could retrieve the assigned SERIAL value with the
925    currval() function after it was inserted by default, e.g.,
926     execute("INSERT INTO person (name) VALUES ('Blaise Pascal')");
927     new_id = execute("SELECT currval('person_id_seq')");
928
929    Finally, you could use the OID returned from the INSERT statement to
930    look up the default value, though this is probably the least portable
931    approach, and the oid value will wrap around when it reaches 4
932    billion. In Perl, using DBI with Edmund Mergl's DBD::Pg module, the
933    oid value is made available via $sth->{pg_oid_status} after
934    $sth->execute().
935    
936     4.15.3) Don't currval() and nextval() lead to a race condition with other
937     users?
938     
939    No. currval() returns the current value assigned by your backend, not
940    by all users.
941    
942     4.15.4) Why aren't my sequence numbers reused on transaction abort? Why are
943     there gaps in the numbering of my sequence/SERIAL column?
944     
945    To improve concurrency, sequence values are given out to running
946    transactions as needed and are not locked until the transaction
947    completes. This causes gaps in numbering from aborted transactions.
948    
949     4.16) What is an OID? What is a TID?
950     
951    OIDs are PostgreSQL's answer to unique row ids. Every row that is
952    created in PostgreSQL gets a unique OID. All OIDs generated during
953    initdb are less than 16384 (from include/access/transam.h). All
954    user-created OIDs are equal to or greater than this. By default, all
955    these OIDs are unique not only within a table or database, but unique
956    within the entire PostgreSQL installation.
957    
958    PostgreSQL uses OIDs in its internal system tables to link rows
959    between tables. These OIDs can be used to identify specific user rows
960    and used in joins. It is recommended you use column type OID to store
961    OID values. You can create an index on the OID field for faster
962    access.
963    
964    OIDs are assigned to all new rows from a central area that is used by
965    all databases. If you want to change the OID to something else, or if
966    you want to make a copy of the table, with the original OIDs, there is
967    no reason you can't do it:
968         CREATE TABLE new_table(old_oid oid, mycol int);
969         SELECT old_oid, mycol INTO new FROM old;
970         COPY new TO '/tmp/pgtable';
971         DELETE FROM new;
972         COPY new WITH OIDS FROM '/tmp/pgtable';
973
974    OIDs are stored as 4-byte integers, and will overflow at 4 billion. No
975    one has reported this ever happening, and we plan to have the limit
976    removed before anyone does.
977    
978    TIDs are used to identify specific physical rows with block and offset
979    values. TIDs change after rows are modified or reloaded. They are used
980    by index entries to point to physical rows.
981    
982     4.17) What is the meaning of some of the terms used in PostgreSQL?
983     
984    Some of the source code and older documentation use terms that have
985    more common usage. Here are some:
986      * table, relation, class
987      * row, record, tuple
988      * column, field, attribute
989      * retrieve, select
990      * replace, update
991      * append, insert
992      * OID, serial value
993      * portal, cursor
994      * range variable, table name, table alias
995        
996    A list of general database terms can be found at:
997    http://hea-www.harvard.edu/MST/simul/software/docs/pkgs/pgsql/glossary
998    /glossary.html
999    
1000     4.18) Why do I get the error "ERROR: Memory exhausted in AllocSetAlloc()"?
1001     
1002    You probably have run out of virtual memory on your system, or your
1003    kernel has a low limit for certain resources. Try this before starting
1004    postmaster:
1005     ulimit -d 262144
1006     limit datasize 256m
1007
1008    Depending on your shell, only one of these may succeed, but it will
1009    set your process data segment limit much higher and perhaps allow the
1010    query to complete. This command applies to the current process, and
1011    all subprocesses created after the command is run. If you are having a
1012    problem with the SQL client because the backend is returning too much
1013    data, try it before starting the client.
1014    
1015     4.19) How do I tell what PostgreSQL version I am running?
1016     
1017    From psql, type SELECT version();
1018    
1019     4.20) Why does my large-object operations get "invalid large obj
1020     descriptor"?
1021     
1022    You need to put BEGIN WORK and COMMIT around any use of a large object
1023    handle, that is, surrounding lo_open ... lo_close.
1024    
1025    Currently PostgreSQL enforces the rule by closing large object handles
1026    at transaction commit. So the first attempt to do anything with the
1027    handle will draw invalid large obj descriptor. So code that used to
1028    work (at least most of the time) will now generate that error message
1029    if you fail to use a transaction.
1030    
1031    If you are using a client interface like ODBC you may need to set
1032    auto-commit off.
1033    
1034     4.21) How do I create a column that will default to the current time?
1035     
1036    Use CURRENT_TIMESTAMP:
1037 CREATE TABLE test (x int, modtime timestamp DEFAULT CURRENT_TIMESTAMP );
1038
1039     4.22) Why are my subqueries using IN so slow?
1040     
1041    In versions prior to 7.4, subqueries were joined to outer queries by
1042    sequentially scanning the result of the subquery for each row of the
1043    outer query. If the subquery returns only a few rows and the outer
1044    query returns many rows, IN is fastest. To speed up other queries,
1045    replace IN with EXISTS:
1046     SELECT *
1047     FROM tab
1048     WHERE col IN (SELECT subcol FROM subtab);
1049
1050    to:
1051     SELECT *
1052     FROM tab
1053     WHERE EXISTS (SELECT subcol FROM subtab WHERE subcol = col);
1054
1055    For this to be fast, subcol should be an indexed column.
1056    
1057    In version 7.4 and later, IN actually uses the same sophisticated join
1058    techniques as normal queries, and is prefered to using EXISTS.
1059    
1060     4.23) How do I perform an outer join?
1061     
1062    PostgreSQL supports outer joins using the SQL standard syntax. Here
1063    are two examples:
1064     SELECT *
1065     FROM t1 LEFT OUTER JOIN t2 ON (t1.col = t2.col);
1066
1067    or
1068     SELECT *
1069     FROM t1 LEFT OUTER JOIN t2 USING (col);
1070
1071    These identical queries join t1.col to t2.col, and also return any
1072    unjoined rows in t1 (those with no match in t2). A RIGHT join would
1073    add unjoined rows of t2. A FULL join would return the matched rows
1074    plus all unjoined rows from t1 and t2. The word OUTER is optional and
1075    is assumed in LEFT, RIGHT, and FULL joins. Ordinary joins are called
1076    INNER joins.
1077    
1078    In previous releases, outer joins can be simulated using UNION and NOT
1079    IN. For example, when joining tab1 and tab2, the following query does
1080    an outer join of the two tables:
1081     SELECT tab1.col1, tab2.col2
1082     FROM tab1, tab2
1083     WHERE tab1.col1 = tab2.col1
1084     UNION ALL
1085     SELECT tab1.col1, NULL
1086     FROM tab1
1087     WHERE tab1.col1 NOT IN (SELECT tab2.col1 FROM tab2)
1088     ORDER BY col1
1089
1090     4.24) How do I perform queries using multiple databases?
1091     
1092    There is no way to query a database other than the current one.
1093    Because PostgreSQL loads database-specific system catalogs, it is
1094    uncertain how a cross-database query should even behave.
1095    
1096    contrib/dblink allows cross-database queries using function calls. Of
1097    course, a client can make simultaneous connections to different
1098    databases and merge the results on the client side.
1099    
1100     4.25) How do I return multiple rows or columns from a function?
1101     
1102    In 7.3, you can easily return multiple rows or columns from a
1103    function, http://techdocs.postgresql.org/guides/SetReturningFunctions.
1104    
1105     4.26) Why can't I reliably create/drop temporary tables in PL/PgSQL
1106     functions?
1107     
1108    PL/PgSQL caches function contents, and an unfortunate side effect is
1109    that if a PL/PgSQL function accesses a temporary table, and that table
1110    is later dropped and recreated, and the function called again, the
1111    function will fail because the cached function contents still point to
1112    the old temporary table. The solution is to use EXECUTE for temporary
1113    table access in PL/PgSQL. This will cause the query to be reparsed
1114    every time.
1115    
1116     4.27) What replication options are available?
1117     
1118    There are several master/slave replication options available. These
1119    allow only the master to make database changes and the slave can only
1120    do database reads. The bottom of
1121    http://gborg.PostgreSQL.org/genpage?replication_research lists them. A
1122    multi-master replication solution is being worked on at
1123    http://gborg.PostgreSQL.org/project/pgreplication/projdisplay.php.
1124    
1125     4.28) What encryption options are available?
1126     
1127      * contrib/pgcrypto contains many encryption functions for use in SQL
1128        queries.
1129      * To encrypt transmission from the client to the server, the server
1130        must have the ssl option set to true in postgresql.conf, and an
1131        applicable host or hostssl record must exist in pg_hba.conf, and
1132        the client sslmode must not be disable. (Note that it is also
1133        possible to use a third-party encrypted transport, such as stunnel
1134        or ssh, rather than PostgreSQL's native SSL connections.)
1135      * Database user passwords are automatically encrypted when stored in
1136        version 7.3. In previous versions, you must enable the option
1137        PASSWORD_ENCRYPTION in postgresql.conf.
1138      * The server can run using an encrypted file system.
1139      _________________________________________________________________
1140    
1141                             Extending PostgreSQL
1142                                       
1143     5.1) I wrote a user-defined function. When I run it in psql, why does it
1144     dump core?
1145     
1146    The problem could be a number of things. Try testing your user-defined
1147    function in a stand-alone test program first.
1148    
1149     5.2) How can I contribute some nifty new types and functions to PostgreSQL?
1150     
1151    Send your extensions to the pgsql-hackers mailing list, and they will
1152    eventually end up in the contrib/ subdirectory.
1153    
1154     5.3) How do I write a C function to return a tuple?
1155     
1156    In versions of PostgreSQL beginning with 7.3, table-returning
1157    functions are fully supported in C, PL/PgSQL, and SQL. See the
1158    Programmer's Guide for more information. An example of a
1159    table-returning function defined in C can be found in
1160    contrib/tablefunc.
1161    
1162     5.4) I have changed a source file. Why does the recompile not see the
1163     change?
1164     
1165    The Makefiles do not have the proper dependencies for include files.
1166    You have to do a make clean and then another make. If you are using
1167    GCC you can use the --enable-depend option of configure to have the
1168    compiler compute the dependencies automatically.