4

I have a SQL table set that looks like this

create table foo ( 
    id int primary key asc, 
    data datatype );

create table bar ( 
    id int primary key asc, 
    fk_foo int,
    foreign key(foo_int) references foo(id));

Now, I want to insert a record set.

insert into table foo (data) values (stuff);

But wait - to get Bar all patched up hunkydory I need the PK from Foo. I know this is a solved problem.

What's the solution?

1 Answer 1

9

try this

SELECT last_insert_rowid() 
Sign up to request clarification or add additional context in comments.

1 Comment

I know this is an older question/answer, but note that this does NOT work correctly with the create statements define above. last_insert_rowid returns the last rowid of the specified table. But in create table statements above, the id column is defined as 'int primary key'. In this case, id is NOT an alias for rowid. That's only the case if id is declared as 'integer primary key'. This is one (the only?) case where sqlite requires a very specific column declaration. 'int' isn't good enough, it MUST be 'integer'. Otherwise, id and rowid are NOT the same colulmn.

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.