How to Check If a Firebase Database Value Exists

Check if value exists in firebase DB

The exists() method is part of the snapshot object which is returned by firebase queries. So keep in mind that you won't be able to avoid retrieving the data to verify if it exists or not.

ref.child("users").orderByChild("ID").equalTo("U1EL5623").once("value",snapshot => {
if (snapshot.exists()){
const userData = snapshot.val();
console.log("exists!", userData);


In case you are in a different scenario which you have the exact ref path where the object might be, you wont need to add orderByChild and equalTo. In this case, you can fetch the path to the object directly so it wont need any search processing from firebase. Also, if you know one of the properties the object must have you can do as the snippet below and make it retrieve just this property and not the entire object. The result will be a much faster check.

//every user must have an email
firebase.database().ref(`users/${userId}/email`).once("value", snapshot => {
if (snapshot.exists()){
const email = snapshot.val();

Checking if a particular value exists in the Firebase database

To check the existence of a user, please use the below code:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference userNameRef = rootRef.child("Users").child("Nick123");
ValueEventListener eventListener = new ValueEventListener() {
public void onDataChange(DataSnapshot dataSnapshot) {
if(!dataSnapshot.exists()) {
//create new user

public void onCancelled(DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!

You can also use a Query to achieve the same thing like this:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
Query query = rootRef.child("Users").orderByChild("userName").equalTo("Nick123");
query.addValueEventListener(/* ... */);

This is another approach which is looping through the entire Users node but is not just using a direct reference to a single user. This option is more likely to be used when you are using as a unique identifier beteeen users the uid instead of the user name (as you do right now). So if your database structure might looks similar to this:

--- Users
--- uid
--- userName: "Test User"
--- emailAddress: ""

The second solution is the recommended one.

There is also another solution which involves you to create another node named userNames, in which you can hold only the unique user names. Please also find below the corresponding security rules:

"Users": {
"$uid": {
".write": "auth !== null && auth.uid === $uid",
".read": "auth !== null && auth.provider === 'password'",
"userName": {
".validate": "
!root.child('userNames').child(newData.val()).exists() ||
root.child('userNames').child(newData.val()).val() == $uid"

But since in this case, your user name is already the name of the node, I recommend you go ahead with the first one.

How to check if value exists in Firebase Realtime Database (Dart/Flutter)?

once() always yields a DataSnapshot object. You have to check if that snapshot contains any data by looking at its value property.

  if (snapshot.value == null) {
print("Item doesn't exist in the db");
} else {
print("Item exists in the db");

Check if some key value exists in Firebase Database and do some action Android

After a long time, my brain light burned and I came up with a solution.

Create a data class for OrderState

public class OrderState {
public static int ordersCount = 0;

public static boolean state = false;

public static void update(boolean state){
if (state){
ordersCount = ordersCount + 1;
OrderState.state = true;
if (!state && ordersCount > 0){
ordersCount = ordersCount - 1;
if (ordersCount < 1) OrderState.state = false;

public static void reset(){
ordersCount = 0;
state = false;

On FirebaseRecyclerAdapter -> onBindViewHolder

//if order not canceled or completed. it will update OrderState, 
//ordersCount + 1 and state to true

if (adminOrders.getState().equals(Prevalent.orderStateNew) ||
adminOrders.getState().equals(Prevalent.orderStateApproved) ||
adminOrders.getState().equals(Prevalent.orderStateShipped) ||


On changing state of order by admin

//if the order is not already cancelled or completed, reduce one order from OrderState as it will be readded automatically upon Recycler refresh.

if (!adminOrders.getState().equals(Prevalent.orderStateCanceled) &&
!adminOrders.getState().equals(Prevalent.orderStateCompleted)) OrderState.update(false);

Al last if the user does not has any order with states New, Approved, and Shipped
OrderState.orderCount = 0;
OrderState.state = false;
and upon updating the database it will set the state to false.

private void changeUserWithOrderState() {
DatabaseReference userWithOrder = FirebaseDatabase.getInstance().getReference()

HashMap<String, Object> map = new HashMap<>();
map.put(Prevalent.orderState, String.valueOf(OrderState.state));
userWithOrder.updateChildren(map).addOnCompleteListener(task -> {
//Changed state based upon OrderState.state value...

How to check if a value exists in firebase

Try this:

boolean CheckExists =false;   //declare and assign default value in global scope

reference.child("Users").addListenerForSingleValueEvent(new ValueEventListener() {
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
Iterable<DataSnapshot> userChildren = dataSnapshot.getChildren();

for (DataSnapshot user: userChildren) {
User u = user.getValue(User.class); //make a model User with necessary fields

CheckExists =true;

public void onCancelled(@NonNull DatabaseError databaseError) {


function to check if a value exists in firebase database (variable needs to be final or effectively final)

You have two separate problems, the compiler error and a conceptual error. To get your desired result, you need to restructure the code to fix the conceptual error, but you should also try to understand the compiler error in the existing code.

For the compiler error, see the explanation of effectively final variables in anonymous inner classes in this question.

(You didn't provide imports in your example, so I am guessing about the framework you are using in the links I provide below).

For the conceptual error, according to the documentation, the purpose of the addListenerForSingleValueEvent method is to register a listener that will be notified (asynchronously, i.e., in another thread) if the value referred to by the DatabaseReference changes. Even if your code compiled, registering the listener would return immediately, and the value of your exists variable would depend on whether the listener happened to update the value of the variable in the very short time before your code reached the return statement.

Instead, you need to check the value directly. For this, I think you need the get method. This method is also asynchronous, but works differently. It gives you a Task, and you need to wait for the Task to complete (using the Tasks.await) before retrieving its value.

The code should look something like this:

    public boolean esiste(String desc, DatabaseReference meseref){

Task<DataSnapshot> task = meseref.get();
DataSnapshot dataSnapshot = Tasks.await(task);
return snapshot.child(desc).exists();

Check If a Particular Value Exists in the FireBase Database Using Python

To conditionally write a value to a path in the database, you can use a transaction.

In your case that's look something like:

def set_initial_value(current_value):
return current_value if current_value else {
'Name' : user.full_name,
'ID' : str(,
'Date' : str('Asia/Damascus')).strftime("%d-%b-%Y")),
'Time' : str('Asia/Damascus')).strftime("%H:%M:%S"))

ref = db.reference("/Logs")
print('Transaction completed')
except db.TransactionAbortedError:
print('Transaction failed to commit')

How do you check if value exists within Firebase live database using Firebase Functions?

const functions = require('firebase-functions');
const admin = require('firebase-admin');


exports.test = functions.https.onRequest((request, response) => {

return ExistTest();

function RandCharGen(length){

var result = '';
var characters = 'ABCDEFGHIJKLMNPRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789';
var charactersLength = characters.length;

for ( var i = 0; i < length; i++ ) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));

return result;

function ExistTest(){
var result = RandCharGen(4);
admin.database().ref(result).once('value', (snapshot) => {
if (snapshot.exists()) {
return result;

For anyone who wants the correct answer or knows a cleaner way of doing so.

Related Topics

Leave a reply