Expression Library

A reference library of all expressions that can be used in PlaidCloud

Description

An expression is a basic function that does a conversion, calculation, cast to another data type, or other action on data in a column or in a dashboard chart object. Examples are startswith, max, or current_date. PlaidCloud expressions are based on PostgreSQL. For a more in depth tutorial or reference guide, please see: tutorial

There are three primary areas to apply expressions - metrics and calculated columns in datasets, and chart objects in dashboards.

In order to view and edit metrics and calculated expressions:

  1. Sign into plaidcloud.com and navigate to Dasboards. Select the dashboard you want to work in.
  2. Select Data > Datasets from the menu.
  3. Search for a dataset to view or modify
  4. Hover over the dataset with the cursor and you will see icons in the actions column.
  5. Click the edit icon beneath Actions

Viewing a chart object and adding an expression

You can add expressions to chart objects on a dashboard. For example, if you want to add an expression to a table object (a calculated column), you can:

  1. Open the chart object by opening a dashboard, clicking on the three dot icon, and selecting "View chart in Explore".
  2. Now that you are editing the chart, you can add a new Dimension or Metric, and do a SIMPLE expression, or a CUSTOM SQL expression

Now that you have located where you want to add an expression, you can use the table below as a guide to determining what expression you are looking for.

Category    ExpressionStructureExampleDescription
Conditionalcasecase((expression, truevalue), else_ = falsevalue)case((table.first_name.isnot(None), func.concat(table.first_name, table.last_name)), else_ = table.last_name)
Additional Examples
a switch or a conditional control structure that allows the program to evaluate an expression and perform different actions based on the value of that expression
Conditionalcoalescefunc.coalesce(column1, column2, ...)func.coalesce(table.nickname, table.first_name)
Additional Examples
Returns the first non-null value in a set of columns. In the example, if there is a nickname it returns that, otherwise it returns the first name.
Conversioncastfunc.cast(value, datatype)func.cast(123, Text)
Additional Examples
Converts the value to a specific data type. In the example, it takes an Integer (123) and returns it as a string "123".
Conversionto_charfunc.to_char(timestamp, text)
See More
func.to_char(current_timestamp, 'HH12:MI:S S')
Additional Examples
Converts an object type to a char (text). In the example, it converts a timestamp to text
Conversionto_datefunc.to_date(text, format)func.to_date(table.Created_on, 'DD-MM-YYYY')Convert a text field into a date formatted how you like
Conversionto_numberfunc.to_number(text, format)func.to_number ('12,454.8 -', '99G999D9S')Convert a string to a numeric value
Conversionto_timestampfunc.to_timestamp(text, format)
See More
func.to_timestamp('05 Dec 2000', 'DD Mon YYYY')
Additional Examples
Convert a string to a timestamp
Timeagefunc.age(timestamp, timestamp)age(timestamp ‘2001-04-1 0’, timestamp ‘1957-06-1 3’)=43 years 9 months 27 daysSubtracts the second timestamp from the first one and returns an interval as a result
Timeagefunc.age(timestamp)age(timestamp ‘1957-06-1 3’)=43 years 8 months 3 daysReturns the interval between the current date and the argument provided
Timeclock_timestampfunc.clock_timestamp()func.clock_timestamp()Returns a timestamp for the current date and time which changes during execution
Timecurrent_datefunc.current_date()func.current_date()

get_column(table, 'Created On')>=(func.current_date()-120)
Returns the a date object with the current date
Timecurrent_timefunc.current_time()func.current_time()Returns a time object with the current time and timezone
Timecurrent_timestampfunc.current_timestamp()func.current_timestamp()Returns a timestamp object with the current date and time at the beginning of execution
Timedate_partfunc.date_part(text, timestamp)func.date_part('hour', timestamp '2001-02-1 6 20:38:40')=20Returns the part of the timestamp you are looking for (month, year, etc.)
See more options
Timedate_partfunc.date_part(text, interval)func.date_part('month', interval '2 years 3 months')=3Returns the part of the interval you are looking for (month, year, etc.)
See more options
Timedate_truncfunc.date_trunc(text, timestamp)func.date_trunc('hour', timestamp '2001-02-1 6 20:38:40')=36938.8333333333
Additional Examples
Truncate to specified precision
Timeextractfunc.extract(field from timestamp)func.extract(hour from timestamp '2001-02-1 6 20:38:40')=20Get a field of a timestamp or an interval e.g., year, month, day, etc.
Timeextractfunc.extract(field from interval)func.extract(month from interval '2 years 3 months')=3Get a field of a timestamp or an interval e.g., year, month, day, etc.
Timeisfinitefunc.isfinite(timestamp)func.isfinite(timestamp '2001-02-1 6 21:28:30')=TRUECheck if a date, a timestamp, or an interval is finite or not (not +/-infinity)
Timeisfinitefunc.isfinite(interval)func.isfinite(interval '4 hours')=TRUECheck if a date, a timestamp, or an interval is finite or not (not +/-infinity)
Timejustify_daysfunc.justify_days(interval)func.justify_days(interval '30 days')=1 monthAdjust interval so 30-day time periods are represented as months
Timejustify_hoursfunc.justify_hours(interval)func.justify_hours(interval '24 hours')=1 dayAdjust interval so 24-hour time periods are represented as days
Timejustify_intervalfunc.justify_interval(interval)func.justify_interval(interval '1 mon -1 hour')=29 days 23:00:00Adjust interval using justify_days and justify_hours, with additional sign adjustments
Timenowfunc.now()func.now()Return the date and time with time zone at which the current transaction start
Timestatement_timestampfunc.statement_timestamp()func.statement_timestamp()Return the current date and time at which the current statement executes
Timetimeofdayfunc.timeofday()func.timeofday()Return the current date and time, like clock_timestamp, as a text string
Timetransaction_timestampfunc.transaction_timestamp()func.transaction_timestamp()Return the date and time with time zone at which the current transaction start
General Usage>>table.column > 23Greater Than
General Usage<<table.column < 23Less Than
General Usage>=>=table.column >= 23Greater than or equal to
General Usage<=<=table.column <= 23Less than or equal to
General Usage====table.column == 23Equal to
General Usage!=!=table.column != 23Not Equal to
General Usageand_and_()and_(table.a > 23, table.b == u'blue')
Additional Examples
Creates an AND SQL condition
General Usageany_any_()table.column.any(('red', 'blue', 'yellow'))Applies the SQL ANY() condition to a column
General Usagebetweenbetweentable.column.between(23, 46)

