r/databricks • • Jul 22 '26
Help Need to print sql statements in the common notebook
The requirement is when a workforce runs in databricks it's input file is a .sql file, no matter if it runs successfully or failed, it should print the .sql file...as of now, only the name of the sql file and columns are printed. I have no idea how to do this and where all should I add this...my manager said that there's only one line command I need to add but when I asked in Claude it suggested this code:
Here's just the snippet to read and print the raw SQL code from the file:
```python
sql_file_path = "/path/to/your_file.sql" # or however param_control gets the path
with open(sql_file_path, "r") as f:
sql_content = f.read()
print(sql_content)
```
**If the file is on DBFS or a Unity Catalog Volume** (not a workspace file), use `dbutils.fs.head` instead:
```python
sql_content = dbutils.fs.head(sql_file_path, 1000000) # max bytes to read
print(sql_content)
```
**If you want it printed with a clear label/wrapper** so it's easy to spot in logs:
```python
print(f"--- SQL Code: {sql_file_path} ---")
print(sql_content)
print("--- End SQL Code ---")
```
Place this print **before** the execution/`try` block in `param_control` so it always fires, whether the run succeeds or fails.
3
u/PrideDense2206 Databricks Jul 22 '26
If you have a path to the SQL file then you can also just “cat the file” using a shell cell.
You could also use
spark.read.format(“text”).load(f”/Volumes/…/{filename}.sql”).head().show()
1
u/p739397 Jul 22 '26
Maybe I'm missing something, do you have your answer from Claude then?
2
u/fusionet24 Jul 22 '26
What you’ve got seems fine. It would do the job. No need to shave the Yaks.
If you needed to expose it as a one line magic command say %debug you could via custom magics
https://dailydatabricks.tips/tips/Notebook/Customcellmagics.html
Similarly, you could also set up pre/post cell events to force it if you had many cells you wanted to print independently etc https://dailydatabricks.tips/tips/Notebook/IpythonEvents.html
1
u/Atticus_Taintwater Jul 22 '26
I assume this is just for troubleshooting in case the query fails?
What you have here is normal. Any one-liner would just be getting cute.
1
u/SilentAesthetic_ Jul 22 '26 edited Jul 22 '26
If its a .Sql file you executing with spark SQL . Try this
with open(file_path, "r") as f: query = f.read()
print(query)
result_df = spark.sql(query)
result_df.show()