Solved

How to convert this query to postgres

Posted on 2014-02-05
10
814 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
  • 2
  • 2
  • +3
10 Comments
 
LVL 14

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 42

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
How Do You Stack Up Against Your Peers?

With today’s modern enterprise so dependent on digital infrastructures, the impact of major incidents has increased dramatically. Grab the report now to gain insight into how your organization ranks against your peers and learn best-in-class strategies to resolve incidents.

 
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 34

Assisted Solution

by:ste5an
ste5an 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
 

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 42

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

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

CCModeler offers a way to enter basic information like entities, attributes and relationships and export them as yEd or erviz diagram. It also can import existing Access or SQL Server tables with relationships.
Read about achieving the basic levels of HRIS security in the workplace.
Steps to create a PostgreSQL RDS instance in the Amazon cloud. We will cover some of the default settings and show how to connect to the instance once it is up and running.
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…

738 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