Normalizing data in Airtable

This KB article is part of SYNCHUB's data-extraction knowledge base for Airtable

Airtable's flexibility is reflected in its API data structure, which is abstracted into DataTables, Records and TableFields - each representing a regular database Table/Row/Cell respectively. To return the data to the more "normal" tabular format that you are used to dealing with, you'll need to use a `PIVOT QUERY` in SQL. This example below uses _SQL Server_, but your own database will have an equivalent ```sql -- Variables - change these DECLARE @TableName nvarchar(200) = N'People' -- Load our table details DECLARE @PeopleTableID NVARCHAR(MAX); SELECT @PeopleTableID = dt.ID FROM [CONNECTIONS.airtable].DataTable AS dt WHERE dt.Name = @TableName; -- Helpful error message IF (@PeopleTableID is null) BEGIN RAISERROR('There is no table named "%s" in your database', 16, 1, @TableName) RETURN END DECLARE @ColumnList NVARCHAR(MAX) = ''; DECLARE @PivotQuery NVARCHAR(MAX); -- Load the columns into a string variable so that we may inject them in our dynamic SQL below SELECT @ColumnList = @ColumnList + QUOTENAME(tf.Name) + ',' FROM [CONNECTIONS.airtable].TableField AS tf WHERE tf.TableID = @PeopleTableID AND tf.IsDeleted = 0 ORDER BY tf.Name; SET @ColumnList = LEFT(@ColumnList, LEN(@ColumnList) - 1); -- Remove trailing comma SET @PivotQuery = ' SELECT PivotTable.RemoteID AS PersonRemoteID, ' + @ColumnList + ' FROM ( SELECT r.RemoteID, tf.Name AS FieldName, COALESCE(rfv.StringValue, CAST(rfv.DateValue AS NVARCHAR(MAX)), CAST(rfv.BoolValue AS NVARCHAR(MAX)), CAST(rfv.DecimalValue AS NVARCHAR(MAX)), CAST(rfv.IntegerValue AS NVARCHAR(MAX)), rfv.UserIDValue) AS FieldValue FROM [CONNECTIONS.airtable].Record AS r INNER JOIN [CONNECTIONS.airtable].RecordFieldValue AS rfv ON (r.ID = rfv.RecordID AND r.IsDeleted = 0 AND rfv.IsDeleted = 0) INNER JOIN [CONNECTIONS.airtable].TableField AS tf ON (rfv.FieldID = tf.ID AND tf.IsDeleted = 0) WHERE r.TableID = @PeopleTableID ) AS SourceData PIVOT ( MAX(FieldValue) FOR FieldName IN (' + @ColumnList + ') ) AS PivotTable;'; EXEC sp_executesql @PivotQuery, N'@PeopleTableID NVARCHAR(MAX)', @PeopleTableID = @PeopleTableID; ```