Why Snowpark?
So far everything was SQL. But ShopKart's team also has Python developers (maybe you took our Python course), and some logic is easier in Python. The old way was to download data with a connector, process it on a laptop or server, and upload it back: slow, insecure, and impossible for big data. Snowpark flips it: the code goes to the data.
๐Your Python
DataFrame code on your laptop, in a notebook, or in a task
๐Snowpark library
Builds a plan; turns it into SQL
โ๏ธWarehouse
Runs the SQL; UDFs run in a Python sandbox inside Snowflake
๐Result
Stays as a table, or comes back small (show, to_pandas)
Set up and connect
$python3.11 -m venv venv && source venv/bin/activate$pip install "snowflake-snowpark-python[pandas]" # we used version 1.58
Snowpark reads the same connection file as the Snowflake CLI (~/.snowflake/config.toml). Ours connects as the key-pair service user from lesson 9. You can also write Snowpark in Snowflake Notebooks in Snowsight, where a session is ready for you.
DataFrames: Python that becomes SQL
from snowflake.snowpark import Session
from snowflake.snowpark import functions as F
# Connects with the "tt" connection from ~/.snowflake/config.toml (same one the Snowflake CLI uses)
session = Session.builder.config("connection_name", "tt").create()
print(session.sql("SELECT CURRENT_ROLE(), CURRENT_WAREHOUSE()").collect())
orders = session.table("shopkart.raw.orders")
customers = session.table("shopkart.raw.customers")
# Nothing runs yet: this only builds a plan (lazy, like Spark)
city_revenue = (
orders.filter(F.col("status") == "DELIVERED")
.join(customers, "customer_id")
.group_by("city")
.agg(
F.count("order_id").alias("orders"),
F.sum(F.col("quantity") * F.col("unit_price")).alias("revenue"),
)
.sort(F.col("revenue").desc())
)
city_revenue.show() # action: Snowpark sends ONE SQL query to Snowflake
print(city_revenue.queries["queries"][-1]) # the SQL it generated[Row(CURRENT_ROLE()='TEACHTRAILS_ROLE', CURRENT_WAREHOUSE()='SHOPKART_WH')]
-------------------------------------
|"CITY" |"ORDERS" |"REVENUE" |
-------------------------------------
|Delhi |961 |2211902.00 |
|Bengaluru |890 |2089900.00 |
|Mumbai |836 |1907862.00 |
|Kolkata |777 |1785410.00 |
|Pune |698 |1615432.00 |
-------------------------------------
SELECT * FROM (
SELECT "CITY", count("ORDER_ID") AS "ORDERS", sum(("QUANTITY" * "UNIT_PRICE")) AS "REVENUE"
FROM ( SELECT * FROM (
( SELECT * FROM shopkart.raw.orders WHERE ("STATUS" = 'DELIVERED') ) AS SNOWPARK_LEFT
INNER JOIN
( SELECT * FROM shopkart.raw.customers ) AS SNOWPARK_RIGHT
USING (customer_id) ) )
GROUP BY "CITY" )
ORDER BY "REVENUE" DESC NULLS LASTThe same revenue-by-city report as lesson 4 (with a few more orders now that December has arrived), written in Python. The printed SQL shows what really happened: Snowpark built one query and Snowflake ran it on the warehouse. Not a single order row came to our laptop, only the 5 result rows. (We tidied the SQL's spacing for the page.)
| PySpark | Snowpark | Note |
|---|---|---|
| spark.table(...) | session.table(...) | |
| df.filter / where | df.filter / where | Same |
| df.groupBy(...).agg(...) | df.group_by(...).agg(...) | snake_case (camelCase also works) |
| df.withColumn | df.with_column | |
| df.write.saveAsTable | df.write.save_as_table | |
| df.toPandas() | df.to_pandas() | Downloads the result: keep it small |
UDFs: your Python function, on every row
Some logic is easier to write in Python. A user-defined function is registered in Snowflake and called like a built-in function, from Snowpark or SQL:
from snowflake.snowpark import Session
from snowflake.snowpark import functions as F
from snowflake.snowpark.types import StringType, DecimalType
session = Session.builder.config("connection_name", "tt").create()
session.use_schema("shopkart.analytics")
# 1. A Python function that runs INSIDE Snowflake, on every row (a UDF)
@F.udf(name="price_band", replace=True, return_type=StringType(), input_types=[DecimalType(10, 2)])
def price_band(price):
if price is None:
return "unknown"
if price < 1000:
return "budget"
if price < 3000:
return "mid"
return "premium"
products = session.table("shopkart.raw.products")
products.select("name", "price", price_band("price").alias("band")).sort("price").show(12)
# 2. Use it in a bigger query, and save the result as a table
orders = session.table("shopkart.raw.orders").filter(F.col("status") == "DELIVERED")
by_band = (
orders.join(products, "product_id")
.with_column("band", price_band(F.col("price")))
.group_by("band")
.agg(F.sum(F.col("quantity") * F.col("unit_price")).alias("revenue"),
F.count("order_id").alias("orders"))
.sort(F.col("revenue").desc())
)
by_band.write.save_as_table("revenue_by_price_band", mode="overwrite")
df = session.table("revenue_by_price_band").sort(F.col("revenue").desc()).to_pandas() # small result โ pandas
print(df)
print("share of revenue from premium:", round(df.loc[df.BAND == "premium", "REVENUE"].iloc[0] / df.REVENUE.sum() * 100, 1), "%")----------------------------------------
|"NAME" |"PRICE" |"BAND" |
----------------------------------------
|Phone Case |299.00 |budget |
|Wall Clock |599.00 |budget |
|Table Lamp |799.00 |budget |
|Cotton Kurta |899.00 |budget |
|Bedsheet Set |1199.00 |mid |
|Power Bank |1299.00 |mid |
|Denim Jacket |1899.00 |mid |
|Pressure Cooker |1899.00 |mid |
|Running Shoes |2199.00 |mid |
|Wireless Earbuds |2499.00 |mid |
|Silk Saree |3499.00 |premium |
|Smartwatch |4999.00 |premium |
----------------------------------------
BAND REVENUE ORDERS
0 mid 4695645.0 2061
1 premium 3757622.0 692
2 budget 1157239.0 1409
share of revenue from premium: 39.1 %A business insight in a few lines: just 2 premium products bring 39% of delivered revenue from only 692 orders. The heavy work (join, UDF on every row, group by, save) ran in Snowflake; only the 3-row summary became a pandas DataFrame.
Stored procedures: Python jobs inside Snowflake
A stored procedure runs a whole program inside Snowflake: many queries, if/else logic, loops. Make it permanent and anyone with access can CALL it, including a task every night.
from snowflake.snowpark import Session
from snowflake.snowpark import functions as F
session = Session.builder.config("connection_name", "tt").create()
session.use_schema("shopkart.analytics")
session.sql("CREATE STAGE IF NOT EXISTS code_stage").collect()
# A stored procedure: Python that runs inside Snowflake and can run many queries.
# Permanent, so a task (lesson 7) can CALL it every night.
@F.sproc(name="refresh_city_revenue", replace=True, is_permanent=True,
stage_location="@code_stage", packages=["snowflake-snowpark-python"])
def refresh_city_revenue(session: Session, min_orders: int) -> str:
orders = session.table("shopkart.raw.orders").filter(F.col("status") == "DELIVERED")
customers = session.table("shopkart.raw.customers")
result = (orders.join(customers, "customer_id")
.group_by("city")
.agg(F.count("order_id").alias("orders"),
F.sum(F.col("quantity") * F.col("unit_price")).alias("revenue"))
.filter(F.col("orders") >= min_orders))
result.write.save_as_table("city_revenue", mode="overwrite")
return f"city_revenue refreshed: {result.count()} cities"
print(session.call("refresh_city_revenue", 800))city_revenue refreshed: 3 cities-- The procedure is a normal Snowflake object now: call it from SQL, a task or a dbt hook
CALL shopkart.analytics.refresh_city_revenue(700);
SELECT * FROM shopkart.analytics.city_revenue ORDER BY revenue DESC;| REFRESH_CITY_REVENUE |
|---|
| city_revenue refreshed: 4 cities |
| CITY | ORDERS | REVENUE |
|---|---|---|
| Delhi | 961 | 2211902.00 |
| Bengaluru | 890 | 2089900.00 |
| Mumbai | 836 | 1907862.00 |
| Kolkata | 777 | 1785410.00 |
With min_orders = 800 three cities qualified; with 700, four (Pune's 698 just misses). The procedure's code was uploaded to @code_stage and runs inside Snowflake, so a task could run CALL refresh_city_revenue(700) on a schedule with no laptop involved.
What else Snowpark can do
| Feature | What it's for |
|---|---|
| Snowflake Notebooks | Python and SQL cells in Snowsight, with a Snowpark session built in |
| Vectorized UDFs / UDTFs | Fast batch functions; table functions that return many rows per input |
| pandas on Snowflake (modin) | Write pandas code that runs on Snowflake for big data |
| Snowpark ML | Feature engineering, training and a model registry inside Snowflake |
| Snowpark Container Services | Run any container (APIs, GPU models) next to your data |
| Snowpark Connect | Run existing PySpark code on Snowflake |
๐ฏ Interview questions on this topic
Try to answer out loud first, then tap to check.
Q1What is Snowpark?Fresher+
Q2Snowpark vs PySpark?1โ3 yrs+
Q3UDF vs stored procedure?1โ3 yrs+
Q4How do you use third-party Python packages in Snowpark?1โ3 yrs+
Q5A Snowpark job is slow. What do you check?3+ yrs+
Key takeaways
- โSnowpark brings Python to the data instead of data to Python.
- โDataFrames become SQL; print df.queries to see it.
- โUDFs and procedures run inside Snowflake; procedures can be scheduled.
- โPySpark skills carry over almost one-to-one.
Frequently asked questions
What is Snowpark?
Snowflake's set of libraries for Python (also Java and Scala) that lets you work with data using DataFrames and run your own code inside Snowflake. DataFrame code is turned into SQL and runs on your warehouse, so data never leaves Snowflake.
Is Snowpark the same as PySpark?
The API looks very similar on purpose (select, filter, group_by, join, lazy evaluation), so PySpark skills transfer. But there's no Spark cluster: Snowpark translates your code to SQL that Snowflake runs. For many PySpark jobs there's also Snowpark Connect, which runs PySpark code on Snowflake.
When should I use Snowpark instead of SQL?
When Python is clearer: reusable functions, complex logic, ML feature engineering, calling Python libraries (inside UDFs), or teams that prefer Python. For simple transformations, SQL (or dynamic tables) is just as good and easier for everyone to read.
Where does my Python code actually run?
DataFrame operations run as SQL on the warehouse. UDFs and stored procedures run in a secure Python sandbox inside Snowflake, next to the data. Only to_pandas() or collect() brings data back to your laptop, so use them on small results.
Can I use any Python package?
Inside UDFs and procedures, you can use the thousands of packages in Snowflake's Anaconda channel (pandas, numpy, scikit-learn and more) by listing them in packages=[...]. You can also upload your own pure-Python code or use artifact repositories for PyPI packages.
๐ง Quick check: Snowpark Python
1. When does a Snowpark DataFrame actually run?
2. What did our group-by DataFrame turn into?
3. What is a UDF?
4. Why be careful with to_pandas()?
5. Which can be scheduled with a task and called from SQL?
Checking your accessโฆ