Search code examples
sqlfinal

SQL - Make column value type final - unchangeable edit of timestamp


I would like to keep a column that shows when a user is created. That value should never be edited. Is there any mechinism in JPA and SQL for not allowing anything to change it unless the row is completely deleted. I might be over concerned about this. There is final value that I use in java so I thought there might be something similar in SQL

@Temporal(TemporalType.TIME)
@Column(name = "created_date")
private Date      creationDate = new Date();

Solution

  • There isn't exactly that mechanism in SQL, although it can be done. Normally, a create date is just assigned automatically when the row is created, and you don't worry about updating it later. Just don't update it. You can further enforce this by doing all updates in stored procedures, which is how I usually write such code.

    Of course, you can still be worried about such updates. The "built-in" solution is to use an update trigger that prevents new values from going into the field. An alternative solution would be to create a view on the table and to only allow access to the table through the view. The view can then make the column not updatable, something like:

    create view v_table as
        select col1, col2, . . ., (CreatedAt + interval 0 second) as CreatedAt
        from table t;
    

    Applying a function should make the column not-updatable. The particular syntax, of course, depends on the database.

    And, particular databases may have specific mechanisms to do this. When I saw the question, it had no database tag.

    EDIT:

    In Oracle, you can do this with GRANT and REVOKE at the column level.