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