# Sequences

Bind a column to a PostgreSQL sequence with [AutoIncrement].

## `[AutoIncrement]`

Marks a property as a sequence-backed column. The migration tool creates a named PostgreSQL sequence and sets `nextval('...')` as the column default.

```csharp
[Table("log_entries")]
public partial class LogEntry
{
    [PrimaryKey]
    public Guid Id { get; set; }

    [AutoIncrement]
    public int Seq { get; set; }

    public string Message { get; set; }
}
```

---

## Sequence naming convention

The generated sequence name follows the pattern `{table}_{column}_seq`:

| Table | Column | Sequence name |
|-------|--------|---------------|
| `log_entries` | `seq` | `log_entries_seq_seq` |
| `orders` | `order_number` | `orders_order_number_seq` |

---

## Generated DDL

```sql
CREATE SEQUENCE IF NOT EXISTS "log_entries_seq_seq" AS INTEGER START 1;

CREATE TABLE "log_entries" (
    "id"      UUID    NOT NULL,
    "seq"     INTEGER NOT NULL DEFAULT nextval('"log_entries_seq_seq"'),
    "message" TEXT    NOT NULL DEFAULT '',
    PRIMARY KEY ("id")
);
```

---

## Usage

Because `[AutoIncrement]` is effectively a database-side default, use `ExcludeAutoFields()` to let PostgreSQL assign the sequence value:

```csharp
var entry = new LogEntry
{
    Id      = Guid.NewGuid(),
    Message = "Application started",
};

await entry.Insert()
    .WithConnection(conn)
    .ExcludeAutoFields()
    .ExecuteAsync();
```

After the insert, `entry.Seq` reflects whatever value PostgreSQL assigned only if you explicitly re-fetch the row. The current insert builder does not return the generated value inline.

---

## Notes

- `[AutoIncrement]` does **not** imply `[PrimaryKey]`. Primary key and sequence are orthogonal — you can have a UUID primary key alongside a sequence counter column, as shown above.
- Sequences are `INTEGER` by default. For a `BIGINT` sequence, override the column type: `[Column(Type = "BIGINT"), AutoIncrement]`.
- `[AutoIncrement]` is only valid on `short`, `int`, or `long` properties — any other type is reported as error [`SCGDB001`](/database/0.3.0/advanced/generator-diagnostics).
