All topics

PostgreSQL interview questions

32 questions, 31 with answers. 979 open jobs in India ask for PostgreSQL.

  1. Which version of PostgreSQL am I running?

    Run this query from PostgreSQL:

    SELECT version();
    

    From Stack Overflow: asked by Highly Irregular, answered by Highly Irregular (CC BY-SA 3.0)

  2. Difference between text and varchar (character varying)

    There is no difference, under the hood it's all varlena (variable length array).

    Check this article from Depesz: http://www.depesz.com/index.php/2010/03/02/charx-vs-varcharx-vs-varchar-vs-text/

    A couple of highlights:

    To sum it all up:

    • char(n) – takes too much space when dealing with values shorter than n (pads them to n), and can lead to subtle errors because of adding trailing spaces, plus it is problematic to change the limit
    • varchar(n) – it's problematic to change the limit in live environment (requires exclusive lock while altering table)
    • varchar – just like text
    • text – for me a winner – over (n) data types because it lacks their problems, and over varchar – because it has distinct name

    The article does detailed testing to show that the performance of inserts and selects for all 4 data types are similar. It also takes a detailed look at alternate ways on constraining the length when needed. Function based constraints or domains provide the advantage of instant increase of the length constraint, and on the basis that decreasing a string length constraint is rare, depesz concludes that one of them is usually the best choice for a length limit.

    From Stack Overflow: asked by Adam Matan, answered by Frank Heikens (CC BY-SA 4.0)

  3. What is the format for the PostgreSQL connection string / URL?

    If you use Libpq binding for respective language, according to its documentation URI is formed as follows:

    postgresql://[user[:password]@][netloc][:port][/dbname][?param1=value1&...]
    

    Here are examples from same document

    postgresql://
    postgresql://localhost
    postgresql://localhost:5432
    postgresql://localhost/mydb
    postgresql://user@localhost
    postgresql://user:secret@localhost
    postgresql://other@localhost/otherdb?connect_timeout=10&application_name=myapp
    postgresql://localhost/mydb?user=other&password=secret
    

    From Stack Overflow: asked by JII, answered by Andrey (CC BY-SA 3.0)

  4. What's the PostgreSQL datatype equivalent to MySQL AUTO INCREMENT?

    Yes, SERIAL is the equivalent function.

    CREATE TABLE foo (
        id SERIAL,
        bar varchar
    );
    INSERT INTO foo (bar) VALUES ('blah');
    INSERT INTO foo (bar) VALUES ('blah');
    SELECT * FROM foo;
    +----------+
    | 1 | blah |
    +----------+
    | 2 | blah |
    +----------+
    

    SERIAL is just a create table time macro around sequences. You can not alter SERIAL onto an existing column.

    From Stack Overflow: asked by Ian, answered by Trey (CC BY-SA 4.0)

  5. Where does PostgreSQL store configuration/conf files?

    Or ask your database:

    $ psql -U postgres -c 'SHOW config_file'
    

    or, if logged in as the ubuntu user:

    $ sudo -u postgres psql -c 'SHOW config_file'
    

    From Stack Overflow: asked by Timur Sadykov, answered by Frank Heikens (CC BY-SA 4.0)

  6. Where does PostgreSQL store the database?

    To see where the data directory is, use this query.

    show data_directory;
    

    To see all the run-time parameters, use

    show all;
    

    You can create tablespaces to store database objects in other parts of the filesystem. To see tablespaces, which might not be in that data directory, use this query.

    SELECT *, pg_tablespace_location(oid) FROM pg_tablespace;
    

    From Stack Overflow: asked by Teifion, answered by Mike Sherrill 'Cat Recall' (CC BY-SA 4.0)

  7. How to show tables in PostgreSQL?

    From the psql command line interface,

    First, choose your database

    \c database_name
    

    Then, this shows all tables in the current schema:

    \dt
    

    Programmatically (or from the psql interface too, of course):

    SELECT * FROM pg_catalog.pg_tables;
    

    The system tables live in the pg_catalog database.

    From Stack Overflow: asked by flybywire, answered by Mihai Limbășan (CC BY-SA 4.0)

  8. PostgreSQL "DESCRIBE TABLE"

    Try this (in the psql command-line tool):

    \d+ tablename
    

    See the manual for more info.

    From Stack Overflow: asked by Mr. Muskrat, answered by Chris Bunch (CC BY-SA 3.0)

  9. How can I change a PostgreSQL user password?

    To log in without a password:

    sudo -u user_name psql db_name
    

    To reset the password if you have forgotten:

    ALTER USER user_name WITH PASSWORD 'new_password';
    

    From Stack Overflow: asked by Saad, answered by solaimuruganv (CC BY-SA 4.0)

  10. How to exit from PostgreSQL command line utility: psql?

    Type \q and then press ENTER to quit psql.

    UPDATE: 19-OCT-2018

    As of PostgreSQL 11, the keywords "quit" and "exit" in the PostgreSQL command-line interface have been included to help make it easier to leave the command-line tool.

    From Stack Overflow: asked by App Work, answered by Frankline (CC BY-SA 4.0)

  11. How can I drop all the tables in a PostgreSQL database?

    If all of your tables are in a single schema, this approach could work (below code assumes that the name of your schema is public)

    DROP SCHEMA public CASCADE;
    CREATE SCHEMA public;
    

    If you are using PostgreSQL 9.3 or later, you may also need to restore the default grants.

    GRANT ALL ON SCHEMA public TO postgres;
    GRANT ALL ON SCHEMA public TO public;
    

    From Stack Overflow: asked by AP257, answered by Derek Slife (CC BY-SA 4.0)

  12. How to switch databases in psql?

    In PostgreSQL, you can use the \connect meta-command of the client tool psql:

    \connect DBNAME
    

    or in short:

    \c DBNAME
    

    Note that it is not possible to switch the current database via an SQL command, like you asked.

    MySQL's USE DatabaseName is named somewhat confusingly, because what MySQL calls a "database" is more similar to what other systems (like Oracle or PostgreSQL) call a "schema" (and PostgreSQL also lets you access multiple schemas from a single SQL session). To quote the official documentation:

    Users coming from an Oracle Database background may find that the MySQL meaning of a database is closer to what Oracle Database calls a schema.

    From Stack Overflow: asked by Blankman, answered by Will Hartung (CC BY-SA 4.0)

  13. Save PL/pgSQL output from PostgreSQL to a CSV file

    Do you want the resulting file on the server, or on the client?

    Server side

    If you want something easy to re-use or automate, you can use Postgresql's built in COPY command. e.g.

    Copy (Select * From foo) To '/tmp/test.csv' With CSV DELIMITER ',' HEADER;
    

    This approach runs entirely on the remote server - it can't write to your local PC. It also needs to be run as a Postgres "superuser" (normally called "root") because Postgres can't stop it doing nasty things with that machine's local filesystem.

    That doesn't actually mean you have to be connected as a superuser (automating that would be a security risk of a different kind), because you can use the SECURITY DEFINER option to CREATE FUNCTION to make a function which runs as though you were a superuser.

    The crucial part is that your function is there to perform additional checks, not just by-pass the security - so you could write a function which exports the exact data you need, or you could write something which can accept various options as long as they meet a strict whitelist. You need to check two things:

    1. Which files should the user be allowed to read/write on disk? This might be a particular directory, for instance, and the filename might have to have a suitable prefix or extension.
    2. Which tables should the user be able to read/write in the database? This would normally be defined by GRANTs in the database, but the function is now running as a superuser, so tables which would normally be "out of bounds" will be fully accessible. You probably don’t want to let someone invoke your function and add rows on the end of your “users” table…

    I've written a blog post expanding on this approach, including some examples of functions that export (or import) files and tables meeting strict conditions.

    Client side

    The other approach is to do the file handling on the client side, i.e. in your application or script. The Postgres server doesn't need to know what file you're copying to, it just spits out the data and the client puts it somewhere.

    The underlying syntax for this is the COPY TO STDOUT command, and graphical tools like pgAdmin will wrap it for you in a nice dialog.

    The psql command-line client has a special "meta-command" called \copy, which takes all the same options as the "real" COPY, but is run inside the client:

    \copy (Select * From foo) To '/tmp/test.csv' With CSV DELIMITER ',' HEADER
    

    Note that there is no terminating ;, because meta-commands are terminated by newline, unlike SQL commands.

    From the docs:

    Do not confuse COPY with the psql instruction \copy. \copy invokes COPY FROM STDIN or COPY TO STDOUT, and then fetches/stores the data in a file accessible to the psql client. Thus, file accessibility and access rights depend on the client rather than the server when \copy is used.

    Your application programming language may also have support for pushing or fetching the data, but you cannot generally use COPY FROM STDIN/TO STDOUT within a standard SQL statement, because there is no way of connecting the input/output stream. PHP's PostgreSQL handler (not PDO) includes very basic pg_copy_from and pg_copy_to functions which copy to/from a PHP array, which may not be efficient for large data sets.

    From Stack Overflow: asked by Hoff, answered by IMSoP (CC BY-SA 4.0)

  14. Creating a copy of a database in PostgreSQL

    Postgres allows the use of any existing database on the server as a template when creating a new database. I'm not sure whether pgAdmin gives you the option on the create database dialog but you should be able to execute the following in a query window if it doesn't:

    CREATE DATABASE newdb WITH TEMPLATE originaldb OWNER dbuser;
    

    Still, you may get:

    ERROR:  source database "originaldb" is being accessed by other users
    

    To disconnect all other users from the database, you can use this query:

    SELECT pg_terminate_backend(pg_stat_activity.pid) FROM pg_stat_activity 
    WHERE pg_stat_activity.datname = 'originaldb' AND pid <> pg_backend_pid();
    

    From Stack Overflow: asked by egaga, answered by Bell (CC BY-SA 4.0)

  15. How to do an update + join in PostgreSQL?

    The UPDATE syntax is:

    [ WITH [ RECURSIVE ] with_query [, ...] ]
    UPDATE [ ONLY ] table [ [ AS ] alias ]
        SET { column = { expression | DEFAULT } |
              ( column [, ...] ) = ( { expression | DEFAULT } [, ...] ) } [, ...]
        [ FROM from_list ]
        [ WHERE condition | WHERE CURRENT OF cursor_name ]
        [ RETURNING * | output_expression [ [ AS ] output_name ] [, ...] ]
    

    In your case I think you want this:

    UPDATE vehicles_vehicle AS v 
    SET price = s.price_per_vehicle
    FROM shipments_shipment AS s
    WHERE v.shipment_id = s.id 
    

    Or if you need to join on two or more tables:

    UPDATE table_1 t1
    SET foo = 'new_value'
    FROM table_2 t2
        JOIN table_3 t3 ON t3.id = t2.t3_id
    WHERE
        t2.id = t1.t2_id
        AND t3.bar = True;
    

    From Stack Overflow: asked by mpen, answered by Mark Byers (CC BY-SA 4.0)

  16. How to drop a PostgreSQL database if there are active connections to it?

    This will drop existing connections except for yours:

    Query pg_stat_activity and get the pid values you want to kill, then issue SELECT pg_terminate_backend(pid int) to them.

    PostgreSQL 9.2 and above:

    SELECT pg_terminate_backend(pg_stat_activity.pid)
    FROM pg_stat_activity
    WHERE pg_stat_activity.datname = 'TARGET_DB' -- ← change this to your DB
      AND pid <> pg_backend_pid();
    

    PostgreSQL 9.1 and below:

    SELECT pg_terminate_backend(pg_stat_activity.procpid)
    FROM pg_stat_activity
    WHERE pg_stat_activity.datname = 'TARGET_DB' -- ← change this to your DB
      AND procpid <> pg_backend_pid();
    

    Once you disconnect everyone you will have to disconnect and issue the DROP DATABASE command from a connection from another database aka not the one your trying to drop.

    Note the renaming of the procpid column to pid. See this mailing list thread.

    From Stack Overflow: asked by Roman Prykhodchenko, answered by Kuberchaun (CC BY-SA 4.0)

  17. Run a PostgreSQL .sql file using command line arguments

    Of course, you will get a fatal error for authenticating, because you do not include a user name...

    Try this one, it is OK for me :)

    psql -U username -d myDataBase -a -f myInsertFile
    

    If the database is remote, use the same command with host

    psql -h host -U username -d myDataBase -a -f myInsertFile
    

    From Stack Overflow: asked by CSharpened, answered by pmverma (CC BY-SA 3.0)

  18. What is faster, one big query or many small queries?

    What would address your question is the subject JOIN DECOMPOSITION.

    According to Page 209 of the Book

    You can decompose a join by running multiple single-table queries instead of a multitable join, and then performing the join in the application. For example, instead of this single query:

    SELECT * FROM tag
    JOIN tag_post ON tag_post.tag_id = tag.id
    JOIN post ON tag_post.post_id = post.id
    WHERE tag.tag = 'mysql';
    

    You might run these queries:

    SELECT * FROM tag WHERE tag = 'mysql';
    SELECT * FROM tag_post WHERE tag_id=1234;
    SELECT * FROM post WHERE post.id IN (123,456,567,9098,8904);
    

    Why on earth would you do this ? It looks wasteful at first glance, because you've increased the number of queries without getting anything in return. However, such restructuring can actually give significant performance advantages:

    • Caching can be more efficient. Many applications cache "objects" that map directly to tables. In this example, if the object with the tag mysql is already cached, the application will skip the first query. If you find posts with an ID of 123, 567, or 908 in the cache, you can remove them from the IN() list. The query cache might also benefit from this strategy. If only one of the tables changes frequently, decomposing a join can reduce the number of cache invalidations.
    • Executing the queries individually can sometimes reduce lock contention
    • Doing joins in the application makes it easier to scale the database by placing tables on different servers.
    • The queries themselves can be more efficient. In this example, using an IN() list instead of a join lets MySQL sort row IDs and retrieve rows more optimally than might be possible with a join.
    • You can reduce redundant row accesses. Doing a join in the application means retrieving each row only once., whereas a join in the query is essentially a denormalization that might repeatedly access the same data. For the same reason, such restructuring might also reduce the total network traffic and memory usage.
    • To some extent, you can view this technique as manually implementing a hash join instead of the nested loops algorithm MySQL uses to execute a join. A hash join might be more efficient.

    As a result, doings joins in the application can be more efficient when you cache and reuse a lot of data from earlier queries, you distribute data across multiple servers, you replace joins with IN() lists, or a join refers to the same table multiple times.

    OBSERVATION

    I like the first bulletpoint because InnoDB is a little heavy-handed when it crosschecks the query cache.

    As for the last bulletpoint, I wrote a post back on Mar 11, 2013 (Is there an execution difference between a JOIN condition and a WHERE condition?) that describes the nested loop algorithm. After reading it, you will see how good join decomposition may be.

    Read the rest at the sourceFrom Database Administrators Stack Exchange: asked by sudo.ie, answered by RolandoMySQLDBA (CC BY-SA 4.0)

  19. What is the search_path for a given database and user?

    You can find configuration settings for roles and databases in the catalog table pg_db_role_setting.

    This query retrieves any settings for a given role or database:

    SELECT r.rolname, d.datname, rs.setconfig
    FROM   pg_db_role_setting rs
    LEFT   JOIN pg_roles      r ON r.oid = rs.setrole
    LEFT   JOIN pg_database   d ON d.oid = rs.setdatabase
    WHERE  r.rolname = 'myrole' OR d.datname = 'mydb';
    

    If nothing is set, the next lower instance determines the default state of the search_path, which is postgresql.conf in this case or command-line options at server start. Related:

    To unset any settings of a role or database - the search_path in this particular example:

    ALTER ROLE myrole RESET search_path;
    

    Or:

    ALTER DATABASE mydb RESET search_path;
    

    Or:

    ALTER ROLE myrole IN DATABASE mydb RESET search_path;
    

    Never manipulate data in the system catalog (pg_catalog.*) manually. Use DDL commands as instructed in the manual for ALTER ROLE and ALTER DATABASE.
    Essentially, the ALTER ROLE ... RESET command deletes a row from pg_db_role_setting allowing the base setting to take effect again. I wouldn't call that convoluted.

    All of this alters presets. One can always SET or RESET the setting of the current session.

    From Database Administrators Stack Exchange: asked by user664833, answered by Erwin Brandstetter (CC BY-SA 4.0)

  20. Are views harmful for performance in PostgreSQL?

    The book is wrong.

    Selecting from a view is exactly as fast or slow as running the underlying SQL statement – you can easily check that using explain analyze.

    The Postgres optimizer (and the optimizer for many other modern DBMSes) will be able to push down predicates on the view into the actual view statement – provided this is a simple statement (again, this can be verified using explain analyze).

    The "bad reputation" regarding performance stems – I think – from when you overuse views and start building views that use views that use views. Very often that results in statements that do too much compared to a statement that was hand-tailored without the views e.g. because some intermediate tables wouldn't be needed. In almost all cases the optimizer is not smart enough to remove those unneeded tables/joins or to push down predicates over multiple levels of views (this is true for other DBMSes as well).

    From Database Administrators Stack Exchange: asked by ARX, answered by user1822 (CC BY-SA 3.0)

  21. Should I add an arbitrary length limit to VARCHAR columns?

    The answer is no.

    Related advice in the Postgres Wiki.

    Don't add a length modifier to varchar if you don't need it. (Most of the time, you don't.) Just use text for all character data. Make that varchar (standard SQL type) without length modifier if you need to stay compatible with RDBMS which don't have text as generic character string type.

    Performance is almost the same, text is a bit faster in rare situations, and you save the cycles for the check on the length.

    A particularly common misconception is varchar(255), which hardly ever makes sense in Postgres. Often carried over from other (outdated) RDBMS, where the particular limit has performance benefits. That's not true for Postgres. See:

    If you actually need to enforce a maximum length, varchar(n) is a valid choice. But I would still consider text with a CHECK constraint like:

    ALTER TABLE tbl ADD CONSTRAINT tbl_col_len CHECK (length(col) < 51);
    

    You can modify or drop such a constraint at any time without having to mess with the table definition and depending objects (views, functions, foreign keys, ...). And you can enforce other requirements in the (same) constraint.

    Length modifiers used to cause problems like this or this or this ...

    PostgreSQL 9.1 introduced a new feature to alleviate the pain somewhat. The release notes:

    Allow ALTER TABLE ... SET DATA TYPE to avoid table rewrites in appropriate cases (Noah Misch, Robert Haas)

    For example, converting a varchar column to text no longer requires a rewrite of the table. However, increasing the length constraint on a varchar column still requires a table rewrite.

    More issues with varchar(n) have been fixed in later releases.

    From Database Administrators Stack Exchange: asked by Daniel Serodio, answered by Erwin Brandstetter (CC BY-SA 4.0)

  22. Do stored procedures prevent SQL injection?

    No, stored procedures do not prevent SQL injection. Here's an actual example (from an in-house app someone created where I work) of a stored procedure that unfortunately permits SQL injection:

    This sql server code:

    CREATE PROCEDURE [dbo].[sp_colunmName2]   
        @columnName as nvarchar(30),
        @type as nvarchar(30), 
        @searchText as nvarchar(30)           
    AS
    BEGIN
        DECLARE @SQLStatement NVARCHAR(4000)
        BEGIN
            SELECT @SQLStatement = 'select * from Stations where ' 
                + @columnName + ' ' + @type + ' ' + '''' + @searchText + '''' 
            EXEC(@SQLStatement)
        END      
    END
    GO
    

    roughly equivalent to postgres:

    CREATE or replace FUNCTION public.sp_colunmName2 (
        columnName  varchar(30),
        type varchar(30), 
        searchText  varchar(30) ) RETURNS SETOF stations LANGUAGE plpgsql            
    AS
    $$
    DECLARE SQLStatement VARCHAR(4000);
    BEGIN
        SQLStatement = 'select * from Stations where ' 
                || columnName || ' ' || type || ' ' || ''''|| searchText || '''';
        RETURN QUERY EXECUTE  SQLStatement;
    END
    $$;
    

    The developer's idea was to create a versatile search procedure, but the result is that the WHERE clause can contain anything the user wants, allowing a visit from little Bobby Tables.

    Whether you use SQL statements or stored procedure doesn't matter. What matters is whether your SQL uses parameters or concatenated strings. Parameters prevent SQL injection; concatenated strings allow SQL injection.

    From Database Administrators Stack Exchange: asked by Am1rr3zA, answered by Kyralessa (CC BY-SA 4.0)

  23. Understanding "bitmap heap scan" and "bitmap index scan"

    How does PostgreSQL knows by just a bitmap anything about rows' physical order?

    The bitmap is one bit per heap page. The bitmap index scan sets the bits based on the heap page address that the index entry points to.

    So when it goes to do the bitmap heap scan, it just does a linear table scan, reading the bitmap to see whether it should bother with a particular page or seek over it.

    Or generates the bitmap so that any element of it can be mapped to the pointer to a page easily?

    No, the bitmap corresponds 1:1 to heap pages.

    I wrote some more on this here.

    OK, it looks like you might be misunderstanding what "bitmap" means in this context.

    It's not a bit string like "101011" that's created for each heap page, or each index read, or whatever.

    The whole bitmap is a single bit array, with as many bits as there are heap pages in the relation being scanned.

    One bitmap is created by the first index scan, starting off with all entries 0 (false). Whenever an index entry that matches the search condition is found, the heap address pointed to by that index entry is looked up as an offset into the bitmap, and that bit is set to 1 (true). So rather than looking up the heap page directly, the bitmap index scan looks up the corresponding bit position in the bitmap.

    The second and further bitmap index scans do the same thing with the other indexes and the search conditions on them.

    Then each bitmap is ANDed together. The resulting bitmap has one bit for each heap page, where the bits are true only if they were true in all the individual bitmap index scans, i.e. the search condition matched for every index scan. These are the only heap pages we need to bother to load and examine. Since each heap page might contain multiple rows, we then have to examine each row to see if it matches all the conditions - that's what the "recheck cond" part is about.

    One crucial thing to understand with all this is that the tuple address in an index entry points to the row's ctid, which is a combination of the heap page number and the offset within the heap page. A bitmap index scan ignores the offsets, since it'll check the whole page anyway, and sets the bit if any row on that page matches the condition.

    Graphical example

    Heap, one square = one page:
    +---------------------------------------------+
    |c____u_____X___u___X_________u___cXcc______u_|
    +---------------------------------------------+
    Rows marked c match customers pkey condition.
    Rows marked u match username condition.
    Rows marked X match both conditions.
    Bitmap scan from customers_pkey:
    +---------------------------------------------+
    |100000000001000000010000000000000111100000000| bitmap 1
    +---------------------------------------------+
    One bit per heap page, in the same order as the heap
    Bits 1 when condition matches, 0 if not
    Bitmap scan from ix_cust_username:
    +---------------------------------------------+
    |000001000001000100010000000001000010000000010| bitmap 2
    +---------------------------------------------+
    

    Once the bitmaps are created a bitwise AND is performed on them:

    +---------------------------------------------+
    |100000000001000000010000000000000111100000000| bitmap 1
    |000001000001000100010000000001000010000000010| bitmap 2
     &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
    |000000000001000000010000000000000010000000000| Combined bitmap
    +-----------+-------+--------------+----------+
                |       |              |
                v       v              v
    Used to scan the heap only for matching pages:
    +---------------------------------------------+
    |___________X_______X______________X__________|
    +---------------------------------------------+
    

    The bitmap heap scan then seeks to the start of each page and reads the page:

    Read the rest at the sourceFrom Database Administrators Stack Exchange: asked by St.Antario, answered by Craig Ringer (CC BY-SA 3.0)

  24. What is the best way to store an email address in PostgreSQL?

    Custom DOMAINs

    I don't think using citext (case-insensitive) is enough[1]. Using PostgreSQL we can create a custom domain which is essentially some defined constraints over a type. We can create a domain for instance over the citext type, or over text.

    Using HTML5 type=email spec

    Currently the most correct answer to the question what is an e-mail address is specified in RFC5322. That spec is insanely complex[2], so much so that everything breaks it. HTML5 contains a different spec for email,

    This requirement is a willful violation of RFC 5322, which defines a syntax for e-mail addresses that is simultaneously too strict (before the "@" character), too vague (after the "@" character), and too lax (allowing comments, whitespace characters, and quoted strings in manners unfamiliar to most users) to be of practical use here. [...] The following JavaScript- and Perl-compatible regular expression is an implementation of the above definition.

    /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/
    

    This is likely what you want, and if it's good enough for HTML5, it's probably good enough for you. We can make use of that directly in PostgreSQL. I also use citext here (which technically means you can simply the regex a bit visually by removing either the upper-case or lower-case).

    CREATE EXTENSION citext;
    CREATE DOMAIN email AS citext
      CHECK ( value ~ '^[a-zA-Z0-9.!#$%&''*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$' );
    

    Now you can do...

    SELECT 'asdf@foobar.com'::email;
    

    But not

    SELECT 'asdf@foob,,ar.com'::email;
    SELECT 'asd@f@foobar.com'::email;
    

    Because both of those return

    ERROR:  value for domain email violates check constraint "email_check"
    

    Because this is based on citext too

    SELECT 'asdf@foobar.com'::email = 'ASdf@fooBAR.com';
    

    returns true by default.

    Using plperlu/Email::Valid

    As an important note, there is a more correct method of doing this that is far more complex using plperlu. If you need this level of correctness you do not want citext. Email::Valid can even check if the domain has an MX record (example in docs of Email::Valid)! First, add plperlu (requires superuser).

    CREATE EXTENSION plperlu;
    

    Then create the function, notice we mark at as an IMMUTABLE:

    CREATE FUNCTION valid_email(text)
      RETURNS boolean
      LANGUAGE plperlu
      IMMUTABLE LEAKPROOF STRICT AS
    $$
      use Email::Valid;
      my $email = shift;
      Email::Valid->address($email) or die "Invalid email address: $email\n";
      return 'true';
    $$;
    

    Then create the domain,

    CREATE DOMAIN validemail AS text NOT NULL
      CONSTRAINT validemail_check CHECK (valid_email(VALUE));
    

    Footnotes

    Read the rest at the sourceFrom Database Administrators Stack Exchange: asked by Adam Matan, answered by Evan Carroll (CC BY-SA 4.0)

  25. What is a valid use case for using TIMESTAMP WITHOUT TIME ZONE?

    This is stated in a lot of places, but I think it worth mentioning always when we compare the timestamp with time zone with timestamp without time zone types: the timestamp WITH time zone does not store the time zone information along with the timestamp. What it does is to store every data in UTC time zone, as stated in the docs:

    For timestamp with time zone, the internally stored value is always in UTC (Universal Coordinated Time, traditionally known as Greenwich Mean Time, GMT). An input value that has an explicit time zone specified is converted to UTC using the appropriate offset for that time zone. If no time zone is stated in the input string, then it is assumed to be in the time zone indicated by the system's TimeZone parameter, and is converted to UTC using the offset for the timezone zone.

    It is considered valid for some to use timestamp WITHOUT time zone in situations where (1) everything is in the same timezone or (2) the application layer handles the time zone and just store everything in a certain time zone (usually UTC). But it is also considered an anti-pattern, simple because the correct solution for (1) is to configure the TimeZone setting to the given one timezone for the system and (2) is already solved, as PostgreSQL already stores everything on the same timezone (UTC).

    Now, with those two down, I can came with only one good reason to use timestamp WITHOUT time zone. That is when you want to store events in the future and that some kind of alert must be triggered when we got to that time. That could be good for timestamp WITH time zone if, and only if, the rules defined by region's laws about time zone didn't ever change. The most common rule that changes is about the adoption or not of day light saving time (DST).

    For example, imagine that you are at, let's say, 2013-06-15 (not yet in DST) schedule some event to happen at 2013-01-15 10:00 (which would be already in DST), and at 2013-06-15 your region was designated to adopt DST; but, some time after that, the government changed the rule and say your region will no longer use DST, and suddenly your scheduled time becomes 2013-01-15 11:00 (instead of 10:00), that if you use timestamp WITH time zone, and keep your TZ configurations up-to-date. Of course you may also notice that it is possible to treat such cases also with time zone, if you keep track of the rule changes in the regions/timezones of your interest, and update the affected records.

    Worth mentioning that some regions does often change these rules (like at Brazil, some states - not the entire country - often change), but in most cases it changes it very earlier, so your users would be affected only by events scheduled very far from the current time.

    With all that said, I only have one more suggestion. If you do have users, logs, or anything on different timezones, store the timezone they are coming from somewhere and choose and use timestamp with time zone. That way you can (1) cross events happening closer to each other for different sources (independent of their timezones) and (2) show the original time (the clock time) the event has happened.

    From Database Administrators Stack Exchange: asked by Marcus Junius Brutus, answered by MatheusOl (CC BY-SA 3.0)

  26. What are the drawbacks with using UUID or GUID as a primary key?

    It depends on your generation function and size of the final tables

    GUIDs are intended to be globally unique identifiers. As discussed in the Postgres 8.3 documentation there are no methodologies that are universally appropriate to generate these identifiers, but postgreSQL does ship with a few more useful candidates.

    From the scope of your problem, and the need for offline writes, you've quite neatly boxed out the use of anything but a GUID, and therefore there are no compensatory advantages of other schemes.

    From a functional standpoint, the key length is usually not an issue on any kind of modern system, depending on the number of reads and size of the table. As an alternative methodology, offline clients could batch new records without a primary key and simply insert them when reconnecting. As postgreSQL offers the "Serial" datatype, clients will never need to determine the ID if they can perform a simple write to the database.

    From Database Administrators Stack Exchange: asked by Jonas, answered by Brian Ballsun-Stanton (CC BY-SA 2.5)

  27. How to manage DEFAULT PRIVILEGES for USERs on a DATABASE vs SCHEMA?

    Postgres 14 adds the predefined roles pg_read_all_data and pg_write_all_data, which allow shortcuts for the purposes implied by the names.

    Where can I find a decent guide, tutorial or video series on this?

    You'll find everything in the manual. Links below.
    Granted, the matter is not trivial and sometimes confusing. Here is a recipe for the use case:

    Recipe

    I want to have it configured so only the hostdb_admin can create (and drop and alter) tables;
    the hostdb_mgr can read, insert, update and delete on all tables by default;
    and the hostdb_usr can only read all tables (and views).

    As superuser postgres:

    CREATE USER schma_admin WITH PASSWORD 'youwish';
    -- CREATE USER schma_admin WITH PASSWORD 'youwish' CREATEDB CREATEROLE; -- see below
    CREATE USER schma_mgr   WITH PASSWORD 'youwish2';
    CREATE USER schma_usr   WITH PASSWORD 'youwish3';
    

    If you want a more powerful admin that can also manage databases and roles, add the role attributes CREATEDB and CREATEROLE above.

    Grant each role to the next higher level, so all levels "inherit" at least the set of privileges from the next lower level (cascading):

    GRANT schma_usr TO schma_mgr;
    GRANT schma_mgr TO schma_admin;
    CREATE DATABASE hostdb;
    REVOKE ALL ON DATABASE hostdb FROM public;  -- see notes below!
    GRANT CONNECT ON DATABASE hostdb TO schma_usr;  -- others inherit
    \connect hostdb  -- psql syntax
    

    I am naming the schema schma (not hostdb which would be confusing). Pick any name. Optionally make schma_admin the owner of the schema:

    CREATE SCHEMA schma AUTHORIZATION schma_admin;
    SET search_path = schma;  -- see notes
    ALTER ROLE schma_admin IN DATABASE hostdb SET search_path = schma; -- not inherited
    ALTER ROLE schma_mgr   IN DATABASE hostdb SET search_path = schma;
    ALTER ROLE schma_usr   IN DATABASE hostdb SET search_path = schma;
    GRANT USAGE  ON SCHEMA schma TO schma_usr;
    GRANT CREATE ON SCHEMA schma TO schma_admin;
    ALTER DEFAULT PRIVILEGES FOR ROLE schma_admin
    GRANT SELECT                           ON TABLES TO schma_usr;  -- only read
    ALTER DEFAULT PRIVILEGES FOR ROLE schma_admin
    GRANT INSERT, UPDATE, DELETE, TRUNCATE ON TABLES TO schma_mgr;  -- + write, TRUNCATE optional
    ALTER DEFAULT PRIVILEGES FOR ROLE schma_admin
    GRANT USAGE, SELECT, UPDATE ON SEQUENCES TO schma_mgr;  -- SELECT, UPDATE are optional 
    

    For and drop and alter see notes below.

    Postgres 14 adds the predefined, non-login roles pg_read_all_data and pg_write_all_data to give read-only / write-only access to all objects in all schemas. That goes beyond what's being asked here, but may be useful. See:

    As things get more advanced I'll also have questions to apply similar restrictions on TRIGGERS, stored procedures, VIEWS and perhaps other objects.

    Views are special.

    The manual:

    ... (but note that ALL TABLES is considered to include views and foreign tables).

    And for Updatable Views:

    Read the rest at the sourceFrom Database Administrators Stack Exchange: asked by Jim Dennis, answered by Erwin Brandstetter (CC BY-SA 4.0)

  28. Can a single PostgreSQL query use multiple cores?

    No, for versions of PostgreSQL prior to v9.6. Please see the PostgreSQL FAQ: How does PostgreSQL use CPU resources?

    The PostgreSQL server is process-based (not threaded). Each database session connects to a single PostgreSQL operating system (OS) process. Multiple sessions are automatically spread across all available CPUs by the OS. The OS also uses CPUs to handle disk I/O and run other non-database tasks. Client applications can use threads, each of which connects to a separate database process.

    Since version 9.6, portions of some queries can be run in parallel, in separate OS processes, allowing use of multiple CPU cores. Parallel queries are enabled by default in version 10 (max_parallel_workers_per_gather), with additional parallelism expected in future releases.

    From Database Administrators Stack Exchange: asked by Alireza, answered by Jayadevan (CC BY-SA 4.0)

  29. Why is a new user allowed to create a table?

    When you create a new database, any role is allowed to create objects in the public schema. To remove this possibility, you may issue immediately after the database creation:

    REVOKE ALL ON schema public FROM public;
    

    Edit: after the above command, only a superuser may create new objects inside the public schema, which is not practical. Assuming a non-superuser foo_user should be granted this privilege, this should be done with:

    GRANT ALL ON schema public TO foo_user;
    

    To know what ALL means for a schema, we must refer to GRANT in the doc, (in PG 9.2 there are no less than 14 forms of GRANT statements that apply to different things...). It appears that for a schema it means CREATE and USAGE.

    On the other hand, GRANT ALL PRIVILEGES ON DATABASE... will grant CONNECT and CREATE and TEMP, but CREATE in this context relates to schemas, not permanent tables.

    Regarding this error: ERROR: no schema has been selected to create in, it happens when trying to create an object without schema qualification (as in create table foo(...)) while lacking the permission to create it in any schema of the search_path.

    From Database Administrators Stack Exchange: asked by andreas-h, answered by Daniel Vérité (CC BY-SA 3.0)

  30. What are the differences between "Stored Procedures" and "Stored Functions"?

    Officially, PostgreSQL only has "functions". Trigger functions are sometimes referred to as "trigger procedures", but that usage has no distinct meaning. Internally, functions are sometimes referred to as procedures, such as in the system catalog pg_proc. That's a holdover from PostQUEL. Any features that some people (possibly with experience in different database systems) might associate with procedures, such as their relevance to preventing SQL injections or the use of output parameters, also apply to functions as they exist in PostgreSQL.

    Now, when people in the PostgreSQL community talk about "stored procedures" or "real stored procedures", however, they often mean a hypothetical feature of a function-like object that can start and stop transactions in its body, something that current functions cannot do. The use of the term "stored procedure" in this context appears to be by analogy to other database products. See this mailing list thread for a vague idea.

    In practice, however, this distinction of function versus procedure in terms of their transaction-controlling capabilities is not universally accepted, and certainly many programmers without database bias will take a Pascal-like interpretation of a procedure as a function without return value. (The SQL standard appears to take a middle ground, in that a procedure by default has a different transaction behavior than a function, but this can be adjusted per object.) So in any case, and especially when looking at questions on Stack Exchange with a very mixed audience, you should avoid assuming too much and use clearer terms or define the properties that you expect.

    From Database Administrators Stack Exchange: asked by DrColossos, answered by Peter Eisentraut (CC BY-SA 3.0)

After the last page: 1 question more, without answers. Go to the last page

Related topics

Where these questions come from

Open-source collections on GitHub, official documentation, a government careers service and the Stack Exchange sites, each used under its own licence. The answers are the authors' own words: we only tidy the layout, leave out pictures, and cut a long answer with a link to the rest. Stack Exchange answers stay under CC BY-SA and name who asked and who answered.