Using PostgreSQL 9.3. Have a column with file name values like that:
qwerty.swf
some.image.jpg
some.other.image.jpg
This column also allow null values.
How to get file extensions from this column in sql query?
Using PostgreSQL 9.3. Have a column with file name values like that:
qwerty.swf
some.image.jpg
some.other.image.jpg
This column also allow null values.
How to get file extensions from this column in sql query?
try :
with mytable as (
select unnest(string_to_array($$qwerty.swf
some.image.jpg
some.other.image.jpg
test
$$,E'\n')) filename)
select filename,substring(filename from '\.([^\.]*)$')
from mytable
Use regexp
to do this.
select regexp_matches(filename,'\.(\w+)$')
from tablename
where filename ~ '\.' --check if filename has atleast 1 . character in it
Or a combination of substring
, reverse
and strpos
.
select reverse(substring(reverse(filename) from 1 for strpos(reverse(filename),'.')-1))
from tablename
where filename ~ '\.' --check if filename has atleast 1 . character in it
In case you want to extract the extension of a file from an URL, the thing is slightly more difficult, as a short URL such as https://whatever.com
could be taken for a file descriptor, resulting in com
as an extension.
This is my approach.
create or replace function url_ext (s varchar)
returns varchar
immutable language sql as $$
select substring(s from '^http[s]?:\/\/.*\/.*\.([A-z0-9_-]*)$');
$$;
And these are some tests:
select
url_ext('http://whatever.com'),
url_ext('https://whatever.com'),
url_ext('https://whatever.com/something/more/file.pdf'),
url_ext('https://whatever.com/file.pdf'),
url_ext('https://whatever.com/something/more/slug');
url_ext|url_ext|url_ext|url_ext|url_ext|
-------+-------+-------+-------+-------+
| |pdf |pdf | |
© 2022 - 2024 — McMap. All rights reserved.