I’ve created a scratch org, but it’s empty without a price book. I’d like to create it with script/code/CLI so it can be automated. Unless the price book is in place I can’t really add products w price.

1 Answer 1



In Apex, you can create a Price Book (Pricebook2) and a Product (Product2) and relate the two records with a Price Book Entry (PricebookEntry) using the following method:

// Create a Pricebook

Pricebook2 priceBook = new Pricebook2(
    Name = 'Example Price Book',
    Description = 'This is the Price Book description.',
    IsActive = true

insert priceBook;

// Create a Product

Product2 product = new Product2(
    Name = 'Example Product',
    Description = 'This is the Product description.',
    ProductCode = 'EX1234',
    StockKeepingUnit = 'EX5678',
    Family = 'Example Product Family',
    QuantityUnitOfMeasure = 'inches',
    DisplayUrl = 'https://www.example.com/',
    ExternalId = 'ID #1234',
    ExternalDataSourceId = '0XCXXXXXXXXXXXXXXX',
    IsActive = true

insert product;

// Get the Standard Price Book ID

Pricebook2 standardPriceBook = [
      FROM Pricebook2
     WHERE isStandard = true
     LIMIT 1

// Insert the Product in the Standard Price Book (if necessary)

PricebookEntry standardPriceBookEntry = new PricebookEntry(
    Pricebook2Id = standardPriceBook.Id,
    Product2Id = product.Id,
    UnitPrice = 100.00,
    UseStandardPrice = false,
    IsActive = true

insert standardPriceBookEntry;

// Insert the Product in the New Price Book

PricebookEntry priceBookEntry = new PricebookEntry(
    Pricebook2Id = priceBook.Id,
    Product2Id = product.Id,
    UnitPrice = 100.00,
    UseStandardPrice = false,
    IsActive = true

insert priceBookEntry;


If you store the above Apex code in a file (i.e. example.apex), in SFDX, you can run the apex:execute command to execute the code anonymously to create the Price Book in the org:

sfdx force:apex:execute --apexcodefile ~/example.apex

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.