get_column(table, 'LAST_CHANGED_DATE').between({start_date}, {end_date})
Applies the SQL BETWEEN condition
General Usagecontainscontainstable.column.contains('mno')

table.SOURCE_SYSTEM.contains('TEST')
Applies the SQL LIKE '%%'
General Usageendswithendswithtable.column.endswith('xyz')

table.Parent.endswith(':EBITX')

table.PERIOD.endswith("01")
Applies the SQL LIKE '%%'
General UsageFALSEFALSEFALSEFalse, false, FALSE - Alias for Python False
General Usageilikeiliketable.column.ilike('%foobar%')Applies the SQL ILIKE method
General Usagein_in_()table.column.in_((1, 2, 3))

get_column(table, 'Source Country').in_(['CN','SG','BR'])

table.MONTH.in_(['01','02','03','04','05','06','07','08','09'])
Test if values are with a tuple of values
General Usageis_is_table.column.is_(None)

get_column(table, 'Min SafetyStock').is_(None)

get_column(table, 'date_pod').is_(None)
Applies the SQL is the IS for things like IS NULL
General Usageisnotisnottable.column.isnot(None)Applies the SQL is the IS for things like IS NOT NULL
General Usagelikeliketable.column.like('%foobar%')

table.SOURCE_SYSTEM.like('%Adjustments%')
Applies the SQL LIKE method
General Usagenot_not_()not_(and_(table.a > 23, table.b == u'blue'))
Additional Examples
Inverts the condition
General Usagenotilikenotiliketable.column.notilike('%foobar%')Applies the SQL NOT ILIKE method
General Usagenotinnotintable.column.notin((1, 2, 3))

table.LE.notin_(['12345','67890'])
Inverts the IN condition
General Usagenotlikenotliketable.column.notlike('%foobar%')Applies the SQL NOT LIKE method
General UsageNULLNULLNULLNull, null, NULL - Alias for Python None
General Usageor_or_()or_(table.a > 23, table.b == u'blue')
Additional Examples
Creates an OR SQL condition
General Usagestartswithstartswithtable.column.startswith('abc')

get_column(table, 'Zip Code').startswith('9')

get_column(table1, 'GL Account').startswith('CORP')
Applies the SQL LIKE '%'
General UsageTRUETRUETRUETrue, true, TRUE - Alias for Python True
Math Expressions+++2+3=5
Math Expressions-2–3=-1
Math Expressions***2*3=6
Math Expressions///4/2=2
Math Expressionscolumn.opcolumn.op(operator)column.op('%')5%4=1
Math Expressionscolumn.opcolumn.op(operator)column.op('^')2.0^3.0=8
Math Expressionscolumn.opcolumn.op(operator)column.op('!')5!=120
Math Expressionscolumn.opcolumn.op(operator)column.op('!!')!!5=120
Math Expressionscolumn.opcolumn.op(operator)column.op('@')@-5.0=5
Math Expressionscolumn.opcolumn.op(operator)column.op('&')91&15=11
Math Expressionscolumn.opcolumn.op(operator)column.op('#')17##5=20
Math Expressionscolumn.opcolumn.op(operator)column.op('~')~1=-2
Math Expressionscolumn.opcolumn.op(operator)column.op('<<')1<<4=16
Math Expressionscolumn.opcolumn.op(operator)column.op('>>')8>>2=2
Math Functionsabsfunc.abs(x)abs(-17.4)=17.4

func.abs(get_column(table, 'RPA Value'))
absolute value (return type: Same as input)
Math Functionscbrtfunc.cbrt(dp)cbrt(27.0)=3cube root (return type: Big Float)
Math Functionsceilfunc.ceil(dp or numeric)ceil(-42.8)=-42

func.ceil(func.extract('seconds', table.OutlierTime) / 60)
smallest integer not less than argument (return type: Same as input)
Math Functionsceilingfunc.ceiling(dp or numeric)ceiling(-95.3)=-95smallest integer not less than argument (return type: Same as input)
Math Functionsdegreesfunc.degrees(dp)degrees(0.5)=28.6478897565412radians to degrees (return type: Big Float)
Math Functionsexpfunc.exp(dp or numeric)exp(1.0)=2.71828182845905exponential (return type: Same as input)
Math Functionsfloorfunc.floor(dp or numeric)floor(-42.8)=-43largest integer not greater than argument (return type: Same as input)
Math Functionsgreatestfunc.greatest(value …)Select the largest value from a list. NULL values in the list are ignored. The result will be NULL only if all values are NULL. (return type: Same as input)
Math Functionsleastfunc.least(value…)Select the smallest value from a list. NULL values in the list are ignored. The result will be NULL only if all values are NULL. (return type: Same as input)
Math Functionslnfunc.ln(dp or numeric)ln(2.0)=0.693147180559945natural logarithm (return type: Same as input)
Math Functionslogfunc.log(dp or numeric)log(100.0)=2base 10 logarithm (return type: Same as input)
Math Functionslogfunc.log(b numeric, x numeric)log(2.0,64.0)=6logarithm to base b (return type: Numeric)
Math Functionsmodfunc.mod(y, x)mod(9,4)=1remainder of y/x (return type: Same as input)
Math Functionspifunc.pi()pi()=3.14159265358979“π” constant (return type: Big Float)
Math Functionspowerfunc.power(a dp, b dp)power(9.0,3.0)=729a raised to the power of b (return type: Big Float)
Math Functionspowerfunc.power(a numeric, b numeric)power(9.0,3.0)=729a raised to the power of b (return type: Numeric)
Math Functionsradiansfunc.radians(dp)radians(4 5.0)=0.785398163397448degrees to radians (return type: Big Float)
Math Functionsrandomfunc.random()random()random value in the range 0.0 <= x < 1.0 (return type: Big Float)
Math Functionsroundfunc.round(dp or numeric)round(42.4)=42round to nearest integer (return type: Same as input)
Math Functionsroundfunc.round(v numeric, s int)round(42.4382, 2)=42.44

func.round(table.RATE, 5)

