Grab specific fields from the first row from a table using the standard select statement
422786
public function fieldSelect($table, $fields, $where, $orderBy = null)
    {
        $table = $this->getTableName($table);

        $query = "SELECT ";

        if (substr($this->mode, 0, 5) === "mssql") {
            $query .= "TOP 1 ";
        }

        $query .= $this->selectFields($fields);

        $query .= " FROM " . $table . " ";

        $params = null;
        if ($where !== self::NO_WHERE_CLAUSE) {
            $query .= "WHERE " . $this->where($where, $params);
        }

        if ($orderBy) {
            $query .= $this->orderBy($orderBy) . " ";
        }

        switch ($this->mode) {

            case "mysql":
            case "postgres":
            case "redshift":
            case "sqlite":
                $query .= "LIMIT 1";
                break;

            case "odbc":
                $query .= "FETCH FIRST 1 ROW ONLY";
                break;
        }

        return $this->query($query, $params)->fetch();
    }
32241
public function find($table, $fields = null, $where = null, $order = null, $limit = null, $offset = null, $array = array(), $fetchMode = \PDO::FETCH_ASSOC)
     {
         $sql = ' SELECT '.(($fields) ?? '*').' FROM '.(($table)).(($where) ? ' WHERE '.$where : ' ')
            .(($limit) ? ' LIMIT '.$limit : ' ')
            .(($offset && $limit) ? ' OFFSET '.$offset : ' ')
            .(($order) ? ' ORDER BY '.$order : ' ');

         $stmt = $this->conn->prepare($sql);

         foreach ($array as $key => $values) {
             return  $stmt->bindValue("$key", $values);
         }
         $stmt->execute();

         do {
             return $stmt->fetchAll($fetchMode);
         } while (
            $stmt->nextRowset());
         $stmt->close();
     }
840127
def selectcontains(table, field, value, complement=False):
    """"""

    return selectop(table, field, value, operator.contains,
                    complement=complement)
401286
def get_last_field(self, field, table=None):
        '''
        '''
        field = field if is_array(field) else [field]
        table = self.get_table(table, except_=False)
        if table is None:
            last = None
        else:
            is_defined(field, 'field must be defined!')
            last = self.find(table=table, fields=field, scalar=True,
                             sort=field, limit=1, descending=True,
                             date='~', default_fields=False)
        logger.debug("last %s.%s: %s" % (table, list2str(field), last))
        return last
697089
def _select_limit_statement(table, cols='*', offset=0, limit=MAX_ROWS_PER_QUERY):
        """"""
        return 'SELECT {0} FROM {1} LIMIT {2}, {3}'.format(join_cols(cols), wrap(table), offset, limit)
944239
def select(table, cols="*", where=(), group="", order=(), limit=(), **kwargs):
    """"""
    where = dict(where, **kwargs).items()
    sql, args = makeSQL("SELECT", table, cols, where, group, order, limit)
    return execute(sql, args)
62026
def selecttrue(table, field, complement=False):
    """"""

    return select(table, field, lambda v: bool(v), complement=complement)
673658
def fetchall_with_fieldnames(self, sql: str, *args) \
            -> Tuple[Sequence[Sequence[Any]], Sequence[str]]:
        """"""
        self.ensure_db_open()
        cursor = self.db.cursor()
        self.db_exec_with_cursor(cursor, sql, *args)
        try:
            rows = cursor.fetchall()
            fieldnames = [i[0] for i in cursor.description]
            return rows, fieldnames
        except:  # nopep8
            log.exception("fetchall_with_fieldnames: SQL was: " + sql)
            raise
549311
def select_fields(self, *fields):
        """"""
        if fields:
            if not isinstance(fields[0], basestring): 
                fields = list(fields[0]) + list(fields)[1:]

        for field_name in fields:
            field_name = self._normalize_field_name(field_name)
            self.select_field(field_name)
        return self
685996
public function select(
        $table,
        $conditions = null,
        $fields = null,
        $order = null,
        $limit = null,
        $offset = null
    )
    {
        if (is_null($fields)) {
            $fields = "*";
        }

        $queryString = "SELECT {$fields} FROM {$table} ";

        if (!is_null($conditions)) {
            $queryString .= "WHERE {$conditions} ";
        }

        if (!is_null($order)) {
            $queryString .= "ORDER BY {$order} ";
        }

        if (!is_null($limit)) {
            $queryString .= "LIMIT {$limit} ";
        }

        if (!is_null($offset) && !is_null($limit)) {
            $queryString .= "OFFSET {$offset} ";
        }


        $queryString .= ";";

        $this->query($queryString);

        return $this->countRows();
    }
