Skip to content

Instantly share code, notes, and snippets.

@ben-nour
Last active August 12, 2024 02:25
Show Gist options
  • Save ben-nour/19b4a6c63e376efeab58df923ecba1df to your computer and use it in GitHub Desktop.
Save ben-nour/19b4a6c63e376efeab58df923ecba1df to your computer and use it in GitHub Desktop.
Snowflake UDF to extract FY from a date.
CREATE OR REPLACE FUNCTION extract_fy(date_to_convert varchar, date_format varchar DEFAULT 'YYYY-MM-DD')
RETURNS VARCHAR
LANGUAGE SQL
AS
$$
SELECT
CASE
WHEN MONTH(TRY_TO_DATE(date_to_convert, date_format)) >= 7 THEN
CONCAT('FY', RIGHT(YEAR(TRY_TO_DATE(date_to_convert, date_format)) + 1, 2))
ELSE CONCAT('FY', RIGHT(YEAR(TRY_TO_DATE(date_to_convert, date_format)), 2))
END AS financial_year
$$
;
@ben-nour
Copy link
Author

Note that this is for Australia.

The Australian financial year starts on 1 July, with the last day occurring the following year on 30 June.

@ben-nour
Copy link
Author

Examples:

SELECT EXTRACT_FY('2024-07-01')
FY25

SELECT EXTRACT_FY('07-01-2024', 'MM-DD-YYYY')
FY25

SELECT EXTRACT_FY('2024-06-30')
FY24

SELECT EXTRACT_FY('2024')
[NULL]

SELECT EXTRACT_FY('2024', 'YYYY')
FY24

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