# Insert a record into Mnesia only if its key doesn't exist yet

**URL:** <https://erlangforums.com/t/insert-a-record-into-mnesia-only-if-its-key-doesnt-exist-yet/2811>\
**Category:** Questions / Help\
**Tags:** mnesia\
**Created:** [August 21, 2023, 3:40pm UTC](https://erlangforums.com/t/insert-a-record-into-mnesia-only-if-its-key-doesnt-exist-yet/2811 "2023-08-21T15:40:29Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![peerst](https://erlangforums.com/user_avatar/erlangforums.com/peerst/32/557_2.png) [@peerst](https://erlangforums.com/u/peerst)\
**Post date:** [August 21, 2023, 3:40pm UTC](https://erlangforums.com/t/insert-a-record-into-mnesia-only-if-its-key-doesnt-exist-yet/2811/1 "2023-08-21T15:40:29Z")

</div>

I want to insert a record into a Mnesia table only when it doesn’t exist yet avoiding race conditions: if two processes try to add the same key only one should succeed.

There is the `mnesia:wread/1` function which is just a shortcut for `mnesia:read/2` with a `write` lock set on the record. The documentation says locks are on a record, but what if there is no record? Is the lock actually on the key? Would the below code work and achieve what I described above?

```erlang
insert_if_not_exists(Record=#my_record{key=Key}) ->
       Fun = fun() ->
                 case mnesia:wread({my_record, Key}) of
                     [] -> % Key doesn't exist yet
                         mnesia:write(Record);
                     [_Existing] -> % Key exists
                         already_exists
                 end
             end,
       mnesia:transaction(Fun).

```

---

<div class="post-metadata">

**Author:** ![starbelly](https://erlangforums.com/user_avatar/erlangforums.com/starbelly/32/209_2.png) [@starbelly](https://erlangforums.com/u/starbelly)\
**Post date:** [August 21, 2023, 4:35pm UTC](https://erlangforums.com/t/insert-a-record-into-mnesia-only-if-its-key-doesnt-exist-yet/2811/2 "2023-08-21T16:35:24Z")

</div>

It looks like the lock is on the [tab and key](https://github.com/erlang/otp/blob/5bd165d16a62d6fa30118f846d52c016141b606e/lib/mnesia/src/mnesia_locker.erl#L655)

---

<div class="post-metadata">

**Author:** ![LeonardB](https://erlangforums.com/user_avatar/erlangforums.com/leonardb/32/1856_2.png) [@LeonardB](https://erlangforums.com/u/LeonardB)\
**Post date:** [August 21, 2023, 4:49pm UTC](https://erlangforums.com/t/insert-a-record-into-mnesia-only-if-its-key-doesnt-exist-yet/2811/3 "2023-08-21T16:49:59Z")

</div>

Scanning mnesia code seems to indicate there is no check for the key existing before the lock is added, so it appears it should be safe.
