How Optimize sql query make it faster

Posted by user502083 on Stack Overflow See other posts from Stack Overflow or by user502083
Published on 2010-11-09T15:57:36Z Indexed on 2010/12/23 5:54 UTC
Read the original article Hit count: 234

Filed under:
|
|
|
|

Hello every one :

I have a very simple small database, 2 of tables are:

Node (Node_ID, Node_name, Node_Date) : Node_ID is primary key
Citation (Origin_Id, Target_Id) : PRIMARY KEY (Origin_Id, Target_Id) each is FK in Node

Now I write a query that first find all citations that their Origin_Id has a specific date and then I want to know what are the target dates of these records.

I'm using sqlite in python the Node table has 3000 record and Citation has 9000 records, and my query is like this in a function:

def cited_years_list(self, date):
    c=self.cur
    try:
    c.execute("""select n.Node_Date,count(*) from Node n INNER JOIN 
              (select c.Origin_Id AS Origin_Id, c.Target_Id AS Target_Id, n.Node_Date AS 
               Date from CITATION c INNER JOIN NODE n ON c.Origin_Id=n.Node_Id where
               CAST(n.Node_Date as INT)={0}) VW ON VW.Target_Id=n.Node_Id 
               GROUP BY n.Node_Date;""".format(date))
    cited_years=c.fetchall()
    self.conn.commit()
    print('Cited Years are : \n ',str(cited_years))
    except Exception as e:
       print('Cited Years retrival failed ',e)
   return cited_years

Then I call this function for some specific years, But it's crazy slowwwwwwwww :( (around 1 min for a specific year) Although my query works fine, it is slow. would you please give me a suggestion to make it faster? I'd appreciate any idea about optimizing this query :)

I also should mention that I have indices on Origin_Id and Target_Id, so the inner join should be pretty fast, but it's not!!!

© Stack Overflow or respective owner

Related posts about query

Related posts about sqlite