1101491
def check_values_selection_field(cr, table_name, field_name, allowed_values):
    
    res = True
    cr.execute("SELECT %s, count(*) FROM %s GROUP BY %s;" %
               (field_name, table_name, field_name))
    for row in cr.fetchall():
        if row[0] not in allowed_values:
            logger.error(
                "Invalid value '%s' in the table '%s' "
                "for the field '%s'. (%s rows).",
                row[0], table_name, field_name, row[1])
            res = False
    return res
815124
def selectin(table, field, value, complement=False):
    """"""

    return select(table, field, lambda v: v in value,
                  complement=complement)
877557
def _get_fields(self, table_name, **kwargs):
        """"""
        ret = {}
        query_str = []
        query_args = ['f', table_name]

        # I had to brush up on my join knowledge while writing this query
        # https://en.wikipedia.org/wiki/Join_(SQL)
        #
        # other helpful links
        # https://wiki.postgresql.org/wiki/Retrieve_primary_key_columns
        # https://www.postgresql.org/docs/9.4/static/catalog-pg-attribute.html
        # https://www.postgresql.org/docs/9.3/static/catalog-pg-type.html
        # 
        # another approach
        # http://dba.stackexchange.com/questions/22362/how-do-i-list-all-columns-for-a-specified-table
        # http://gis.stackexchange.com/questions/94049/how-to-get-the-data-type-of-each-column-from-a-postgis-table
        query_str.append('SELECT')
        query_str.append(',  '.join([
            'a.attnum',
            'a.attname',
            'a.attnotnull',
            't.typname',
            'i.indisprimary',
            #'s.conname',
            #'pg_get_constraintdef(s.oid, true) as condef',
            'c.relname AS confrelname',
        ]))
        query_str.append('FROM')
        query_str.append('  pg_attribute a')
        query_str.append('JOIN pg_type t ON a.atttypid = t.oid')
        query_str.append('LEFT JOIN pg_index i ON a.attrelid = i.indrelid')
        query_str.append('  AND a.attnum = any(i.indkey)')
        query_str.append('LEFT JOIN pg_constraint s ON a.attrelid = s.conrelid')
        query_str.append('  AND s.contype = {} AND a.attnum = any(s.conkey)'.format(self.val_placeholder))
        query_str.append('LEFT JOIN pg_class c ON s.confrelid = c.oid')
        query_str.append('WHERE')
        query_str.append('  a.attrelid = {}::regclass'.format(self.val_placeholder))
        query_str.append('  AND a.attisdropped = False')
        query_str.append('  AND a.attnum > 0')
        query_str.append('ORDER BY a.attnum ASC')

        query_str = os.linesep.join(query_str)
        fields = self.query(query_str, *query_args, **kwargs)

        pg_types = {
            "float8": float,
            "timestamp": datetime.datetime,
            "int2": int,
            "int4": int,
            "int8": long,
            "numeric": decimal.Decimal,
            "text": str,
            "bpchar": str,
            "varchar": str,
            "bool": bool,
            "date": datetime.date,
            "blob": bytearray,
        }

        # the rows we can set: field_type, name, field_required, min_size, max_size,
        #   size, unique, pk, <foreign key info>
        # These keys will roughly correspond with schema.Field
        for row in fields:
            field = {
                "name": row["attname"],
                "field_type": pg_types[row["typname"]],
                "field_required": row["attnotnull"],
                "pk": bool(row["indisprimary"]),
            }

            if row["confrelname"]:
                # TODO -- I can't decide which name I like
                field["schema_table_name"] = row["confrelname"]
                field["ref_table_name"] = row["confrelname"]

            ret[field["name"]] = field

        return ret
1016632
def select_by_field(self, base, field, value):
        """"""
        Ac = self.ACCES
        return groups.Collection(Ac(base, i) for i, row in self.items() if row[field] == value)
753390
def get_select_sql(self):
        
        if self.table:
            return '{0}.{1}'.format(self.table.get_identifier(), self.name)
        return '{0}'.format(self.name)
267231
function select($fields,$filter=NULL,array $options=NULL,$ttl=0) {
		list($sql,$args)=$this->stringify($fields,$filter,$options);
		$result=$this->db->exec($sql,$args,$ttl);
		$out=[];
		foreach ($result as &$row) {
			foreach ($row as $field=>&$val) {
				if (array_key_exists($field,$this->fields)) {
					if (!is_null($val) || !$this->fields[$field]['nullable'])
						$val=$this->db->value(
							$this->fields[$field]['pdo_type'],$val);
				}
				unset($val);
			}
			$out[]=$this->factory($row);
			unset($row);
		}
		return $out;
	}
1000379
def select(self, table, cols, mode='list', key_filter=True):
        
        if cols is None:
            cols = [c.name for c in self.relations[table]]
        rows = self.read_table(table, key_filter=key_filter)
        for row in select_rows(cols, rows, mode=mode):
            yield row