How can I insert a row using other rows data? #985
-
First Check
Commit to Help
Example Codefrom typing import Optional
from sqlmodel import Field, SQLModel, create_engine
class Test(SQLModel, table=True):
total:int = Field(default=0)
count:int = Field(default=0) DescriptionHow can I get this SQL using SQLModel? INSERT INTO test (total, count)
VALUES ((SELECT total FROM test ORDER BY id DESC LIMIT 1) + 3, 3); Operating SystemLinux Operating System DetailsNo response SQLModel Version0.0.19 Python Version3.12.3 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Answered by
YuriiMotov
Aug 20, 2025
Replies: 1 comment
-
Use Runnable code example: from sqlmodel import SQLModel, Field, create_engine, Session, select
from sqlalchemy import insert
# Define two tables with the same schema
class Source(SQLModel, table=True):
id: int | None = Field(default=None, primary_key=True)
name: str
class Target(SQLModel, table=True):
id: int | None = Field(default=None, primary_key=True)
name: str
# Create an in-memory SQLite database
engine = create_engine("sqlite:///:memory:")
SQLModel.metadata.create_all(engine)
# Insert some sample rows into Source
with Session(engine) as session:
session.add_all([Source(name="Alice"), Source(name="Bob")])
session.commit()
# Copy rows from Source → Target in one SQL query
stmt = insert(Target).from_select(
[Target.name], # target columns
select(Source.name) # source columns
)
with Session(engine) as session:
session.exec(stmt)
session.commit()
# Check copied rows
with Session(engine) as session:
results = session.exec(select(Target)).all()
print(results) # [Target(id=1, name='Alice'), Target(id=2, name='Bob')] |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
YuriiMotov
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Use
insert(Target).from_select(...)
Runnable code example: