Raw SQL queries
Usedb.Raw to write a full SQL statement and scan the results into any struct or slice.
Executing raw SQL
Usedb.Exec for statements that do not return rows — INSERT, UPDATE, DELETE, DDL, etc.
RowsAffected on the returned *gorm.DB to see how many rows were changed:
Named arguments
Usesql.Named or a map[string]interface{} to pass named placeholders. Any SQL containing @ is treated as a named expression.
Generating SQL without executing
db.ToSQL runs the provided function in DryRun mode and returns the final SQL string without sending anything to the database.
stmt.SQL and stmt.Vars directly:
SQL expressions in updates
Usegorm.Expr to embed raw SQL expressions inside update operations.
Clause expressions
Useclause.Expr when you need a raw SQL fragment anywhere a clause.Expression is accepted.
Locking
Addclause.Locking to any select query to control row-level locking.
Upsert with OnConflict
clause.OnConflict controls what happens when a unique constraint violation occurs.
Optimizer hints
Use thehints package (available in gorm.io/hints) to add database optimizer hints without writing raw SQL.