func.round((get_column(table, 'Order Quantity')/3), 0)
round to s decimal places (return type: Numeric)
Math Functionssafe_dividefunc.safe_divide(numerator numeric, denominator numeric, divide_by_zero_value)func.safe_divide(get_column(table, 'VALUE__MC'), table.RATE, 0.0)

func.safe_divide(get_column(table, 'Total_Weight'), (table.PickHours + table.BreakHours), 0.00)
Equivalent to the division operator (X / Y), but returns NULL if an error occurs, such as a division by zero error
Math Functionssetseedfunc.setseed(dp)setseed(0 .54823)=1177314959set seed for subsequent random() calls (value between 0 and 1.0) (return type: Integer)
Math Functionssignfunc.sign(dp or numeric)sign(-8.4)=-1sign of the argument (-1, 0, +1) (return type: Same as input)
Math Functionssqrtfunc.sqrt(dp or numeric)sqrt(2.0)=1.4142135623731square root (return type: Same as input)
Math Functionstruncfunc.trunc(dp or numeric)trunc(42. 8)=42truncate toward zero (return type: Same as input)
Math Functionstruncfunc.trunc(v numeric, s int)trunc(42.4382, 2)=42.43truncate to s decimal places (return type: Numeric)
Math Functionswidth_bucketfunc.width_bucket( op numeric, b1 numeric, b2 numeric, count int)width_bucket(5.35, 0.024, 10.06, 5)=3return the bucket to which operand would be assigned in an equidepth histogram with count buckets, in the range b1 to b2 (return type: Integer)
Math Trigacosfunc.acos(x)inverse cosine
Math Trigasinfunc.asin(x)inverse sine
Math Trigatanfunc.atan(x)inverse tangent
Math Trigatan2func.atan2(x,y)inverse tangent of x/y
Math Trigcosfunc.cos(x)cosine
Math Trigcotfunc.cot(x)cotangent
Math Trigsinfunc.sin(x)sine
Math Trigtanfunc.tan(x)tangent
Geometry / PostGISST_3DMakeBoxbox3d ST_3DMakeBox(geometry point3DLowLeftBottom, geometry point3DUpRightTop);ExampleCreates a BOX3D defined by the given 3d point geometries.
Geometry / PostGISST_BdMPolyFromTextgeometry ST_BdMPolyFromText(text WKT, integer srid);ExampleConstruct a MultiPolygon given an arbitrary collection of closed linestrings as a MultiLineString text representation Well-Known text representation.
Geometry / PostGISST_BdPolyFromTextgeometry ST_BdPolyFromText(text WKT, integer srid);ExampleConstruct a Polygon given an arbitrary collection of closed linestrings as a MultiLineString Well-Known text representation.
Geometry / PostGISST_Box2dFromGeoHashbox2d ST_Box2dFromGeoHash(text geohash, integer precision=full_precision_of_geohash);ExampleReturn a BOX2D from a GeoHash string.
Geometry / PostGISST_GeogFromTextgeography ST_GeogFromText(text EWKT);ExampleReturn a specified geography value from Well-Known Text representation or extended (WKT).
Geometry / PostGISST_GeogFromWKBgeography ST_GeogFromWKB(bytea wkb);ExampleCreates a geography instance from a Well-Known Binary geometry representation (WKB) or extended Well Known Binary (EWKB).
Geometry / PostGISST_GeographyFromTextgeography ST_GeographyFromText(text EWKT);ExampleReturn a specified geography value from Well-Known Text representation or extended (WKT).
Geometry / PostGISST_GeomCollFromTextgeometry ST_GeomCollFromText(text WKT, integer srid);ExampleMakes a collection Geometry from collection WKT with the given SRID. If SRID is not given, it defaults to 0.
Geometry / PostGISST_GeometryFromTextgeometry ST_GeometryFromText(text WKT, integer srid);ExampleReturn a specified ST_Geometry value from Well-Known Text representation (WKT). This is an alias name for ST_GeomFromText
Geometry / PostGISST_GeomFromEWKBgeometry ST_GeomFromEWKB(bytea EWKB);ExampleReturn a specified ST_Geometry value from Extended Well-Known Binary representation (EWKB).
Geometry / PostGISST_GeomFromEWKTgeometry ST_GeomFromEWKT(text EWKT);ExampleReturn a specified ST_Geometry value from Extended Well-Known Text representation (EWKT).
Geometry / PostGISST_GeomFromGeoHashgeometry ST_GeomFromGeoHash(text geohash, integer precision=full_precision_of_geohash);ExampleReturn a geometry from a GeoHash string.
Geometry / PostGISST_GeomFromGMLgeometry ST_GeomFromGML(text geomgml, integer srid);ExampleTakes as input GML representation of geometry and outputs a PostGIS geometry object
Geometry / PostGISST_GeomFromGMLgeometry ST_GeomFromGML(text geomgml, integer srid);ExampleTakes as input GML representation of geometry and outputs a PostGIS geometry object
Geometry / PostGISST_GeomFromKMLgeometry ST_GeomFromKML(text geomkml);ExampleTakes as input KML representation of geometry and outputs a PostGIS geometry object
Geometry / PostGISST_GeomFromTextgeometry ST_GeomFromText(text WKT, integer srid);ExampleReturn a specified ST_Geometry value from Well-Known Text representation (WKT).
Geometry / PostGISST_GeomFromWKBgeometry ST_GeomFromWKB(bytea geom, integer srid);ExampleCreates a geometry instance from a Well-Known Binary geometry representation (WKB) and optional SRID.
Geometry / PostGISST_GMLToSQLgeometry ST_GMLToSQL(text geomgml, integer srid);ExampleReturn a specified ST_Geometry value from GML representation. This is an alias name for ST_GeomFromGML
Geometry / PostGISST_LineFromEncodedPolylinegeometry ST_LineFromEncodedPolyline(text polyline, integer precision=5);ExampleCreates a LineString from an Encoded Polyline.
Geometry / PostGISST_LineFromMultiPointgeometry ST_LineFromMultiPoint(geometry aMultiPoint);ExampleCreates a LineString from a MultiPoint geometry.
Geometry / PostGISST_LineFromTextgeometry ST_LineFromText(text WKT, integer srid);ExampleMakes a Geometry from WKT representation with the given SRID. If SRID is not given, it defaults to 0.
Geometry / PostGISST_LineFromWKBgeometry ST_LineFromWKB(bytea WKB, integer srid);ExampleMakes a LINESTRING from WKB with the given SRID
Geometry / PostGISST_LinestringFromWKBgeometry ST_LinestringFromWKB(bytea WKB, integer srid);ExampleMakes a geometry from WKB with the given SRID.
Geometry / PostGISST_MakeBox2Dbox2d ST_MakeBox2D(geometry pointLowLeft, geometry pointUpRight);ExampleCreates a BOX2D defined by the given point geometries.
Geometry / PostGISST_MakeEnvelopegeometry ST_MakeEnvelope(double precision xmin, double precision ymin, double precision xmax, double precision ymax, integer srid=unknown);ExampleCreates a rectangular Polygon formed from the given minimums and maximums. Input values must be in SRS specified by the SRID
Geometry / PostGISST_MakeLinegeometry ST_MakeLine(geometry geom1, geometry geom2);ExampleCreates a Linestring from point or line geometries.
Geometry / PostGISST_MakePointgeometry ST_MakePoint(double precision x, double precision y, double precision z, double precision m);ExampleCreates a 2D,3DZ or 4D point geometry.
Geometry / PostGISST_MakePointMgeometry ST_MakePointM(float x, float y, float m);ExampleCreates a point geometry with an x, y, and m coordinate.
Geometry / PostGISST_MakePolygongeometry ST_MakePolygon(geometry outerlinestring, geometry[] interiorlinestrings);ExampleCreates a Polygon formed by the given shell. Input geometries must be closed LINESTRINGS.
Geometry / PostGISST_MLineFromTextgeometry ST_MLineFromText(text WKT, integer srid);ExampleReturn a specified ST_MultiLineString value from WKT representation.
Geometry / PostGISST_MPointFromTextgeometry ST_MPointFromText(text WKT, integer srid);ExampleMakes a Geometry from WKT with the given SRID. If SRID is not give, it defaults to 0.
Geometry / PostGISST_MPolyFromTextgeometry ST_MPolyFromText(text WKT, integer srid);ExampleMakes a MultiPolygon Geometry from WKT with the given SRID. If SRID is not give, it defaults to 0.
Geometry / PostGISST_Pointgeometry ST_Point(float x_lon, float y_lat);ExampleReturns an ST_Point with the given coordinate values. OGC alias for ST_MakePoint.
Geometry / PostGISST_PointFromGeoHashpoint ST_PointFromGeoHash(text geohash, integer precision=full_precision_of_geohash);ExampleReturn a point from a GeoHash string.
Geometry / PostGISST_PointFromTextgeometry ST_PointFromText(text WKT, integer srid);ExampleMakes a point Geometry from WKT with the given SRID. If SRID is not given, it defaults to unknown.
Geometry / PostGISST_PointFromWKBgeometry ST_GeomFromWKB(bytea geom, integer srid);ExampleMakes a geometry from WKB with the given SRID
Geometry / PostGISST_Polygongeometry ST_Polygon(geometry aLineString, integer srid);ExampleReturns a polygon built from the specified linestring and SRID.
Geometry / PostGISST_PolygonFromTextgeometry ST_PolygonFromText(text WKT, integer srid);ExampleMakes a Geometry from WKT with the given SRID. If SRID is not give, it defaults to 0.
Geometry / PostGISST_WKBToSQLgeometry ST_WKBToSQL(bytea WKB);ExampleReturn a specified ST_Geometry value from Well-Known Binary representation (WKB). This is an alias name for ST_GeomFromWKB that takes no srid
Geometry / PostGISST_WKTToSQLgeometry ST_WKTToSQL(text WKT);ExampleReturn a specified ST_Geometry value from Well-Known Text representation (WKT). This is an alias name for ST_GeomFromText
Text Expressionasciifunc.ascii(string) returns intascii('x')=120

