Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 241335
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 11, 20262026-05-11T20:44:41+00:00 2026-05-11T20:44:41+00:00

How can I write my own aggregate functions with SQLAlchemy? As an easy example

  • 0

How can I write my own aggregate functions with SQLAlchemy? As an easy example I would like to use numpy to calculate the variance. With sqlite it would look like this:

import sqlite3 as sqlite
import numpy as np

class self_written_SQLvar(object):
  def __init__(self):
    import numpy as np
    self.values = []
  def step(self, value):
    self.values.append(value)
  def finalize(self):
    return np.array(self.values).var()

cxn = sqlite.connect(':memory:')
cur = cxn.cursor()
cxn.create_aggregate("self_written_SQLvar", 1, self_written_SQLvar)
# Now - how to use it:
cur.execute("CREATE TABLE 'mytable' ('numbers' INTEGER)")
cur.execute("INSERT INTO 'mytable' VALUES (1)") 
cur.execute("INSERT INTO 'mytable' VALUES (2)") 
cur.execute("INSERT INTO 'mytable' VALUES (3)") 
cur.execute("INSERT INTO 'mytable' VALUES (4)")
a = cur.execute("SELECT avg(numbers), self_written_SQLvar(numbers) FROM mytable")
print a.fetchall()
>>> [(2.5, 1.25)]
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-11T20:44:41+00:00Added an answer on May 11, 2026 at 8:44 pm

    The creation of new aggregate functions is backend-dependant, and must be done
    directly with the API of the underlining connection. SQLAlchemy offers no
    facility for creating those.

    However after created you can just use them in SQLAlchemy normally.

    Example:

    import sqlalchemy
    from sqlalchemy import Column, Table, create_engine, MetaData, Integer
    from sqlalchemy import func, select
    from sqlalchemy.pool import StaticPool
    from random import randrange
    import numpy
    import sqlite3
    
    class NumpyVarAggregate(object):
      def __init__(self):
        self.values = []
      def step(self, value):
        self.values.append(value)
      def finalize(self):
        return numpy.array(self.values).var()
    
    def sqlite_memory_engine_creator():
        con = sqlite3.connect(':memory:')
        con.create_aggregate("np_var", 1, NumpyVarAggregate)
        return con
    
    e = create_engine('sqlite://', echo=True, poolclass=StaticPool,
                      creator=sqlite_memory_engine_creator)
    m = MetaData(bind=e)
    t = Table('mytable', m, 
                Column('id', Integer, primary_key=True),
                Column('number', Integer)
              )
    m.create_all()
    

    Now for the testing:

    # insert 30 random-valued rows
    t.insert().execute([{'number': randrange(100)} for x in xrange(30)])
    
    for row in select([func.avg(t.c.number), func.np_var(t.c.number)]).execute():
        print 'RESULT ROW: ', row
    

    That prints (with SQLAlchemy statement echo turned on):

    2009-06-15 14:55:34,171 INFO sqlalchemy.engine.base.Engine.0x...d20c PRAGMA 
    table_info("mytable")
    2009-06-15 14:55:34,174 INFO sqlalchemy.engine.base.Engine.0x...d20c ()
    2009-06-15 14:55:34,175 INFO sqlalchemy.engine.base.Engine.0x...d20c 
    CREATE TABLE mytable (
        id INTEGER NOT NULL, 
        number INTEGER, 
        PRIMARY KEY (id)
    )
    2009-06-15 14:55:34,175 INFO sqlalchemy.engine.base.Engine.0x...d20c ()
    2009-06-15 14:55:34,176 INFO sqlalchemy.engine.base.Engine.0x...d20c COMMIT
    2009-06-15 14:55:34,177 INFO sqlalchemy.engine.base.Engine.0x...d20c INSERT
    INTO mytable (number) VALUES (?)
    2009-06-15 14:55:34,177 INFO sqlalchemy.engine.base.Engine.0x...d20c [[98], 
    [94], [7], [1], [79], [77], [51], [28], [85], [26], [34], [68], [15], [43], 
    [52], [97], [64], [82], [11], [71], [27], [75], [60], [85], [42], [40], 
    [76], [12], [81], [69]]
    2009-06-15 14:55:34,178 INFO sqlalchemy.engine.base.Engine.0x...d20c COMMIT
    2009-06-15 14:55:34,180 INFO sqlalchemy.engine.base.Engine.0x...d20c SELECT
    avg(mytable.number) AS avg_1, np_var(mytable.number) AS np_var_1 FROM mytable
    2009-06-15 14:55:34,180 INFO sqlalchemy.engine.base.Engine.0x...d20c []
    RESULT ROW: (55.0, 831.0)
    

    Note that I didn’t use SQLAlchemy’s ORM (just the sql expression part of SQLAlchemy was used) but you could use ORM just as well.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 117k
  • Answers 118k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer class Program { static void Main(string[] args) { Timer timer… May 11, 2026 at 10:50 pm
  • Editorial Team
    Editorial Team added an answer Use GROUP_CONCAT SELECT GROUP_CONCAT(bar) FROM TABLE GROUP BY foo; May 11, 2026 at 10:50 pm
  • Editorial Team
    Editorial Team added an answer Your code doesn't work because the function is not returning… May 11, 2026 at 10:50 pm

Related Questions

Lets say I have this amputated Person class: class Person { public int Age
How can I copy a line 10 times easily in Emacs? I can't find
Using a .NET DbCommand (eg OracleCommand, SqlCommand, ODBCCommand, etc) object with Parameters, how can
I have a class which constructor takes a Jakarta enums . I'm trying to

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.