Query Execution Functions

Once a connection to a database server has been successfully established, the functions described here are used to perform SQL queries and commands.

Main Routines

PQexec

PQexec submits a query to the Red Hat Database backend server and waits for the result.
PGresult *PQexec(PGconn *conn, const char *query);
returns a PGresult pointer or possibly a NULL pointer. A non-NULL pointer will generally be returned except in the case of out-of-memory conditions or other serious errors such as inability to send the query to the backend. If a NULL is returned, it should be treated like a PGRES_FATAL_ERROR result. Use PQerrorMessage to get more information about the error.

The PGresult structure encapsulates the query result returned by the backend.

Note

libpq application programmers should be careful to maintain the PGresult abstraction. Use the accessor functions below to get at the contents of PGresult. Avoid directly referencing the fields of the PGresult structure because they are subject to change in the future. (The definition of struct PGresult is not even provided in libpq-fe.h. If you have old code that accesses PGresult fields directly, you can keep using it by including libpq-int.h as well, but you should fix the code.)

PQresultStatus

PQresultStatus returns the result status of the query.
ExecStatusType PQresultStatus(const PGresult *res)
PQresultStatus can return one of the following values:

  • PGRES_COMMAND_OK — Successful completion of a command returning no data

  • PGRES_TUPLES_OK — The query was successfully executed

  • PGRES_EMPTY_QUERY — The string sent to the backend was empty

  • PGRES_COPY_OUT — Copy Out (from server) data transfer started

  • PGRES_COPY_IN — Copy In (to server) data transfer started

  • PGRES_BAD_RESPONSE — The server's response was not understood

  • PGRES_NONFATAL_ERROR

  • PGRES_FATAL_ERROR

If the result status is PGRES_TUPLES_OK, you can use the routines described below to retrieve the tuples returned by the query. Note that a SELECT that happens to retrieve zero tuples still shows PGRES_TUPLES_OK. The status PGRES_COMMAND_OK is for commands that can never return tuples (INSERT, UPDATE, and so on). A response of PGRES_EMPTY_QUERY often exposes a bug in the client software.

PQresStatus

PQresStatus converts the enumerated type returned by PQresultStatus into a string constant that describes the status code.
char *PQresStatus(ExecStatusType status);

PQresultErrorMessage

PQresultErrorMessage returns the error message associated with the query, or an empty string if there was no error.
char *PQresultErrorMessage(const PGresult *res);
Immediately following a PQexec or PQgetResult call, PQerrorMessage (on the connection) will return the same string as PQresultErrorMessage (on the result). However, a PGresult will retain its error message until destroyed, whereas the connection's error message will change when subsequent operations are done. Use PQresultErrorMessage when you want to know the status associated with a particular PGresult; use PQerrorMessage when you want to know the status from the latest operation on the connection.

PQclear

PQclear frees the storage associated with the PGresult. Whenever a query result is no longer needed, free it with PQclear.
void PQclear(PQresult *res);
You can keep a PGresult object around for as long as you need it; it does not go away when you issue a new query or if you close the connection. To free it, you must call PQclear. Failure to do this will result in memory leaks in the frontend application.

PQmakeEmptyPGresult

PQmakeEmptyPGresult constructs an empty PGresult object with the given status.
PGresult* PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status);
This is the internal routine libpq uses to allocate and initialize an empty PGresult object. It is exported because some applications find it useful to generate result objects (particularly objects with error status) themselves. If conn is not NULL and status indicates an error, the connection's current errorMessage is copied into the PGresult. Note that you should eventually call PQclear on the object to dispose of it, just as with a PGresult returned by libpq itself.

Retrieving SELECT Result Information

PQntuples

PQntuples returns the number of tuples (rows) in the query result.
int PQntuples(const PGresult *res);

PQnfields

PQnfields returns the number of fields (attributes) in each tuple of the query result.
int PQnfields(const PGresult *res);

PQfname

PQfname returns the field (attribute) name associated with the given field index. Field indices start at 0.
char *PQfname(const PGresult *res, int field_index);

PQfnumber

PQfnumber returns the field (attribute) index associated with the given field name.
int PQfnumber(const PGresult *res, const char *field_name);

