Under the global shortage of freshwater resources, capacitive deionization (CDI) has attracted widespread attention as an efficient and energy-saving water purification technology. Herein, N-doped hierarchically porous carbons (NPCs) with micro-meso-macropore, excellent specific capacitance (194.75 F g−1), large specific surface area (1903.0 m2 g−1), high mesoporous content, and fast ion transport capability were prepared by the pyrolysis of polyacrylonitrile using nano-silica and ZnCl2 as pore-making agents. As CDI electrode materials for desalination and heavy metal adsorption, the optimized NPC-0.75 electrode delivered a maximum electrosorption capacity of 19.61 mg g−1 at the optimum operating parameters (1.2 V, 10 mL min−1, 500 mg L-1 NaCl) and an excellent regeneration performance after continuous electrosorption-desorption cycles. The structure–activity relationship analysis indicated that the mesopore dominates the CDI performance of NPCs in water. In addition, NPC-0.75 electrode showed a high removal capacity for Cu2+ (36.3 mg g−1), Cd2+ (30.02 mg g−1) and Pb2+ (21.5 mg g−1) in water. This study provides new insight into the design of high-efficiency porous carbons toward the CDI from water.