Updated:

The basic form

/setblock ~ ~1 ~ minecraft:stone

Position first, then the block ID. This places stone one block above you. Use numbers such as 100 64 -20 or ~ for offsets from you. Bedrock also accepts stone without minecraft:.

replace, destroy and keep

ModeWhat it does
replace (default)Removes the old block and places the new one.
destroyBreaks the old block first; it drops as an item with sound and particles.
keepPlaces only if the spot is air.
/setblock ~ ~ ~2 minecraft:oak_planks keep

Facing and shape (block states)

/setblock ~ ~ ~1 minecraft:oak_stairs[facing=north]
/setblock ~ ~ ~1 minecraft:oak_slab[type=top]

On Java, states go in square brackets right after the ID. Bedrock writes them as ["name"=value] with quoted names, and some state names differ, so follow the suggestions.

A chest with items (Java)

/setblock ~ ~ ~1 minecraft:chest{Items:[{Slot:0b,id:"minecraft:diamond",count:3}]}

Block data goes in braces after the block. From 1.20.5 the amount is lowercase count; on 1.20.4 and earlier write Count:3b.

A command-block door

/setblock 10 64 20 minecraft:air
/setblock 10 64 20 minecraft:iron_block

Wire the first line to a button to open a one-block gap and the second to close it again. Do not add destroy to the open command: it drops the iron block as an item every time, which turns the door into an iron farm. For larger doors use /clone or /fill.

Common problems

Check your command

The Command Error Doctor checks common syntax mistakes in your browser.