postgres random select
To perform a random select in PostgreSQL using the C language, you can use the following code:
#include <stdio.h>
#include <stdlib.h>
#include <libpq-fe.h>
int main() {
PGconn *conn;
PGresult *res;
const char *conninfo = "dbname=mydb user=myuser password=mypassword";
const char *query = "SELECT column FROM table ORDER BY RANDOM() LIMIT 1";
conn = PQconnectdb(conninfo);
if (PQstatus(conn) == CONNECTION_OK) {
res = PQexec(conn, query);
if (PQresultStatus(res) == PGRES_TUPLES_OK) {
int num_rows = PQntuples(res);
if (num_rows > 0) {
int random_row = rand() % num_rows;
const char *value = PQgetvalue(res, random_row, 0);
printf("Random value: %s\n", value);
} else {
printf("No rows found.\n");
}
} else {
printf("Query execution failed.\n");
}
PQclear(res);
} else {
printf("Connection to database failed.\n");
}
PQfinish(conn);
return 0;
}
Make sure to replace mydb
, myuser
, mypassword
, column
, and table
with the appropriate values for your database.
This code establishes a connection to the PostgreSQL database, executes the query to select a random row from the specified table, and retrieves the value from the selected row. The rand()
function is used to generate a random index within the range of the number of rows returned by the query.
Please note that you need to have the PostgreSQL C library installed and linked properly for this code to work.