Solved

How to convert this query to postgres

Posted on 2014-02-05
10
755 Views
Last Modified: 2014-02-20
I have the following mysql command, how can I change to postgres:
DELETE pm FROM  wp_postmeta  pm LEFT JOIN  wp_posts  wp ON wp."ID" = pm.post_id WHERE wp."ID" IS NULL;

Open in new window

0
Comment
Question by:Ashraf Hassanein
  • 2
  • 2
  • 2
  • +3
10 Comments
 
LVL 12

Assisted Solution

by:Phil Phillips
Phil Phillips earned 100 total points
ID: 39837408
The join doesn't seem to make too much sense since "ID" looks like a primary key, and those shouldn't have null records.  Do you just want to get rid of null references?  In that case, it might just make sense to do:

delete from wp_postmeta where post_id is null;

Open in new window

0
 
LVL 22

Expert Comment

by:earth man2
ID: 39837477
Phil seems correct about the true intent.  
PostgreSQL has a non ANSI standard extension USING clause for DELETE so the equivalent syntax would be ...

DELETE FROM wp_postmeta AS pm USING wp_posts AS wp
  WHERE pm.post_id = wp."ID"  AND wp."ID"  is null;

This is the same as
delete from wp_postmeta where post_id is null;
except there would have to be entries  in wp_posts table where wp_posts.id = NULL

It is always better to catch this on input using table column NOT NULL criteria.
0
 
LVL 41

Accepted Solution

by:
pcelba earned 100 total points
ID: 39837499
The original query says following:

DELETE FROM  wp_postmeta WHERE post_id IS NULL OR post_id NOT IN (SELECT ID FROM wp_posts)

I would recommend to execute the SELECT query first:
SELECT * FROM  wp_postmeta WHERE post_id IS NULL OR post_id NOT IN (SELECT ID FROM wp_posts)
0
 
LVL 8

Expert Comment

by:Surrano
ID: 39838268
The original query is actually a left join that tells you to delete all records from left which have no counterparts in right.

Not sure about mysql approach but it's important that the predicate "null = null" in postgresql is not true. It's NULL and as such, left join on a NULL field is simply not possible. Therefore I'd say what you're looking for is:

DELETE FROM wp_postmeta WHERE NOT EXISTS 
(SELECT 1 FROM wp_posts wp WHERE wp.id = wp_postmeta.id);

Open in new window

Note that
- "NOT EXISTS" is usually faster than "NOT IN"
- you can't use alias (e.g. pm) for the table name to delete from but you can use alias in the subquery.
0
 
LVL 32

Assisted Solution

by:Stefan Hoffmann
Stefan Hoffmann earned 100 total points
ID: 39838278
Your JOIN is a OUTER non-equi / non-semi JOIN. Cause the IS NULL test is on the outer table. I would say the logical solution is:

DELETE FROM wp_postmeta pm
WHERE NOT EXISTS (
  SELECT p.*
  FROM wp_posts p
  WHERE pm.post_id = p.id
);

Open in new window

or

DELETE FROM wp_postmeta pm
WHERE NOT pm.post_id IN (
  SELECT p.ID
  FROM wp_posts p
);

Open in new window

0
6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

 

Author Comment

by:Ashraf Hassanein
ID: 39843863
Thank you for your support, I think that it would be better to make a select first to see the content, but when I am trying to do :
SELECT COUNT(*) FROM  wp_postmeta WHERE post_id IS NULL OR post_id NOT IN (SELECT ID FROM wp_posts);

Open in new window