A result of -1 is returned if the given name does not match any field.

PQftype

PQftype returns the field type associated with the given field index. The integer returned is an internal coding of the type. Field indices start at 0.
Oid PQftype(const PGresult *res, int field_index);
You can query the system table pg_type to obtain the name and properties of the various datatypes. The OIDs of the built-in datatypes are defined in src/include/catalog/pg_type.h in the source tree.

PQfmod

PQfmod returns the type-specific modifier data of the field associated with the given field index. Field indices start at 0.
int PQfmod(const PGresult *res, int field_index);

PQfsize

PQfsize returns the size in bytes of the field associated with the given field index. Field indices start at 0.
int PQfsize(const PGresult *res, int field_index);
Returns the space allocated for this field in a database tuple (in other words, the size of the server's binary representation of the data type). If the field is variable size, -1 is returned.

PQbinaryTuples

PQbinaryTuples returns 1 if the PGresult contains binary tuple data, 0 if it contains ASCII data.
int PQbinaryTuples(const PGresult *res);
Currently, binary tuple data can be returned only by a query that extracts data from a BINARY cursor.

Retrieving SELECT Result Values

PQgetvalue

PQgetvalue returns a single field (attribute) value of one tuple of a PGresult. Tuple and field indices start at 0.
char* PQgetvalue(const PGresult *res, int tup_num, int field_num);
For most queries, the value returned by PQgetvalue is a NULL-terminated ASCII string representation of the attribute value. If PQbinaryTuples returns 1, the value returned by PQgetvalue is the binary representation of the type in the internal format of the backend server (but not including the size word, if the field is variable-length). It is then the programmer's responsibility to cast and convert the data to the correct C type. The pointer returned by PQgetvalue points to storage that is part of the PGresult structure; you should not modify it. If the pointer is to be used past the lifetime of the PGresult structure itself, you must explicitly copy the value into other storage.

PQgetisnull

PQgetisnull tests a field for a NULL entry. Tuple and field indices start at 0.
int PQgetisnull(const PGresult *res, int tup_num, int field_num);
This function returns 1 if the field contains a NULL, 0 if it contains a non-NULL value. (Note that PQgetvalue will return an empty string, not a null pointer, for a NULL field.)

PQgetlength

PQgetlength returns the length of a field (attribute) value in bytes. Tuple and field indices start at 0.
int PQgetlength(const PGresult *res, int tup_num, int field_num);
This is the actual data length for the particular data value (that is, the size of the object pointed to by PQgetvalue). Note that for ASCII-represented values, this size has little to do with the binary size reported by PQfsize.

PQprint

PQprint prints out all the tuples and, optionally, the attribute names to the specified output stream.
void PQprint(FILE* fout,      /* output stream */
                   const PGresult *res,
                   const PQprintOpt *po);

struct {
    pqbool  header;            /* print output field headings and row count */
    pqbool  align;              /* fill align the fields */
    pqbool  standard;        /* old brain dead format */
    pqbool  html3;             /* output html tables */
    pqbool  expanded;      /* expand tables */
    pqbool  pager;            /* use pager for output if needed */
    char    *fieldSep;        /* field separator */
    char    *tableOpt;       /* insert to HTML table ... */
    char    *caption;         /* HTML caption */
    char    **fieldName;   /* NULL terminated array of replacement field names */
} PQprintOpt;

Retrieving Non-SELECT Result Information

PQcmdStatus

PQcmdStatus returns the command status string associated with the SQL command that generated the PGresult.
char * PQcmdStatus(const PGresult *res);

PQcmdTuples

PQcmdTuples returns the number of rows affected by the SQL command.
char * PQcmdTuples(const PGresult *res);
If the SQL command that generated the PGresult was INSERT, UPDATE, or DELETE, this returns a string containing the number of rows affected; otherwise it returns the empty string.

PQoidValue

PQoidValue returns the object id of the tuple inserted, if the SQL command was an INSERT. Otherwise, returns InvalidOid.
Oid PQoidValue(const PGresult *res);
If you include the libpq header file, the type Oid and the constant InvalidOid will be defined (both will be some integer type).