func.ascii(get_column(table, 'TAX_SEGMENT'))
ASCII code of the first byte of the argument
Text Expressionbit_lengthfunc.bit_length(string) returns intbit_length('jose')=32Number of bits in string
Text Expressionbtrimfunc.btrim(string text [, characters text]) returns Textbtrim('xyx johnyyx', 'xy')=johnRemove the longest string consisting only of characters in characters (a space by default) from the start and end of string
Text Expressionchar_lengthfunc.char_length(string) or func.character_length(string) returns intchar_leng th('jose')=4Number of characters in string
Text Expressionchrfunc.chr(int) returns Textchr(65)=ACharacter with the given ASCII code
Text Expressionconcatfunc.concat(string, string) returns Textconcat('Post', 'greSQL')=PostgreSQL

func.concat(table.YEAR,'_', table.PERIOD)
String concatenation
Text Expressionconvertfunc.convert(string text, [src_encoding name,]dest_encoding name)convert('text_in_utf8', 'UTF8', 'LATIN1')=text_in_utf8 represented in ISO 8859-1 encodingConvert string to dest_encoding. The original encoding is specified by src_encoding. If src_encoding is omitted, database encoding is assumed.
Text Expressionconvertfunc.convert(string using conversion_name)convert('PostgreSQL' using iso_8859_1_to_utf8)Change encoding using specified conversion name. Conversions can be defined by CREATE CONVERSION. Also there are some pre-defined conversion names. See here for available conversion names.
Text Expressiondecodefunc.decode(string text, type text)Decode binary data from string previously encoded with encode. Parameter type is same as in encode.
Text Expressioninitcapfunc.initcap(string) returns Textinitcap('hi THOMAS')=Hi ThomasConvert the first letter of each word to uppercase and the rest to lowercase. Words are sequences of alphanumeric characters separated by non-alphanumeric characters
Text Expressionintegerize_truncatefunc.integerize_truncate(string)func.integerize_truncate('30.66')=30Takes a single numeric argument x and returns a numeric vector containing the integers formed by truncating the values in x toward 0
Text Expressionintegerize_roundfunc.integerize_round(string)func.integerize_round('30.66') --> 31Rounds the values in its first argument to the specified number of decimal places
Text Expressionlengthfunc.length(string) returns intlength('jose')=4