I got error:
ERROR:  column "id" does not exist
LINE 1: ...a WHERE post_id IS NULL OR post_id NOT IN (SELECT ID FROM ha...

Open in new window


Although the ID is column in such table:

 \d+ wp_posts;
                                                          Table "public.wp_posts"
        Column         |            Type             |                          Modifiers                          | Storage  | Description
-----------------------+-----------------------------+-------------------------------------------------------------+----------+-------------
 ID                    | bigint                      | not null default nextval(('has_posts_seq'::text)::regclass) | plain    |
 post_author           | bigint                      | not null default 0::bigint                                  | plain    |
 post_date             | timestamp without time zone | not null default now()                                      | plain    |
 post_date_gmt         | timestamp without time zone | not null default timezone('gmt'::text, now())               | plain    |
 post_content          | text                        | not null                                                    | extended |
 post_title            | text                        | not null                                                    | extended |
 post_excerpt          | text                        | not null                                                    | extended |
 post_status           | character varying(20)       | not null default 'publish'::character varying               | extended |
 comment_status        | character varying(20)       | not null default 'open'::character varying                  | extended |
 ping_status           | character varying(20)       | not null default 'open'::character varying                  | extended |
 post_password         | character varying(20)       | not null default ''::character varying                      | extended |
 post_name             | character varying(200)      | not null default ''::character varying                      | extended |
 to_ping               | text                        | not null                                                    | extended |
 pinged                | text                        | not null                                                    | extended |
 post_modified         | timestamp without time zone | not null default now()                                      | plain    |
 post_modified_gmt     | timestamp without time zone | not null default timezone('gmt'::text, now())               | plain    |
 post_content_filtered | text                        | not null                                                    | extended |
 post_parent           | bigint                      | not null default 0::bigint                                  | plain    |
 guid                  | character varying(255)      | not null default ''::character varying                      | extended |
 menu_order            | integer                     | not null default 0                                          | plain    |
 post_type             | character varying(20)       | not null default 'post'::character varying                  | extended |
 post_mime_type        | character varying(100)      | not null default ''::character varying                      | extended |
 comment_count         | bigint                      | not null default 0::bigint                                  | plain    |
Indexes:
    "wp_posts_pkey" PRIMARY KEY, btree ("ID")
    "wp_posts_post_author" btree (post_author)
    "wp_posts_post_name" btree (post_name)
    "wp_posts_post_parent" btree (post_parent)
    "wp_posts_type_status_date" btree (post_type, post_status, post_date, "ID")
Has OIDs: no

Open in new window

0
 
LVL 41

Expert Comment

by:pcelba
ID: 39844009
The ID is reserved word so you'll probably need to use quoted form:

SELECT COUNT(*) FROM  wp_postmeta WHERE post_id IS NULL OR post_id NOT IN (SELECT "ID" FROM wp_posts);

More info: http://www.postgresql.org/docs/8.2/static/sql-syntax-lexical.html
0
 
LVL 22

Assisted Solution

by:earth man2
earth man2 earned 100 total points
ID: 39844047
In this case ID column name has been uppercased explicitly during its' naming, so it needs to be double quoted.  Is ID a reserved word in MySQL ? I use it all the time.

I seem to have forgotten what a LEFT join is, best to include LEFT OUTER in the query to remind people like me what it means.

the not exists option tends to be quicker.

SELECT COUNT(*) FROM  wp_postmeta pm WHERE post_id IS NULL OR NOT EXISTS (SELECT 1 FROM wp_posts  wp where wp."ID" = pm.post_id);

postgres=# delete FROM  wp_postmeta pm WHERE post_id IS NULL OR NOT EXISTS (SELECT 1 FROM wp_posts  wp where wp."ID" = pm.post_id);
DELETE 1
0
 
LVL 8

Assisted Solution

by:Surrano
Surrano earned 100 total points
ID: 39846712
In PostgreSQL, identifiers are case insensitive unless (double-)quoted so if you quote them you must quote everywhere, including table definition.

Also in PostgreSQL, the JOIN keyword implicitly means OUTER JOIN but you may write OUTER JOIN to be unambiguous.
0
 

Author Comment

by:Ashraf Hassanein
ID: 39872635
Thanks I managed to execute the query successfully finally
0

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

Many developers have database experience, but are new to PostgreSQL. It has some truly inspiring capabilities. I have several years' experience with Microsoft's SQL Server. When I began working with MySQL, I wanted a quick-reference to MySQL (htt…
Does the idea of dealing with bits scare or confuse you? Does it seem like a waste of time in an age where we all have terabytes of storage? If so, you're missing out on one of the core tools in every professional programmer's toolbox. Learn how to …
Video by: Steve
Using examples as well as descriptions, step through each of the common simple join types, explaining differences in syntax, differences in expected outputs and showing how the queries run along with the actual outputs based upon a simple set of dem…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now