# `insert`

_Insert or append records to a table_
```syntax
x insert y    insert[x;y]
```

Where

- `x` is a symbol atom naming a non-splayed table
- `y` is one or more records that match the columns of `x` or, if `x` is undefined, a table

inserts `y` into the table named by `x` and returns the new row indexes.

> **Warning — The left argument is the name of a table as a symbol atom.**
>
>
```q
q)show x:([a:`x`y];b:10 20)
a| b
-| --
x| 10
y| 20

q)`x insert (`z;30)
,2

q)x
a| b
-| --
x| 10
y| 20
z| 30

q)tnew
'tnew
  [0]  tnew
       ^
q)`tnew insert ([c1:`a`b];c2:10 20)
0 1
q)tnew
c1| c2
--| --
a | 10
b | 20
```

If the table is keyed, the new records must not match existing keys.
```q
q)`x insert (`z;30)
'insert
  [0]  `x insert (`z;30)
          ^
```

You can append several records at once, as a list of columns, a dictionary, or a table:
```q
q)`x insert (`s`t;40 50)
3 4
q)`x insert `a`b!(`w;60)
,5
q)`x insert ([a:`v`u]b:70 80)
6 7
q)x
a| b
-| --
x| 10
y| 20
z| 30
s| 40
t| 50
w| 60
v| 70
u| 80
```

> **Tip — `insert` can insert only into global variables.**
>
>
> To insert into a table that is local to a function, use [`x,:y`](assign.md#assign-through-operator) or [Update](funsql.md#update) instead.
>
## Type

Values in `y` must match the type of corresponding columns in `x`; otherwise, q signals a `type` error.
```q
q)`x insert (`q;1.5)
'type
  [0]  `x insert (`q;1.5)
          ^
```

Empty columns in `x` with general type assume types from the first record inserted.
```q
q)meta u:([] name:(); age:())
c   | t f a
----| -----
name|
age |
q)`u insert (`tom`dick;30 40)
0 1
q)meta u
c   | t f a
----| -----
name| s
age | j
```

## Foreign keys

If `x` has foreign keys, q checks that the corresponding values of `y` appear in the primary key columns that the foreign keys point to, and signals a `cast` error if they don’t.
```q
q)k:([id:1 2]v:`a`b)
q)o:([]id:`k$1 2;q:10 20)
q)`o insert (`k$1;30)
,2
q)`o insert (3;40)
'cast
  [0]  `o insert (3;40)
          ^
```

## Errors
```txt
cast     y value not in foreign key
insert   y key value defined in x
type     y value wrong type
```

> **Tip — With keyed tables, consider [`upsert`](upsert.md) as an alternative.**
>
>
----

[Join](join.md)


[`upsert`](upsert.md)


[Functional qSQL](funsql.md)


[qSQL query templates](qsql.md)


[Tables](table.md)
