1

If I want to create a table with column create_by automatically filled with the user who create the entry, what is the DDL look like? Wonder whether Postgres can do this similar to create_at

e.g. create_at TIMESTAMP NOT NULL DEFAULT NOW() 

kind of thing.

3
  • There is current_user you can use Commented Nov 3, 2017 at 20:06
  • 3
    create_by text NOT NULL DEFAULT current_user Commented Nov 3, 2017 at 20:07
  • create_at timestamp default current_timestamp Commented Nov 3, 2017 at 23:31

1 Answer 1

6

SQL Fiddle

PostgreSQL 9.6 Schema Setup:

CREATE TABLE foo
    (
        id serial primary key
      , "bar" varchar(1)
      , created_by text NOT NULL DEFAULT current_user
      , created_at timestamp DEFAULT current_timestamp
    )
;

INSERT INTO foo
    ("bar")
VALUES
    ('a'),
    ('b'),
    ('c')
;

Query 1:

select *
from foo

Results:

| id | bar |    created_by |                  created_at |
|----|-----|---------------|-----------------------------|
|  1 |   a | user_17_3a66a | 2017-11-04T05:05:18.161681Z |
|  2 |   b | user_17_3a66a | 2017-11-04T05:05:18.161681Z |
|  3 |   c | user_17_3a66a | 2017-11-04T05:05:18.161681Z |
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.