]> granicus.if.org Git - postgresql/blob - doc/FAQ
Implement SEMI and ANTI joins in the planner and executor. (Semijoins replace
[postgresql] / doc / FAQ
1
2                 Frequently Asked Questions (FAQ) for PostgreSQL
3                                        
4    Last updated: Wed Jun 25 23:54:14 EDT 2008
5    
6    Current maintainer: Bruce Momjian (bruce@momjian.us)
7    
8    The most recent version of this document can be viewed at
9    http://www.postgresql.org/files/documentation/faqs/FAQ.html.
10    
11    Platform-specific questions are answered at
12    http://www.postgresql.org/docs/faq/.
13      _________________________________________________________________
14    
15                              General Questions
16                                       
17    1.1) What is PostgreSQL? How is it pronounced? What is Postgres?
18    1.2) Who controls PostgreSQL?
19    1.3) What is the copyright of PostgreSQL?
20    1.4) What platforms does PostgreSQL support?
21    1.5) Where can I get PostgreSQL?
22    1.6) What is the most recent release?
23    1.7) Where can I get support?
24    1.8) How do I submit a bug report?
25    1.9) How do I find out about known bugs or missing features?
26    1.10) What documentation is available?
27    1.11) How can I learn SQL?
28    1.12) How do I submit a patch or join the development team?
29    1.13) How does PostgreSQL compare to other DBMSs? Can PostgreSQL be
30    embedded?
31    1.14) Will PostgreSQL handle recent daylight saving time changes in
32    various countries?
33    1.15) How do I unsubscribe from the PostgreSQL email lists? How do I
34    avoid receiving duplicate emails?
35    
36                            User Client Questions
37                                       
38    2.1) What interfaces are available for PostgreSQL?
39    2.2) What tools are available for using PostgreSQL with Web pages?
40    2.3) Does PostgreSQL have a graphical user interface?
41    
42                           Administrative Questions
43                                       
44    3.1) How do I install PostgreSQL somewhere other than
45    /usr/local/pgsql?
46    3.2) How do I control connections from other hosts?
47    3.3) How do I tune the database engine for better performance?
48    3.4) What debugging features are available?
49    3.5) Why do I get "Sorry, too many clients" when trying to connect?
50    3.6 What is the upgrade process for PostgreSQL?
51    3.7) What computer hardware should I use?
52    
53                            Operational Questions
54                                       
55    4.1) How do I SELECT only the first few rows of a query? A random row?
56    4.2) How do I find out what tables, indexes, databases, and users are
57    defined? How do I see the queries used by psql to display them?
58    4.3) How do you change a column's data type?
59    4.4) What is the maximum size for a row, a table, and a database?
60    4.5) How much database disk space is required to store data from a
61    typical text file?
62    4.6) Why are my queries slow? Why don't they use my indexes?
63    4.7) How do I see how the query optimizer is evaluating my query?
64    4.8) How do I perform regular expression searches and case-insensitive
65    regular expression searches? How do I use an index for
66    case-insensitive searches?
67    4.9) In a query, how do I detect if a field is NULL? How do I
68    concatenate possible NULLs? How can I sort on whether a field is NULL
69    or not?
70    4.10) What is the difference between the various character types?
71    4.11.1) How do I create a serial/auto-incrementing field?
72    4.11.2) How do I get the value of a SERIAL insert?
73    4.11.3) Doesn't currval() lead to a race condition with other users?
74    4.11.4) Why aren't my sequence numbers reused on transaction abort?
75    Why are there gaps in the numbering of my sequence/SERIAL column?
76    4.12) What is an OID? What is a CTID?
77    4.13) Why do I get the error "ERROR: Memory exhausted in
78    AllocSetAlloc()"?
79    4.14) How do I tell what PostgreSQL version I am running?
80    4.15) How do I create a column that will default to the current time?
81    4.16) How do I perform an outer join?
82    4.17) How do I perform queries using multiple databases?
83    4.18) How do I return multiple rows or columns from a function?
84    4.19) Why do I get "relation with OID ##### does not exist" errors
85    when accessing temporary tables in PL/PgSQL functions?
86    4.20) What replication solutions are available?
87    4.21) Why are my table and column names not recognized in my query?
88    Why is capitalization not preserved?
89      _________________________________________________________________
90    
91                              General Questions
92                                       
93   1.1) What is PostgreSQL? How is it pronounced? What is Postgres?
94   
95    PostgreSQL is pronounced Post-Gres-Q-L. (For those curious about how
96    to say "PostgreSQL", an audio file is available.)
97    
98    PostgreSQL is an object-relational database system that has the
99    features of traditional commercial database systems with enhancements
100    to be found in next-generation DBMS systems. PostgreSQL is free and
101    the complete source code is available.
102    
103    PostgreSQL development is performed by a team of mostly volunteer
104    developers spread throughout the world and communicating via the
105    Internet. It is a community project and is not controlled by any
106    company. To get involved, see the developer's FAQ at
107    http://www.postgresql.org/docs/faqs.FAQ_DEV.html
108    
109    Postgres is a widely-used nickname for PostgreSQL. It was the original
110    name of the project at Berkeley and is strongly preferred over other
111    nicknames. If you find 'PostgreSQL' hard to pronounce, call it
112    'Postgres' instead.
113    
114   1.2) Who controls PostgreSQL?
115   
116    If you are looking for a PostgreSQL gatekeeper, central committee, or
117    controlling company, give up --- there isn't one. We do have a core
118    committee and CVS committers, but these groups are more for
119    administrative purposes than control. The project is directed by the
120    community of developers and users, which anyone can join. All you need
121    to do is subscribe to the mailing lists and participate in the
122    discussions. (See the Developer's FAQ for information on how to get
123    involved in PostgreSQL development.)
124    
125   1.3) What is the copyright of PostgreSQL?
126   
127    PostgreSQL is distributed under the classic BSD license. Basically, it
128    allows users to do anything they want with the code, including
129    reselling binaries without the source code. The only restriction is
130    that you not hold us legally liable for problems with the software.
131    There is also the requirement that this copyright appear in all copies
132    of the software. Here is the actual BSD license we use:
133    
134    PostgreSQL Data Base Management System
135    
136    Portions Copyright (c) 1996-2008, PostgreSQL Global Development Group
137    Portions Copyright (c) 1994-1996 Regents of the University of
138    California
139    
140    Permission to use, copy, modify, and distribute this software and its
141    documentation for any purpose, without fee, and without a written
142    agreement is hereby granted, provided that the above copyright notice
143    and this paragraph and the following two paragraphs appear in all
144    copies.
145    
146    IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY
147    FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
148    INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND
149    ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF CALIFORNIA HAS BEEN
150    ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
151    
152    THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
153    INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
154    MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE
155    PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF
156    CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,
157    UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
158    
159   1.4) What platforms does PostgreSQL support?
160   
161    In general, any modern Unix-compatible platform should be able to run
162    PostgreSQL. The platforms that had received explicit testing at the
163    time of release are listed in the installation instructions.
164    
165    PostgreSQL also runs natively on Microsoft Windows NT-based operating
166    systems like Win2000 SP4, WinXP, and Win2003. A prepackaged installer
167    is available at http://www.postgresql.org/download/windows.
168    MSDOS-based versions of Windows (Win95, Win98, WinMe) can run
169    PostgreSQL using Cygwin.
170    
171    There is also a Novell Netware 6 port at
172    http://developer.novell.com/wiki/index.php/Postgresql, and an OS/2
173    (eComStation) version at
174    http://hobbes.nmsu.edu/cgi-bin/h-search?sh=1&button=Search&key=postgre
175    SQL&stype=all&sort=type&dir=%2F.
176    
177   1.5) Where can I get PostgreSQL?
178   
179    Via web browser, use http://www.postgresql.org/ftp/, and via ftp, use
180    ftp://ftp.postgresql.org/pub/.
181    
182   1.6) What is the most recent release?
183   
184    The latest release of PostgreSQL is version 8.3.3.
185    
186    We plan to have a major release every year, with minor releases every
187    few months.
188    
189   1.7) Where can I get support?
190   
191    The PostgreSQL community provides assistance to many of its users via
192    email. The main web site to subscribe to the email lists is
193    http://www.postgresql.org/community/lists/. The general or bugs lists
194    are a good place to start.
195    
196    The major IRC channel is #postgresql on Freenode (irc.freenode.net).
197    To connect you can use the Unix program irc -c '#postgresql' "$USER"
198    irc.freenode.net or use any other IRC clients. A Spanish one also
199    exists on the same network, (#postgresql-es), a French one,
200    (#postgresqlfr), and a Brazilian one, (#postgresql-br). There is also
201    a PostgreSQL channel on EFNet.
202    
203    A list of commercial support companies is available at
204    http://www.postgresql.org/support/professional_support.
205    
206   1.8) How do I submit a bug report?
207   
208    Visit the PostgreSQL bug form at
209    http://www.postgresql.org/support/submitbug. Also check out our ftp
210    site ftp://ftp.postgresql.org/pub/ to see if there is a more recent
211    PostgreSQL version.
212    
213    Bugs submitted using the bug form or posted to any PostgreSQL mailing
214    list typically generates one of the following replies:
215      * It is not a bug, and why
216      * It is a known bug and is already on the TODO list
217      * The bug has been fixed in the current release
218      * The bug has been fixed but is not packaged yet in an official
219        release
220      * A request is made for more detailed information:
221           + Operating system
222           + PostgreSQL version
223           + Reproducible test case
224           + Debugging information
225           + Debugger backtrace output
226      * The bug is new. The following might happen:
227           + A patch is created and will be included in the next major or
228             minor release
229           + The bug cannot be fixed immediately and is added to the TODO
230             list
231        
232   1.9) How do I find out about known bugs or missing features?
233   
234    PostgreSQL supports an extended subset of SQL:2003. See our TODO list
235    for known bugs, missing features, and future plans.
236    
237    A feature request usually results in one of the following replies:
238      * The feature is already on the TODO list
239      * The feature is not desired because:
240           + It duplicates existing functionality that already follows the
241             SQL standard
242           + The feature would increase code complexity but add little
243             benefit
244           + The feature would be insecure or unreliable
245      * The new feature is added to the TODO list
246        
247    PostgreSQL does not use a bug tracking system because we find it more
248    efficient to respond directly to email and keep the TODO list
249    up-to-date. In practice, bugs don't last very long in the software,
250    and bugs that affect a large number of users are fixed rapidly. The
251    only place to find all changes, improvements, and fixes in a
252    PostgreSQL release is to read the CVS log messages. Even the release
253    notes do not list every change made to the software.
254    
255   1.10) What documentation is available?
256   
257    PostgreSQL includes extensive documentation, including a large manual,
258    manual pages, and some test examples. See the /doc directory. You can
259    also browse the manuals online at http://www.postgresql.org/docs.
260    
261    There are two PostgreSQL books available online at
262    http://www.postgresql.org/docs/books/awbook.html and
263    http://www.commandprompt.com/ppbook/. There are a number of PostgreSQL
264    books available for purchase. One of the most popular ones is by Korry
265    Douglas. A list of book reviews can be found at
266    http://www.postgresql.org/docs/books/. There is also a collection of
267    PostgreSQL technical articles at
268    http://wiki.postgresql.org/wiki/Community_Generated_Articles%2C_Guides
269    %2C_and_Documentation.
270    
271    The command line client program psql has some \d commands to show
272    information about types, operators, functions, aggregates, etc. - use
273    \? to display the available commands.
274    
275    Our web site contains even more documentation.
276    
277   1.11) How can I learn SQL?
278   
279    First, consider the PostgreSQL-specific books mentioned above. Many of
280    our users also like The Practical SQL Handbook, Bowman, Judith S., et
281    al., Addison-Wesley. Others like The Complete Reference SQL, Groff et
282    al., McGraw-Hill.
283    
284    There are also many nice tutorials available online:
285      * http://www.intermedia.net/support/sql/sqltut.shtm
286      * http://sqlcourse.com
287      * http://www.w3schools.com/sql/default.asp
288      * http://mysite.verizon.net/Graeme_Birchall/id1.html
289        
290   1.12) How do I submit a patch or join the development team?
291   
292    See the Developer's FAQ.
293    
294   1.13) How does PostgreSQL compare to other DBMSs? Can PostgreSQL be embedded?
295   
296    There are several ways of measuring software: features, performance,
297    reliability, support, and price.
298    
299    Features
300           PostgreSQL has most features present in large commercial DBMSs,
301           like transactions, subselects, triggers, views, foreign key
302           referential integrity, and sophisticated locking. We have some
303           features they do not have, like user-defined types,
304           inheritance, rules, and multi-version concurrency control to
305           reduce lock contention.
306           
307    Performance
308           PostgreSQL's performance is comparable to other commercial and
309           open source databases. It is faster for some things, slower for
310           others. Our performance is usually +/-10% compared to other
311           databases.
312           
313    Reliability
314           We realize that a DBMS must be reliable, or it is worthless. We
315           strive to release well-tested, stable code that has a minimum
316           of bugs. Each release has at least one month of beta testing,
317           and our release history shows that we can provide stable, solid
318           releases that are ready for production use. We believe we
319           compare favorably to other database software in this area.
320           
321    Support
322           Our mailing lists provide contact with a large group of
323           developers and users to help resolve any problems encountered.
324           While we cannot guarantee a fix, commercial DBMSs do not always
325           supply a fix either. Direct access to developers, the user
326           community, manuals, and the source code often make PostgreSQL
327           support superior to other DBMSs. There is commercial
328           per-incident support available for those who need it. (See FAQ
329           section 1.7.)
330           
331    Price
332           We are free for all use, both commercial and non-commercial.
333           You can add our code to your product with no limitations,
334           except those outlined in our BSD-style license stated above.
335           
336    PostgreSQL is designed as a client/server architecture, which requires
337    separate processes for each client and server, and various helper
338    processes. Many embedded architectures can support such requirements.
339    However, if your embedded architecture requires the database server to
340    run inside the application process, you cannot use Postgres and should
341    select a lighter-weight database solution.
342    
343   1.14) Will PostgreSQL handle recent daylight saving time changes in various
344   countries?
345   
346    USA daylight saving time changes are included in PostgreSQL release
347    8.0.[4+], and all later major releases, e.g. 8.1. Canada and Western
348    Australia changes are included in 8.0.[10+], 8.1.[6+], and all later
349    major releases. PostgreSQL releases prior to 8.0 use the operating
350    system's timezone database for daylight saving information.
351    
352   1.15) How do I unsubscribe from the PostgreSQL email lists? How do I avoid
353   receiving duplicate emails?
354   
355    The PostgreSQL Majordomo page allows subscribing or unsubscribing from
356    any of the PostgreSQL email lists. (You might need to have your
357    Majordomo password emailed to you to log in.)
358    
359    All PostgreSQL email lists are configured so a group reply goes to the
360    email list and the original email author. This is done so users
361    receive the quickest possible email replies. If you would prefer not
362    to receive duplicate email from the list in cases where you already
363    receive an email directly, check eliminatecc from the Majordomo Change
364    Settings page. You can also prevent yourself from receiving copies of
365    emails you post to the lists by unchecking selfcopy.
366      _________________________________________________________________
367    
368                            User Client Questions
369                                       
370   2.1) What interfaces are available for PostgreSQL?
371   
372    The PostgreSQL install includes only the C and embedded C interfaces.
373    All other interfaces are independent projects that are downloaded
374    separately; being separate allows them to have their own release
375    schedule and development teams.
376    
377    Some programming languages like PHP include an interface to
378    PostgreSQL. Interfaces for languages like Perl, TCL, Python, and many
379    others are available at http://pgfoundry.org.
380    
381   2.2) What tools are available for using PostgreSQL with Web pages?
382   
383    A nice introduction to Database-backed Web pages can be seen at:
384    http://www.webreview.com
385    
386    For Web integration, PHP (http://www.php.net) is an excellent
387    interface.
388    
389    For complex cases, many use the Perl and DBD::Pg with CGI.pm or
390    mod_perl.
391    
392   2.3) Does PostgreSQL have a graphical user interface?
393   
394    There are a large number of GUI Tools that are available for
395    PostgreSQL from both commercial and open source developers. A detailed
396    list can be found in the Community Guide to PostgreSQL GUI Tools.
397      _________________________________________________________________
398    
399                           Administrative Questions
400                                       
401   3.1) How do I install PostgreSQL somewhere other than /usr/local/pgsql?
402   
403    Specify the --prefix option when running configure.
404    
405   3.2) How do I control connections from other hosts?
406   
407    By default, PostgreSQL only allows connections from the local machine
408    using Unix domain sockets or TCP/IP connections. Other machines will
409    not be able to connect unless you modify listen_addresses in the
410    postgresql.conf file, enable host-based authentication by modifying
411    the $PGDATA/pg_hba.conf file, and restart the database server.
412    
413   3.3) How do I tune the database engine for better performance?
414   
415    There are three major areas for potential performance improvement:
416    
417    Query Changes
418           This involves modifying queries to obtain better performance:
419           
420           + Creation of indexes, including expression and partial indexes
421           + Use of COPY instead of multiple INSERTs
422           + Grouping of multiple statements into a single transaction to
423             reduce commit overhead
424           + Use of CLUSTER when retrieving many rows from an index
425           + Use of LIMIT for returning a subset of a query's output
426           + Use of Prepared queries
427           + Use of ANALYZE to maintain accurate optimizer statistics
428           + Regular use of VACUUM or pg_autovacuum
429           + Dropping of indexes during large data changes
430             
431    Server Configuration
432           A number of postgresql.conf settings affect performance. For
433           more details, see Administration Guide/Server Run-time
434           Environment/Run-time Configuration for a full listing, and for
435           commentary see
436           http://www.varlena.com/varlena/GeneralBits/Tidbits/annotated_co
437           nf_e.html and
438           http://www.varlena.com/varlena/GeneralBits/Tidbits/perf.html.
439           
440    Hardware Selection
441           The effect of hardware on performance is detailed in
442           http://www.powerpostgresql.com/PerfList/ and
443           http://momjian.us/main/writings/pgsql/hw_performance/index.html
444           .
445           
446   3.4) What debugging features are available?
447   
448    There are many log_* server configuration variables at
449    http://www.postgresql.org/docs/current/interactive/runtime-config-logg
450    ing.html that enable printing of query and process statistics which
451    can be very useful for debugging and performance measurements.
452    
453   3.5) Why do I get "Sorry, too many clients" when trying to connect?
454   
455    You have reached the default limit of 100 database sessions. You need
456    to increase the server's limit on how many concurrent backend
457    processes it can start by changing the max_connections value in
458    postgresql.conf and restarting the server.
459    
460   3.6) What is the upgrade process for PostgreSQL?
461   
462    See http://www.postgresql.org/support/versioning for a general
463    discussion about upgrading, and
464    http://www.postgresql.org/docs/current/static/install-upgrading.html
465    for specific instructions.
466    
467   3.7) What computer hardware should I use?
468   
469    Because PC hardware is mostly compatible, people tend to believe that
470    all PC hardware is of equal quality. It is not. ECC RAM, SCSI, and
471    quality motherboards are more reliable and have better performance
472    than less expensive hardware. PostgreSQL will run on almost any
473    hardware, but if reliability and performance are important it is wise
474    to research your hardware options thoroughly. Our email lists can be
475    used to discuss hardware options and tradeoffs.
476      _________________________________________________________________
477    
478                            Operational Questions
479                                       
480   4.1) How do I SELECT only the first few rows of a query? A random row?
481   
482    To retrieve only a few rows, if you know at the number of rows needed
483    at the time of the SELECT use LIMIT . If an index matches the ORDER BY
484    it is possible the entire query does not have to be executed. If you
485    don't know the number of rows at SELECT time, use a cursor and FETCH.
486    
487    To SELECT a random row, use:
488     SELECT col
489     FROM tab
490     ORDER BY random()
491     LIMIT 1;
492
493   4.2) How do I find out what tables, indexes, databases, and users are
494   defined? How do I see the queries used by psql to display them?
495   
496    Use the \dt command to see tables in psql. For a complete list of
497    commands inside psql you can use \?. Alternatively you can read the
498    source code for psql in file pgsql/src/bin/psql/describe.c, it
499    contains SQL commands that generate the output for psql's backslash
500    commands. You can also start psql with the -E option so it will print
501    out the queries it uses to execute the commands you give. PostgreSQL
502    also provides an SQL compliant INFORMATION SCHEMA interface you can
503    query to get information about the database.
504    
505    There are also system tables beginning with pg_ that describe these
506    too.
507    
508    Use psql -l will list all databases.
509    
510    Also try the file pgsql/src/tutorial/syscat.source. It illustrates
511    many of the SELECTs needed to get information from the database system
512    tables.
513    
514   4.3) How do you change a column's data type?
515   
516    Changing the data type of a column can be done easily in 8.0 and later
517    with ALTER TABLE ALTER COLUMN TYPE.
518    
519    In earlier releases, do this:
520     BEGIN;
521     ALTER TABLE tab ADD COLUMN new_col new_data_type;
522     UPDATE tab SET new_col = CAST(old_col AS new_data_type);
523     ALTER TABLE tab DROP COLUMN old_col;
524     COMMIT;
525
526    You might then want to do VACUUM FULL tab to reclaim the disk space
527    used by the expired rows.
528    
529   4.4) What is the maximum size for a row, a table, and a database?
530   
531    These are the limits:
532    
533    Maximum size for a database? unlimited (32 TB databases exist)
534    Maximum size for a table? 32 TB
535    Maximum size for a row? 400 GB
536    Maximum size for a field? 1 GB
537    Maximum number of rows in a table? unlimited
538    Maximum number of columns in a table? 250-1600 depending on column
539    types
540    Maximum number of indexes on a table? unlimited
541    
542    Of course, these are not actually unlimited, but limited to available
543    disk space and memory/swap space. Performance may suffer when these
544    values get unusually large.
545    
546    The maximum table size of 32 TB does not require large file support
547    from the operating system. Large tables are stored as multiple 1 GB
548    files so file system size limits are not important.
549    
550    The maximum table size, row size, and maximum number of columns can be
551    quadrupled by increasing the default block size to 32k. The maximum
552    table size can also be increased using table partitioning.
553    
554    One limitation is that indexes can not be created on columns longer
555    than about 2,000 characters. Fortunately, such indexes are rarely
556    needed. Uniqueness is best guaranteed by a function index of an MD5
557    hash of the long column, and full text indexing allows for searching
558    of words within the column.
559    
560   4.5) How much database disk space is required to store data from a typical
561   text file?
562   
563    A PostgreSQL database may require up to five times the disk space to
564    store data from a text file.
565    
566    As an example, consider a file of 100,000 lines with an integer and
567    text description on each line. Suppose the text string avergages
568    twenty bytes in length. The flat file would be 2.8 MB. The size of the
569    PostgreSQL database file containing this data can be estimated as 5.2
570    MB:
571     24 bytes: each row header (approximate)
572     24 bytes: one int field and one text field
573    + 4 bytes: pointer on page to tuple
574    ----------------------------------------
575     52 bytes per row
576
577    The data page size in PostgreSQL is 8192 bytes (8 KB), so:
578
579    8192 bytes per page
580    -------------------   =  158 rows per database page (rounded down)
581      52 bytes per row
582
583    100000 data rows
584    --------------------  =  633 database pages (rounded up)
585       158 rows per page
586
587 633 database pages * 8192 bytes per page  =  5,185,536 bytes (5.2 MB)
588
589    Indexes do not require as much overhead, but do contain the data that
590    is being indexed, so they can be large also.
591    
592    NULLs are stored as bitmaps, so they use very little space.
593    
594   4.6) Why are my queries slow? Why don't they use my indexes?
595   
596    Indexes are not used by every query. Indexes are used only if the
597    table is larger than a minimum size, and the query selects only a
598    small percentage of the rows in the table. This is because the random
599    disk access caused by an index scan can be slower than a straight read
600    through the table, or sequential scan.
601    
602    To determine if an index should be used, PostgreSQL must have
603    statistics about the table. These statistics are collected using
604    VACUUM ANALYZE, or simply ANALYZE. Using statistics, the optimizer
605    knows how many rows are in the table, and can better determine if
606    indexes should be used. Statistics are also valuable in determining
607    optimal join order and join methods. Statistics collection should be
608    performed periodically as the contents of the table change.
609    
610    Indexes are normally not used for ORDER BY or to perform joins. A
611    sequential scan followed by an explicit sort is usually faster than an
612    index scan of a large table. However, LIMIT combined with ORDER BY
613    often will use an index because only a small portion of the table is
614    returned.
615    
616    If you believe the optimizer is incorrect in choosing a sequential
617    scan, use SET enable_seqscan TO 'off' and run query again to see if an
618    index scan is indeed faster.
619    
620    When using wild-card operators such as LIKE or ~, indexes can only be
621    used in certain circumstances:
622      * The beginning of the search string must be anchored to the start
623        of the string, i.e.
624           + LIKE patterns must not start with %.
625           + ~ (regular expression) patterns must start with ^.
626      * The search string can not start with a character class, e.g.
627        [a-e].
628      * Case-insensitive searches such as ILIKE and ~* do not utilize
629        indexes. Instead, use expression indexes, which are described in
630        section 4.8.
631      * The default C locale must be used during initdb because it is not
632        possible to know the next-greatest character in a non-C locale.
633        You can create a special text_pattern_ops index for such cases
634        that work only for LIKE indexing. It is also possible to use full
635        text indexing for word searches.
636        
637   4.7) How do I see how the query optimizer is evaluating my query?
638   
639    See the EXPLAIN manual page.
640    
641   4.8) How do I perform regular expression searches and case-insensitive
642   regular expression searches? How do I use an index for case-insensitive
643   searches?
644   
645    The ~ operator does regular expression matching, and ~* does
646    case-insensitive regular expression matching. The case-insensitive
647    variant of LIKE is called ILIKE.
648    
649    Case-insensitive equality comparisons are normally expressed as:
650     SELECT *
651     FROM tab
652     WHERE lower(col) = 'abc';
653
654    This will not use an standard index. However, if you create an
655    expression index, it will be used:
656     CREATE INDEX tabindex ON tab (lower(col));
657
658    If the above index is created as UNIQUE, though the column can store
659    upper and lowercase characters, it can not have identical values that
660    differ only in case. To force a particular case to be stored in the
661    column, use a CHECK constraint or a trigger.
662    
663   4.9) In a query, how do I detect if a field is NULL? How do I concatenate
664   possible NULLs? How can I sort on whether a field is NULL or not?
665   
666    You test the column with IS NULL and IS NOT NULL, like this:
667    SELECT *
668    FROM tab
669    WHERE col IS NULL;
670
671    To concatentate with possible NULLs, use COALESCE(), like this:
672    SELECT COALESCE(col1, '') || COALESCE(col2, '')
673    FROM tab
674
675    To sort by the NULL status, use the IS NULL and IS NOT NULL modifiers
676    in your ORDER BY clause. Things that are true will sort higher than
677    things that are false, so the following will put NULL entries at the
678    top of the resulting list:
679    SELECT *
680    FROM tab
681    ORDER BY (col IS NOT NULL)
682
683   4.10) What is the difference between the various character types?
684   
685         Type    Internal Name                    Notes
686      VARCHAR(n) varchar       size specifies maximum length, no padding
687      CHAR(n)    bpchar        blank padded to the specified fixed length
688      TEXT       text          no specific upper limit on length
689      BYTEA      bytea         variable-length byte array (null-byte safe)
690      "char"     char          one character
691    
692    You will see the internal name when examining system catalogs and in
693    some error messages.
694    
695    The first four types above are "varlena" types (i.e., the first four
696    bytes on disk are the length, followed by the data). Thus the actual
697    space used is slightly greater than the declared size. However, long
698    values are also subject to compression, so the space on disk might
699    also be less than expected.
700    VARCHAR(n) is best when storing variable-length strings and it limits
701    how long a string can be. TEXT is for strings of unlimited length,
702    with a maximum of one gigabyte.
703    
704    CHAR(n) is for storing strings that are all the same length. CHAR(n)
705    pads with blanks to the specified length, while VARCHAR(n) only stores
706    the characters supplied. BYTEA is for storing binary data,
707    particularly values that include NULL bytes. All the types described
708    here have similar performance characteristics.
709    
710   4.11.1) How do I create a serial/auto-incrementing field?
711   
712    PostgreSQL supports a SERIAL data type. It auto-creates a sequence.
713    For example, this:
714     CREATE TABLE person (
715         id   SERIAL,
716         name TEXT
717     );
718
719    is automatically translated into this:
720     CREATE SEQUENCE person_id_seq;
721     CREATE TABLE person (
722         id   INT4 NOT NULL DEFAULT nextval('person_id_seq'),
723         name TEXT
724     );
725
726    Automatically created sequence are named <table>_<serialcolumn>_seq,
727    where table and serialcolumn are the names of the table and SERIAL
728    column, respectively. See the create_sequence manual page for more
729    information about sequences.
730    
731   4.11.2) How do I get the value of a SERIAL insert?
732   
733    The simplest way is to retrieve the assigned SERIAL value with
734    RETURNING. Using the example table in 4.11.1, it would look like this:
735     INSERT INTO person (name) VALUES ('Blaise Pascal') RETURNING id;
736
737    You can also call nextval() and use that value in the INSERT, or call
738    currval() after the INSERT.
739    
740   4.11.3) Doesn't currval() lead to a race condition with other users?
741   
742    No. currval() returns the current value assigned by your session, not
743    by all sessions.
744    
745   4.11.4) Why aren't my sequence numbers reused on transaction abort? Why are
746   there gaps in the numbering of my sequence/SERIAL column?
747   
748    To improve concurrency, sequence values are given out to running
749    transactions as needed and are not locked until the transaction
750    completes. This causes gaps in numbering from aborted transactions.
751    
752   4.12) What is an OID? What is a CTID?
753   
754    If a table is created WITH OIDS, each row gets a unique a OID. OIDs
755    are automatically assigned unique 4-byte integers that are unique
756    across the entire installation. However, they overflow at 4 billion,
757    and then the OIDs start being duplicated. PostgreSQL uses OIDs to link
758    its internal system tables together.
759    
760    To uniquely number rows in user tables, it is best to use SERIAL
761    rather than OIDs because SERIAL sequences are unique only within a
762    single table. and are therefore less likely to overflow. SERIAL8 is
763    available for storing eight-byte sequence values.
764    
765    CTIDs are used to identify specific physical rows with block and
766    offset values. CTIDs change after rows are modified or reloaded. They
767    are used by index entries to point to physical rows.
768    
769   4.13) Why do I get the error "ERROR: Memory exhausted in AllocSetAlloc()"?
770   
771    You probably have run out of virtual memory on your system, or your
772    kernel has a low limit for certain resources. Try this before starting
773    the server:
774     ulimit -d 262144
775     limit datasize 256m
776
777    Depending on your shell, only one of these may succeed, but it will
778    set your process data segment limit much higher and perhaps allow the
779    query to complete. This command applies to the current process, and
780    all subprocesses created after the command is run. If you are having a
781    problem with the SQL client because the backend is returning too much
782    data, try it before starting the client.
783    
784   4.14) How do I tell what PostgreSQL version I am running?
785   
786    From psql, type SELECT version();
787    
788   4.15) How do I create a column that will default to the current time?
789   
790    Use CURRENT_TIMESTAMP:
791     CREATE TABLE test (x int, modtime TIMESTAMP DEFAULT CURRENT_TIMESTAMP );
792
793   4.16) How do I perform an outer join?
794   
795    PostgreSQL supports outer joins using the SQL standard syntax. Here
796    are two examples:
797     SELECT *
798     FROM t1 LEFT OUTER JOIN t2 ON (t1.col = t2.col);
799
800    or
801     SELECT *
802     FROM t1 LEFT OUTER JOIN t2 USING (col);
803
804    These identical queries join t1.col to t2.col, and also return any
805    unjoined rows in t1 (those with no match in t2). A RIGHT join would
806    add unjoined rows of t2. A FULL join would return the matched rows
807    plus all unjoined rows from t1 and t2. The word OUTER is optional and
808    is assumed in LEFT, RIGHT, and FULL joins. Ordinary joins are called
809    INNER joins.
810    
811   4.17) How do I perform queries using multiple databases?
812   
813    There is no way to query a database other than the current one.
814    Because PostgreSQL loads database-specific system catalogs, it is
815    uncertain how a cross-database query should even behave.
816    
817    contrib/dblink allows cross-database queries using function calls. Of
818    course, a client can also make simultaneous connections to different
819    databases and merge the results on the client side.
820    
821   4.18) How do I return multiple rows or columns from a function?
822   
823    It is easy using set-returning functions,
824    http://wiki.postgresql.org/wiki/Return_more_than_one_row_of_data_from_
825    PL/pgSQL_functions.
826    
827   4.19) Why do I get "relation with OID ##### does not exist" errors when
828   accessing temporary tables in PL/PgSQL functions?
829   
830    In PostgreSQL versions < 8.3, PL/PgSQL caches function scripts, and an
831    unfortunate side effect is that if a PL/PgSQL function accesses a
832    temporary table, and that table is later dropped and recreated, and
833    the function called again, the function will fail because the cached
834    function contents still point to the old temporary table. The solution
835    is to use EXECUTE for temporary table access in PL/PgSQL. This will
836    cause the query to be reparsed every time.
837    
838    This problem does not occur in PostgreSQL 8.3 and later.
839    
840   4.20) What replication solutions are available?
841   
842    Though "replication" is a single term, there are several technologies
843    for doing replication, with advantages and disadvantages for each.
844    
845    Master/slave replication allows a single master to receive read/write
846    queries, while slaves can only accept read/SELECT queries. The most
847    popular freely available master-slave PostgreSQL replication solution
848    is Slony-I.
849    
850    Multi-master replication allows read/write queries to be sent to
851    multiple replicated computers. This capability also has a severe
852    impact on performance due to the need to synchronize changes between
853    servers. PGCluster is the most popular such solution freely available
854    for PostgreSQL.
855    
856    There are also commercial and hardware-based replication solutions
857    available supporting a variety of replication models.
858    
859   4.21) Why are my table and column names not recognized in my query? Why is
860   capitalization not preserved?
861   
862    The most common cause of unrecognized names is the use of
863    double-quotes around table or column names during table creation. When
864    double-quotes are used, table and column names (called identifiers)
865    are stored case-sensitive, meaning you must use double-quotes when
866    referencing the names in a query. Some interfaces, like pgAdmin,
867    automatically double-quote identifiers during table creation. So, for
868    identifiers to be recognized, you must either:
869      * Avoid double-quoting identifiers when creating tables
870      * Use only lowercase characters in identifiers
871      * Double-quote identifiers when referencing them in queries