func.length(get_column(table, 'arrival_date_actual'))
Number of characters in string
Text Expressionlowerfunc.lower(string) returns Textlower('TOM ')=tomConvert string to lower case
Text Expressionlpadfunc.lpad(string text, length int [, fill text]) returns Textlpad('hi', 5, 'xy')=xyxhi

func.lpad('stringtofillup', 10, 'X')=stringtofi
Fill up the string to length length by prepending the characters fill (a space by default). If the string is already longer than length then it is truncated (on the right)
Text Expressionltrimfunc.ltrim(string text [, characters text]) returns Textltrim('zzz yjohn', 'xyz')=john

func.ltrim('texttotrimplaidcloud', 'texttotrim')=plaidcloud

func.ltrim('plaidcloud')=plaidcloud
Remove the longest string containing only characters from characters (a space by default) from the start of string
Text Expressionmd5func.md5(string) returns Textmd5('abc')=900150983cd24fb0d6963f7d28e17f72Calculates the MD5 hash of string, returning the result in hexadecimal
Text Expressionmetric_multiplyfunc.metric_multiply(string)The Multiply function can take multiple metrics as inputs and multiply the values of the metrics
Text Expressionnumericizefunc.numericize(string)func.numericize('100')=100Attempts to coerce a non-numeric R object to natomic_object() or list of {natomic_object}
Text Expressionoctet_lengthfunc.octet_length(string) returns intoctet_length('jose')=4Number of bytes in string
Text Expressionoverlayfunc.overlay(string placing string from int [forint]) returns Textoverlay('Txxxxas' placing 'hom' from 2 for 4)=ThomasReplace a substring (returns: Text)
Text Expressionpositionfunc.position(substring in string) returns intposition('om' in 'Thomas')=3Location of specified substring
Text Expressionquote_literalfunc.quote_literal(string) returns Textquote_literal('O'Reilly')='O''Reilly'

func.quote_literal('plaidcloud')='plaidcloud'
Return the given string suitably quoted to be used as a string literal in an SQL statement string. Embedded single-quotes and backslashes are properly doubled.
Text Expressionregexp_replacefunc.regexp_replace(string text, pattern text, replacement text [,flags text]) returns Textregexp_replace('Thomas', '.[mN]a.', 'M')=ThM
More Examples
Replace substring matching POSIX regular expression.
Text Expressionrepeatfunc.repeat(string text, number int) returns Textrepeat('Pg', 4)=PgPgPgPgRepeat string the specified number of times
Text Expressionreplacefunc.replace(string text, from text, to text) returns Textreplace('abcdefabc def', 'cd', 'XX')=abXXefabX Xef

func.replace('string_to_replace_with_spaces','_',' ') --> string to replace with spaces
Replace all occurrences in string of substring from with substring to
Text Expressionrpadfunc.rpad(string text, length int [, fill text]) returns Textrpad('hi', 5, 'xy')=hixyxFill up the string to length length by appending the characters fill (a space by default). If the string is already longer than length then it is truncated
Text Expressionrtrimfunc.rtrim(string text [, characters text]) returns Textrtrim('johnxxxx', 'x')=johnRemove the longest string containing only characters from characters (a space by default) from the end of string
Text Expressionsplit_partfunc.split_part(string text, delimiter text, field int) returns Textsplit_part('abc~@~def~@~ghi', '~@~', 2)=def

func.split_part(table.PERIOD, '_', 1)
Split string on delimiter and return the given field (counting from one)
Text Expressionstrposfunc.strpos(string, substring) returns intstrpos('high', 'ig')=2Location of specified substring (same as position(subst ring in string), but note the reversed argument order)
Text Expressionsubstrfunc.substr(string, from [, count]) returns Textsubstr('alphabet', 3, 2)=phExtract substring (same as substring(string from from for count))
Text Expressionsubstringfunc.substring(string [from int] [for int]) returns Textsubstring('Thomas' from 2 for 3)=hom

func.substring(table.ship_to_postal_code, 1, 5)
Extract substring
Text Expressionsubstringfunc.substring(string frompattern) returns Textsubstring( 'Thomas' from '…$')=masExtract substring matching POSIX regular expression
Text Expressionsubstringfunc.substring(string frompatternforescape) returns Textsubstring( 'Thomas' from '%#”o_a#” _' for '#')=omaExtract substring matching SQL regular expression
Text Expressiontext_to_bigintfunc.text_to_bigint(string)This function allows you to convert a string of character values into a large range integer
Text Expressiontext_to_boolfunc.text_to_bool(string)Converts the input text or numeric expression to a Boolean value
Text Expressiontext_to_integerfunc.text_to_integer(string)Convert text to integer
Text Expressiontext_to_numericfunc.text_to_numeric(string)This function converts a character string to a numeric value
Text Expressiontext_to_smallintfunc.text_to_smallint(string)A 2-byte integer data type used in CREATE TABLE and ALTER TABLE statements
Text Expressionto_asciifunc.to_ascii(string text [, encoding text]) returns Textto_ascii('Karel')=KarelConvert string to ASCII from another encoding (only supports conversion from LATIN1, LATIN2, LATIN9, and WIN1250 encodings)
Text Expressionto_hexfunc.to_hex(number int or bigint) returns Textto_hex(2147483647)=7fffffffConvert number to its equivalent hexadecimal representation
Text Expressiontranslatefunc.translate(string text, from text, to text) returns Texttranslate( '12345', '14', 'ax')=a23x5Any character in the string that matches a character in the from set is replaced by the corresponding character in the to set
Text Expressiontrimfunc.trim([leading, trailing, both] [characters] from string) returns Texttrim(both 'x' from 'xTomxx')=TomRemove the longest string containing only the characters (a space by default) from the start/end/both ends of the string
Text Expressionupperfunc.upper(string) returns Textupper('tom')=TOMConvert string to uppercase
Arraysstring_to_arrayfunc.string_to_array(text, delimiter)ExamplesThis function is used to split a string into array elements using supplied delimiter and optional null string
Arraysunnestfunc.unnest(text)ExamplesThis function is used to expand an array to a set of rows
Grouping / Summarizationfirstfunc.first(field)This function returns the value of a specified field in the first record of the result set returned by a query
Grouping / Summarizationlastfunc.last(field)This function returns the value of a specified field in the last record of the result set returned by a query
Grouping / Summarizationmaxfunc.max(field)The MAX function is an aggregate function that returns the maximum value in a set of values
Grouping / Summarizationmedianfunc.median(field)This function will calculate the middle value of a given set of numbers
Grouping / Summarizationstdevfunc.stdev(field)The STDEV function calculates the standard deviation for a sample set of data
Grouping / Summarizationstdev_popfunc.stdev_pop(field)STDDEV_POP computes the population standard deviation and returns the square root of the population variance
Grouping / Summarizationstdev_sampfunc.stdev_samp(field)STDDEV_SAMP() function returns the sample standard deviation of an expression
Grouping / Summarizationvar_popfunc.var_pop(field)VAR_POP returns the population variance of a set of numbers after discarding the nulls in this set
Grouping / Summarizationvar_sampfunc.var_samp(field)VAR_SAMP returns the sample variance of a set of numbers after discarding the nulls in this set
Grouping / Summarizationvariancefunc.variance(field)This function is used to determine how far a set of values is spread out based on a sample of the population
JSONarray_to_jsonfunc.array_to_json(array)Returns the array as JSON. A PostgreSQL multidimensional array becomes a JSON array of arrays.
JSONjson_array_elementsfunc.json_array_elements(json)Expands a JSON array to a set of JSON elements.
JSONjson_eachfunc.json_each(json)Expands the outermost JSON object into a set of key/value pairs
JSONjson_each_textfunc.json_each_text(json)Expands the outermost JSON object into a set of key/value pairs. The returned value will be of type text.
JSONjson_extract_pathfunc.json_extract_path(json, key_1, key_2, ...)Returns JSON object pointed to by path elements. The return value will be a type of JSON.
JSONjson_extract_path_textfunc.json_extract_path_text(json, key_1, key_2, ...)Returns JSON object pointed to by path elements. The return value will be a type of text.
JSONjson_object_keysfunc.json_object_keys(json)Returns set of keys in the JSON object. Only the "outer" object will be displayed.
Window Functionsavgfunc.avg().over(partition_by=field, order_by=field)This function returns the average of the values in a group. It ignores null values
Window Functionscountfunc.count().over(partition_by=field, order_by=field)See ExamplesAn aggregate function that returns the number of rows, or the number of non-NULL rows
Window Functionscume_distfunc.cume_dist().over(partition_by=field, order_by=field)This function calculates the cumulative distribution of a value within a group of values
Window Functionsdense_rankfunc.dense_rank().over(partition_by=field, order_by=field)The DENSE_RANK() is a window function that assigns a rank to each row within a partition of a result set
Window Functionsfirst_valuefunc.first_value(field).over(partition_by=field, order_by=field)See ExamplesFIRST_VALUE is a function that returns the first value in an ordered set of values
Window Functionslagfunc.lag(field, 1).over(partition_by=field, order_by=field)See ExamplesThis function lets you query more than one row in a table at a time without having to join the table to itself
Window Functionslast_valuefunc.last_value(field).over(partition_by=field, order_by=field)See ExamplesThe LAST_VALUE() function is a window function that returns the last value in an ordered partition of a result set
Window Functionsleadfunc.lead(field, 1).over(partition_by=field, order_by=field)This function provides access to more than one row of a table at the same time without a self join
Window Functionsminfunc.min().over(partition_by=field, order_by=field)The min() function returns the item with the lowest value, or the item with the lowest value in an iterable
Window Functionsntilefunc.ntile(4).over(partition_by=field, order_by=field)This is a function that distributes rows of an ordered partition into a specified number of approximately equal groups, or buckets
Window Functionspercent_rankfunc.percent_rank().over(partition_by=field, order_by=field)The PERCENT_RANK() function evaluates the relative standing of a value within a partition of a result set
Window Functionsrankfunc.rank().over(partition_by=field, order_by=field)This is a function that assigns a rank to each row within a partition of a result set
Window Functionsrow_numberfunc.row_number().over(partition_by=field, order_by=field)This function is used to provide consecutive numbering of the rows in the result by the order selected in the OVER clause for each partition
Window Functionssumfunc.sum().over(partition_by=field, order_by=field)See ExamplesThe SUM function adds values. You can add individual values, cell references or ranges or a mix of all three

Data Types

There are a wide variety of standard data types (dtypes) to support your requirements. As datasets become larger, determining smaller size dtypes for value storage can shrink the size of the table and improve performance. The following dtypes are available:

  • Boolean
  • Text
  • Numbers
    • SmallFloat (6 Digits)
    • Float (15 Digits)
    • BigFloat
    • SmallInteger (16 bit) (-32768 to 32767)
    • Integer (32 bit) (-2147483648 to 2147483647)
    • BigInteger (64 bit) (-9223372036854775808 to 9223372036854775807)
    • Numeric
  • Dates and Times
    • Date
    • Timestamp
    • Time Interval

You can convert from one dtype to another using the func.cast() process.

Case Examples

A simple example

This example returns a person's name. It starts off searching to see if the first name column has a value (the "if"). If there is a value, concatenate the first name with the last name and return it (the "then"). If there isn't a first name, then return the last name only (the "else").

case(
        (table.first_name.isnot(None), func.concat(table.first_name, table.last_name)), 
        else_ = table.last_name
    )

A more complex example with multiple conditions

This example returns a price based on quantity. "If" the quantity in the order is more than 100, then give the customer the special price. If it doesn't satisfy the first condition, go to the second. If the quantity is greater than 10 (11-100), then give the customer the bulk price. Otherwise give the customer the regular price.

case( 
        (order_table.qty > 100, item_table.specialprice), 
        (order_table.qty > 10, item_table.bulkprice) , 
        else_=item_table.regularprice
    )

This example returns the first initial of the person's first name. If the user's name is wendy, return W. Otherwise if the user's name is jack, return J. Otherwise return E.

case( 
        (users_table.name == "wendy", "W"), 
        (users_table.name == "jack", "J"), 
        else_='E'
    )

The above may also be written in shorthand as:

case(
    {"wendy": "W", "jack": "J"}, 
    value=users_table.name, 
    else_='E' 
)

Other Examples

In this example is from a Table:Lookup step where we are updating the "dock_final" column when the table1. dock_final value is Null.

case(
    (table1.dock_final == Null, table2.dock_final),
    else_ = table1.dock_final
    )

This example is from a Table:Lookup step where we are updating the "Marketing Channel" column when "Marketing Channel" in table1 is not 'none' or the "Serial Number" contains a '_'.

case(
    (get_column(table1, 'Marketing Channel') != 'none', get_column(table1, 'Marketing Channel')),
    (get_column(table1, 'Serial Number').contains('_'), get_column(table1, 'Marketing Channel')),
    (get_column(table2, 'Marketing Channel') != Null, get_column(table2, 'Marketing Channel')), 
    else_ = 'none'
    )
CASE WHEN "sol_otif_pod_missing" = 1 THEN
'POD is missing.'
ELSE
'POD exists.'
END
CASE WHEN
SUM("distance_dc_xd") = 0 THEN 0
ELSE
sum("XD")/sum("distance_dc_xd")
END
sum(CASE WHEN "dc" = 'ALAB' THEN
("sol_otif_infull" * "sol_otif_pgi_ontime")
ELSE
0.0
END) / sum(CASE WHEN "dc" = 'ALAB' THEN
1.0
ELSE
0.000001
END)

func.cast() type conversions

Analyze ExpressionDescriptionResult
func.cast(123, Text)Integer to Text‘123’
func.cast(‘123’, Integer)Text to Integer123
func.cast(‘78.69’, Float)Text to Float78.69
func.cast(‘78.69’, SmallFloat)Text to Small Float78.69
func.cast(‘78.69’, Integer)Text to Integer (Truncate decimals)78
func.cast(‘78.69’, SmallInteger)Text to Small Integer (Truncate decimals)78
func.cast(‘78.69’, BigInteger)Text to Big Integer (Truncate decimals)78
func.cast(1, Boolean)Integer to BooleanTrue

Other Examples cast(table.transaction_year, Numeric) cast(get_column(table, 'End_Date'),Text)

func.to() Data Type Conversions

Analyze ExpressionReturn TypeDescriptionExample
func.to_char(timestamp, text)textconvert time stamp to text stringto_char(current_timestamp, ‘HH12:MI:S S’)
func.to_char(interval, text)textconvert interval to stringto_char(interval ‘15h 2m 12s’, ‘HH24:MI:S S’)
func.to_char(integer, text)textconvert integer to stringto_char(125, ‘999’)
func.to_char(bigfloat, text)textconvert real/double precision to stringto_char(125.8::real, ‘999D9’)
func.to_char(numeric, text)textconvert numeric to stringto_char(-125.8, ‘999D99S’)
func.to_date(text, text)dateconvert string to datefunc.to_date(table.Created_on, 'DD-MM-YYYY')
func.to_number(text, text)numericconvert string to numericto_number (‘12,454.8 -‘, ‘99G999D9S ‘)
func.to_timestamp(text, text)timestamp with time zoneconvert string to time stampto_timestamp(‘05 Dec 2000’, ‘DD Mon YYYY’)
func.to_timestamp(bigfloat)timestamp with time zoneconvert UNIX epoch to time stampto_timestamp(200120400)

Other Examples

to_char("Sales_Order_w_Status"."WeekName")

func.to_char(func.date_trunc('week', get_column(table, 'date_sol_delivery_required')), 'YYYY-MM-DD')

func.to_date(get_column(table, 'File Creation Date'), 'YYYYMMDD')

result.CreateDate<func.to_date('09022022', 'MMDDYYYY')

to_char("date_delivery", 'YYYY-mm-dd')

Other Date Time Examples

Date Trunc

func.date_trunc('week', get_column(table, 'Date' ))

func.to_char(func.date_trunc('week', get_column(table, 'date_sol_delivery_required')), 'YYYY-MM-DD')

func.to_char(func.date_trunc('week', ((table.Date) - 6)),'MON-DD')

The following patterns can be used to select specific parts of a timestamp or to format date/time as desired.

PatternDescription
HHhour of day (01-12)
HH12hour of day (01-12)
HH24hour of day (00-23)
MIminute (00-59)
SSsecond (00-59)
MSmillisecond (000-999)
USmicrosecond (000000-999999 )
SSSSseconds past midnight (0-86399)
AM or A.M. or PM or P.M.meridian indicator (uppercase)
am or a.m. or pm or p.m.meridian indicator (lowercase)
Y,YYYyear (4 and more digits) with comma
YYYYyear (4 and more digits)
YYYlast 3 digits of year
YYlast 2 digits of year
Ylast digit of year
IYYYISO year (4 and more digits)
IYYlast 3 digits of ISO year
IYlast 2 digits of ISO year
Ilast digits of ISO year
BC or B.C. or AD or A.D.era indicator (uppercase)
bc or b.c. or ad or a.d.era indicator (lowercase)
MONTHfull uppercase month name (blank-padded to 9 chars)
Monthfull mixed-case month name (blank-padded to 9 chars)
monthfull lowercase month name (blank-padded to 9 chars)
MONabbreviated uppercase month name (3 chars)
Monabbreviated mixed-case month name (3 chars)
monabbreviated lowercase month name (3 chars)
MMmonth number (01-12)
DAYfull uppercase day name (blank-padded to 9 chars)
Dayfull mixed-case day name (blank-padded to 9 chars)
dayfull lowercase day name (blank-padded to 9 chars)
DYabbreviated uppercase day name (3 chars)
Dyabbreviated mixed-case day name (3 chars)
dyabbreviated lowercase day name (3 chars)
DDDday of year (001-366)
DDday of month (01-31)
Dday of week (1-7; Sunday is 1)
Wweek in month (1-5) (The first week starts on the first day of the month.)
WWweek number in year (1-53) (The first week starts on the first day of the year.)
IWISO week number of year (The first Thursday of the new year is in week 1.)
CCcentury (2 digits)
JJulian Day (days since January 1, 4712 BC)
Qquarter
RMmonth in Roman numerals (I-XII; I=January) (uppercase)
rmmonth in Roman numerals (i-xii; i=January) (lowercase)
TZtime-zone name (uppercase)
tztime-zone name (lowercase)

And Operator

Example 1

This example checks if the period is any of the three specified dates.

and_(  
    table.color == 'green',  
    table.shape == 'circle',  
    table.price >= 1.25  
)

Example 2

This example is checking if to ensure the origin_plant is not one of the values specified. This is using the != expression.

and_(  
    table.origin_plant != '5013',  
    table.origin_plant != '5026',  
    table.origin_plant != '5120',  
    table.origin_plant != '5287',  
    table.origin_plant != '5161',  
    table.origin_plant != '5192'  
)

Alternatively, for reference, the above check could be written using the not_ and or_ operators like this:

not_(  
    or_(  
        table.origin_plant == '5013',  
        table.origin_plant == '5026',  
        table.origin_plant == '5120',  
        table.origin_plant == '5287',  
        table.origin_plant == '5161',  
        table.origin_plant == '5192'  
    )  
)

Other Examples

and_(table.origin_plant != '5013',table.origin_plant != '5026')

Not Operator

not_(and_(table.VALUE_FC==0.0, table.VALUE_LC==0.0))

not_(or_(get_column(table, 'GL Account').startswith('7'), get_column(table, 'GL Account').startswith('8')))

Or Operator

Example 1 This example checks if the period is any of the three specified dates.

or_(  
    table.period == '2020_10',  
    table.period == '2020_11',  
    table.period == '2020_12'  
)

Example 2 This example is checking if order_reason_Include is null or has the word KEEP as a value.

or_(  
    table.order_reason_Include == 'KEEP',  
    table.order_reason_Include.is_(None)  
)

Coalesce Examples

func.coalesce(table.UOM,  'none', \n)

func.coalesce(get_column(table2, 'TECHNOLOGY_RATE'), 0.0)

func.coalesce(table_beta.adjusted_price, table_alpha.override_price, table_alpha.price) * table_beta.quantity_sold

Regexp Replace Examples

func.regexp_replace('plaidcloud', 'p', 'P') --> Plaidcloud

func.regexp_replace('remove12345alphabets','[[:alpha:]]','','g') --> 12345

func.regexp_replace('remove12345digits','[[:digit:]]','','g') --> removedigits

First Value Examples

This is an example of using the 'first_value()' capability to calculate the running time of the time series data where each event is on a distinct row.

This assumes you have a table of time series data that looks like this:

locationemployeetimestamp
Building AJohn Doe2022-01-05 15:34:31
Building AJohn Doe2022-01-05 15:44:31
Building AJohn Doe2022-01-05 15:46:41
table.timestamp - func.first_value(table.timestamp, 1).over(partition_by=[table.location, table.employee], order_by=table.timestamp)

Adding the expression above to an Interval column called 'run_time' would result in an output table like this:

locationemployeetimestamprun_time
Building AJohn Doe2022-01-05 15:34:3100:00:00
Building AJohn Doe2022-01-05 15:44:3100:10:00
Building AJohn Doe2022-01-05 15:46:4100:12:10

Lag Examples

This is an example of using the 'lag()' capability to calculate the time interval in time series data where each event is on a distinct row.

This assumes you have a table of time series data that looks like this:

locationemployeetimestamp
Building AJohn Doe2022-01-05 15:34:31
Building AJohn Doe2022-01-05 15:44:31
Building AJohn Doe2022-01-05 15:46:41
table.timestamp - func.lag(table.timestamp, 1).over(partition_by=[table.location, table.employee], order_by=table.timestamp)

Adding the expression above to an Interval column called 'delta' would result in an output table like this:

locationemployeetimestampdelta
Building AJohn Doe2022-01-05 15:34:31null
Building AJohn Doe2022-01-05 15:44:3100:10:00
Building AJohn Doe2022-01-05 15:46:4100:02:10

Last Value Examples

This is an example of using the 'last_value()' capability to calculate the time remaining in time series data where each event is on a distinct row.

This assumes you have a table of time series data that looks like this:

locationemployeetimestamp
Building AJohn Doe2022-01-05 15:34:31
Building AJohn Doe2022-01-05 15:44:31
Building AJohn Doe2022-01-05 15:46:41
func.last_value(table.timestamp, 1).over(partition_by=[table.location, table.employee], order_by=table.timestamp) - table.timestamp

Adding the expression above to an Interval column called 'remaining' would result in an output table like this:

locationemployeetimestampremaining
Building AJohn Doe2022-01-05 15:34:3100:12:10
Building AJohn Doe2022-01-05 15:44:3100:02:10
Building AJohn Doe2022-01-05 15:46:4100:00:00

Sum Examples

(sum("sol_otif_infull" * "sol_otif_pgi_ontime")) / (count(*) + 0.000001)

sum("sol_otif_qty_filled") / (sum("sol_otif_qty_requested") + 0.000001)

Count Examples

sum("RW")/COUNT(DISTINCT "ship_to_customer")

(sum("sol_otif_infull" * "sol_otif_pgi_ontime")) / (count(*) + 0.000001)

Array Examples

In the examples below, we will use the following table called contacts with the phones column defined with an array of text.

CREATE TABLE contacts (
  id SERIAL PRIMARY KEY, 
  name VARCHAR (100), 
  phones TEXT []
);

The phones column is a one-dimensional array that holds various phone numbers that a contact may have.

To define multiple dimensional array, you add the square brackets.

For example, you can define a two-dimensional array as follows:

column_name data_type [][]

An example of inserting data into that table

INSERT INTO contacts (name, phones)
VALUES('John Doe',ARRAY [ '(408)-589-5846','(408)-589-5555' ]);

or

INSERT INTO contacts (name, phones)
VALUES('Lily Bush','{"(408)-589-5841"}'),
      ('William Gate','{"(408)-589-5842","(408)-589-5843"}');

Array unnest

The unnest() function expands an array to a list of rows. For example, the following query expands all phone numbers of the phones array.

SELECT 
  name, 
  unnest(phones) 
FROM 
  contacts;

Output:

nameunnest
John Doe(408)-589-5846
John Doe(408)-589-5555
Lily Bush(408)-589-5841
William Gate(408)-589-5843

STRING_TO_ARRAY() function

This function is used to split a string into array elements using supplied delimiter and optional null string.

Syntax:
string_to_array(text, text [, text])

Return Type:
text[]

Example:

SELECT string_to_array('xx~^~yy~^~zz', '~^~', 'yy');

Output:
{xx,NULL,zz}

Last modified April 01, 2024 at 4:48 PM EST: Round of edits (5f63990)