Getting SQL syntax error in INSERT query in wordpress database

i am using below insert query adding custom filed for all wordpress post, but getting Sql Syntax error i dont know where i m doing wrong

INSERT INTO wp_postmeta (post_id, meta_key, meta_value)
SELECT ID AS post_id, 'CustomField'
AS meta_key 'MyValue AS meta_value
FROM wp_posts WHERE ID NOT IN
(SELECT post_id FROM wp_postmeta WHERE meta_key = 'CustomField')
'' AND post_type = 'post'; 

Related posts

Leave a Reply

1 comment

  1. you missed comma for separation of columns and single quote to wrap string.

    INSERT INTO wp_postmeta (post_id, meta_key, meta_value)
    SELECT ID AS post_id, 
           'CustomField' AS meta_key, 
           'MyValue' AS meta_value
    FROM   wp_posts 
    WHERE  ID NOT IN
           (SELECT post_id 
            FROM wp_postmeta 
            WHERE meta_key = 'CustomField')
           AND post_type = 'post'; 
    

    An alternative of using NOT IN is by joining two tables,

    INSERT  INTO wp_postmeta (post_id, meta_key, meta_value)
    SELECT  a.ID AS post_id, 
            'CustomField' AS meta_key, 
            'MyValue' AS meta_value
    FROM    wp_posts a
            LEFT JOIN wp_postmeta b
                ON  a.ID = b.post_id AND 
                    b.meta_key = 'CustomField'
    WHERE   a.post_type = 'post' AND
            b.post_id IS NULL