How to convert this query to postgres

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

Ashraf HassaneinAsked:
Who is Participating?
 
pcelbaConnect With a Mentor Commented:
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
 
Phil PhillipsConnect With a Mentor Director of DevOps & Quality AssuranceCommented:
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
 
earth man2Commented:
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
Get 10% Off Your First Squarespace Website

Ready to showcase your work, publish content or promote your business online? With Squarespace’s award-winning templates and 24/7 customer service, getting started is simple. Head to Squarespace.com and use offer code ‘EXPERTS’ to get 10% off your first purchase.

 
SurranoSystem EngineerCommented:
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
 
ste5anConnect With a Mentor Senior DeveloperCommented:
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
 
Ashraf HassaneinAuthor Commented:
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
 
pcelbaCommented:
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
 
earth man2Connect With a Mentor Commented:
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
 
SurranoConnect With a Mentor System EngineerCommented:
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
 
Ashraf HassaneinAuthor Commented:
Thanks I managed to execute the query successfully finally
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.