What should be the data type of field 'email' in Postgresql database in pgadmin 4?

Viewed 7735

You can see that I am getting 'No results found' when searching for varchar.

enter image description hereI need to know the data type that I should select for 'email' in postgresql database.

2 Answers

In the past I used text or varchar or character varying

Apart from using of VARCHAR (as suggested by @Maria), you might get some insight from this link: https://www.dbrnd.com/2018/04/postgresql-how-to-validate-the-email-address-column/ and from this https://dba.stackexchange.com/questions/68266/what-is-the-best-way-to-store-an-email-address-in-postgresql

if you read some parts of it, they created their own functions or constraints, which would likely help you in understanding PSQL more.

TL/DR, or the links might change in the future (shamelessly taken from one of the links):

CREATE EXTENSION citext;
CREATE DOMAIN domain_email AS citext
CHECK(
   VALUE ~ '^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$'
);
-- for valid samples
SELECT 'some_email@gmail.com'::domain_email;
SELECT 'accountant@dbrnd.org'::domain_email;
-- for an invalid sample
SELECT 'dba@aol.info'::domain_email;

As Neil had pointed out, yeah it's just like using custom TYPES.

CREATE DOMAIN creates a new domain. A domain is essentially a data type with optional constraints (restrictions on the allowed set of values). source

For those of you unfamiliar with the weird characters used to check the value, it's a regex pattern.

And an example used with a table:

CREATE TABLE sample_table ( id SERIAL PRIMARY KEY, email domain_email );

-- The following is invalid, because ".info" has 4 characters
-- the regex pattern only allows 2-3 characters
INSERT INTO sample_table (email) VALUES ('sample_email@gmail.info');
ERROR:  value for domain domain_email violates check constraint "domain_email_check"

-- The following query is valid
INSERT INTO sample_table (email) VALUES ('sample_email@gmail.com');
SELECT * FROM sample_table;
 id |         email
----+------------------------
  1 | sample_email@gmail.com
(1 row)

Thanks Neil for the suggestion.

Related