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