In Memory Tables · Creating Tables · Practice Question
Defining table schemas
Create an Empty Typed Table
Question
Create an empty table named t with the following schema:
| Column | Type |
|---|---|
a | symbol |
b | float |
c | int |
The table should contain no rows.
Solution
Method 1
t:([] a:`symbol$(); b:`float$(); c:`int$())Result:
a b c
-----Method 2
t:([] a:"S"$(); b:"F"$(); c:"I"$())Method 3
t:([] a:0#`; b:0#0n; c:0#0Ni)Method 4
t:flip `a`b`c!"SFI"$\:()Method 5
t:flip ([a:0#`; b:0#0n; c:0#0Ni])All methods create the same empty typed table.
Explanation
When creating an empty table, it is important to define the column types explicitly.
Method 1: Type Casting
An empty list can be cast to a specific type:
`symbol$()
`float$()
`int$()These typed empty lists are then used as the table columns:
([] a:`symbol$(); b:`float$(); c:`int$())Method 2: Type Characters
The same table can be created using each type's character code with $ (Tok). Applied to an empty list, it returns an empty list of that type:
"S"$()
"F"$()
"I"$()where "S", "F" and "I" are the type characters for symbol, float and int respectively.
Method 3: Empty Lists Using Take
A zero-length list can also be created using the Take operator:
0#`
0#0n
0#0NiResult:
`symbol$()
`float$()
`int$()These typed empty lists can be used directly as table columns.
Method 4: Flip a Dictionary
A table is internally a flipped column dictionary.
The expression:
`a`b`c!"SFI"$\:()creates a dictionary whose values are empty typed lists. The console shows empty values as blanks, but .Q.s1 shows them explicitly:
`a`b`c!(`symbol$();`float$();`int$())Applying flip converts it into a table:
flip `a`b`c!"SFI"$\:()Method 5: Dictionary Literal Syntax
Dictionary literal syntax can also be used:
([a:0#`; b:0#0n; c:0#0Ni])which creates a column dictionary.
Applying flip converts it into a table:
flip ([a:0#`; b:0#0n; c:0#0Ni])Verifying the Schema
The column names can be inspected using:
cols tResult:
`a`b`cThe column types can be inspected using:
type each value flip tResult:
11 9 6hwhich are the type numbers of symbol, float and int lists respectively.
Summary
There are several ways to create an empty typed table in q:
- Cast empty lists to the required types.
- Use type characters (
"SFI") with$. - Create zero-length typed lists with
0#. - Build a column dictionary and
flipit. - Use dictionary literal syntax and
flip.
All approaches produce the same table schema with zero rows.