I understand that writing data to a smart contract is a transaction and it will cost gas. Will reading data from blockchain cost gas?

For example, I have a struct to collect data about a person - name, age, gender. Now I seeded 1000 persons during contract initialization. Can I query to get all the Persons information? Can I write a function to iterate through the mapping Persons and return all the records? Please let me know if there's any efficient way to do this and if this will cost gas.

struct Person {
    uint age;
    string name;
    string gender;
mapping(uint => Person) Persons;

1 Answer 1


As long as you are only reading data from the blockchain and not changing the blockchain, you don't need to carry out a transaction. The function you call is then carried out only by the node you are connected to and not mined, such that you don't need to pay any gas. You can find more details in this answer.

So yes, you can query the mapping. If you can iterate through the mapping depends. If you use as key a counter that is updated with every Person you put on the mapping, then you can. If the key is a number that identifies the Person, iterating will not be possible.

Note that if the uint in your mapping is just a counter, you could also use an array of Person. You can find more information on different storage patterns in this answer

If you define the mapping as Public, you can use the builtin getter function to access it.

  • "you can query the mapping and iterate through it" I believe there's no way to iterate through the keys of a mapping. (You need to know the keys some other way.)
    – user19510
    Nov 25, 2017 at 6:35
  • You are right, i have to be more specific. I was assuming that the key is a counter that is increased with every Person that is put in the mapping. It will work then, if you know the number of Persons you put into the mapping. If the key is a number that identifies the person somehow, then it will not work. I'll updatexthe question.
    – gisdev_p
    Nov 25, 2017 at 8:35
  • It makes sense it is free, most of the time you get the existing data from your local node directly
    – Davide C
    Nov 25, 2017 at 14:01
  • Thanks for the responses. Yes I do have a counter to track the number of records and can iterate through it. My follow up question - Is it a good idea to iterate through all the records? Is there any memory limit that I might hit? I'm trying to find out the best approach.
    – Arun Kumar
    Nov 25, 2017 at 16:39
  • I guess you are talking about returning the full array or mapping. I would expect that there is a limit, but I do not have any further experience or knowledge on that. Concerning speed, it is usually recommendable to retrieve few larger chunks than each item separately, since it minimizes rpc overhead.
    – gisdev_p
    Nov 25, 2017 at 16:48

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