# Postgresql RETURNING statement -\> returning and ID after writing to a DB

**URL:** <https://www.ruby-forum.com/t/postgresql-returning-statement-returning-and-id-after-writing-to-a-db/195174>\
**Category:** Rails\
**Created:** [September 18, 2010, 11:32am UTC](https://www.ruby-forum.com/t/postgresql-returning-statement-returning-and-id-after-writing-to-a-db/195174 "2010-09-18T11:32:55Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![HeisenbergsUncertai](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/h/9de0a6/32.png) [@HeisenbergsUncertai](https://www.ruby-forum.com/u/HeisenbergsUncertai)\
**Post date:** [September 18, 2010, 11:32am UTC](https://www.ruby-forum.com/t/postgresql-returning-statement-returning-and-id-after-writing-to-a-db/195174/1 "2010-09-18T11:32:55Z")

</div>

Currently, I have an Articles page which creates articles in a DB.

What I would like to do is to return the ID of the submitted article.

I know how to do it with raw sql,

"INSERT INTO test (name) VALUES (‘My Name 1’) RETURNING id; "

but I was wondering if there is a way to do it, “The Rails Way”.

Still very new to RoR.

---

<div class="post-metadata">

**Author:** ![HeisenbergsUncertai](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/h/9de0a6/32.png) [@HeisenbergsUncertai](https://www.ruby-forum.com/u/HeisenbergsUncertai)\
**Post date:** [September 18, 2010, 1:18pm UTC](https://www.ruby-forum.com/t/postgresql-returning-statement-returning-and-id-after-writing-to-a-db/195174/2 "2010-09-18T13:18:17Z")

</div>

On Saturday 18 September 2010, HeisenbergsUncertaintyThizz wrote:

> Currently, I have an Articles page which creates articles in a DB.
> 
> What I would like to do is to return the ID of the submitted article.
> 
> I know how to do it with raw sql,
> 
> "INSERT INTO test (name) VALUES (‘My Name 1’) RETURNING id; "
> 
> but I was wondering if there is a way to do it, “The Rails Way”.

You just do

@article = Article.create!(…)

and @article will have the correct ID. Internally, the postgresql  
adapter uses RETURNING if it is supported by the PostgreSQL version (\>=  
8.0.2 or something).

If you’re interested in the details, read the code in /activerecord-3.0.0/lib/active\_record/connection\_adapters/postgresql\_adapter.rb

Michael

–  
Michael S.  
[mailto:removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)  
[http://www.schuerig.de/michael/](http://www.schuerig.de/michael/)

---

<div class="post-metadata">

**Author:** ![HeisenbergsUncertai](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/h/9de0a6/32.png) [@HeisenbergsUncertai](https://www.ruby-forum.com/u/HeisenbergsUncertai)\
**Post date:** [September 18, 2010, 1:20pm UTC](https://www.ruby-forum.com/t/postgresql-returning-statement-returning-and-id-after-writing-to-a-db/195174/3 "2010-09-18T13:20:37Z")

</div>

Thank you very much.
