insert¶
Insert or append records to a table
x insert y insert[x;y]
Where
xis a symbol atom naming a non-splayed tableyis one or more records that match the columns ofxor, ifxis undefined, a table
inserts y into the table named by x and returns the new row indexes.
The left argument is the name of a table as a symbol atom.
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)`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)`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
insert can insert only into global variables.
To insert into a table that is local to a function, use x,:y or Update instead.
Type¶
Values in y must match the type of corresponding columns in x; otherwise, q signals a type error.
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)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)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¶
cast y value not in foreign key
insert y key value defined in x
type y value wrong type
With keyed tables, consider upsert as an alternative.