tags:

views:

401

answers:

4

Right now, I have

SELECT gp_id FROM gp.keywords 
WHERE keyword_id = 15 
AND (SELECT practice_link FROM gp.practices 
     WHERE practice_link IS NOT NULL 
     AND id = gp_id)

This does not provide a syntax error, however for values where it should return row(s), it just returns 0 rows.

What I'm trying to do is get the gp_id from gp.keywords where the the keywords table keyword_id column is a specific value and the practice_link is the practices table corresponds to the gp_id that I have, which is stored in the id column of that table.

+1  A: 
SquareCog
5 seconds faster than me :) I'd like to know if there is any advantage on doing p.id = k.gp_id at the end vs. doing it as the first where clause.
Guido
Will usually make no difference, as the optimizer will handle it, but check your execution plans.
Cade Roux
We even abbreviated the table names the same!There should be no difference on modern DBMSes, which use cost-based, not order-based, optimizers. There may be a difference if you use a join clause instead, but that's also mostly syntactic, not functional.
SquareCog
@Guido - ordering of the where clause can definitely make a difference in performance. Since there is a join, the join condition should be moved into the FROM clause to allow the optimizer to choose the best plan, and make it easier to read.
StingyJack
@StingyJack - I do often move things into the JOIN clause on INNER JOINs however, in my experience, the optimizer is always smart anough to effectively do that already in the execution plan.
Cade Roux
A: 
SELECT k.gp_id
FROM gp.keywords k, gp.practices p
WHERE 
   p.id = k.gp_id.AND
   k.keyword_id = 15 AND
   p.practice_link is not null
Guido
A: 
SELECT g.gp_id, p.practice_link FROM gp.keywords g, gp.practices p 
WHERE
g.keyword_id = 15 AND p.practice_link IS NOT NULL AND p.id = g.gp_id
Elie
+3  A: 

I'm not even sure that is valid SQL, so I'm surprised it is working at all:

SELECT gp_id
FROM gp.keywords
WHERE keyword_id = 15
    AND (SELECT practice_link FROM gp.practices WHERE practice_link IS NOT NULL AND id = gp_id)

How about this instead:

SELECT kw.gp_id, p.practice_link
FROM gp.keywords AS kw
INNER JOIN gp.practices AS p
    ON p.id = kw.gp_id
WHERE kw.keyword_id = 15

I would steer clear of implicit joins as in the other examples. It only leads to tears later.

Cade Roux