Skip to content

Instantly share code, notes, and snippets.

@osamaishtiaq
Last active April 6, 2019 18:13
Show Gist options
  • Save osamaishtiaq/80241a9038b9d63e4e4c52a947d86d74 to your computer and use it in GitHub Desktop.
Save osamaishtiaq/80241a9038b9d63e4e4c52a947d86d74 to your computer and use it in GitHub Desktop.
Check Possible Data Type of a string using pattern matching in PostgreSQL and Return Count.
SELECT COUNT(1) AS COUNT, 'Decimal' as DataType
FROM @TableName
WHERE @ColumnName ~ '^\d+\.\d+$'
UNION ALL
SELECT COUNT(1) AS COUNT, 'Integer' as DataType
FROM @TableName
WHERE @ColumnName ~ '^\+?(0|[1-9]\d*)$'
UNION ALL
SELECT COUNT(1) AS COUNT, 'Date' as DataType
FROM @TableName
WHERE @ColumnName ~ '^((0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])[- /.](19|20)?[0-9]{2})*$'
UNION ALL
SELECT COUNT(1) AS COUNT, 'Time' as DataType
FROM @TableName
WHERE @ColumnName ~ '^(?:1[0-2]|0?[0-9]):[0-5][0-9]:[0-5][0-9] (AM|PM|am|pm)$'
UNION ALL
SELECT COUNT(1) AS COUNT, 'DateTime' AS DataType
FROM @TableName
WHERE @ColumnName ~ '^((0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])[- /.](19|20)?[0-9]{2})\s(?:1[0-2]|0?[0-9]):[0-5][0-9]:[0-5][0-9] (AM|PM|am|pm)$'
@osamaishtiaq
Copy link
Author

Functions like IsNull and IsNumeric are not available in PostgreSQL and checking via parsing requires exception handling on parse failure as well as the need to create custom functions. Above is an efficient way to check for possible datatype of a string value in PostgreSQL using pattern matching.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment