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