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