Basic Data Queries
Execute fundamental queries to retrieve specific data subsets from your Realtime Database.
Intro to Database Queries
Welcome to Basic Data Queries! In this lesson, you'll learn how to fetch specific data from your Firebase Realtime Database efficiently.
A database query is like asking a precise question to your database. Instead of getting all the data, you retrieve only what you need, saving bandwidth and improving app performance.
We'll use the Firebase JavaScript SDK for our examples. The core starting point for any query is a firebase.database().ref(), which points to a specific location in your database.
Sample Data & Initial Setup
First, let's set up a basic HTML page to interact with Firebase and populate some sample data. This will serve as your 'main entry point' for our examples.
We'll use a simple 'users' dataset where each user has a name, age, and city.
Important: Replace YOUR_API_KEY, YOUR_PROJECT_ID, etc., with your actual Firebase project configuration.
<!DOCTYPE html>
<html>
<head>
<title>Firebase Query Demo</title>
<script src="https://www.gstatic.com/firebasejs/8.10.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.10.1/firebase-database.js"></script>
</head>
<body>
<h1>Firebase Query Setup</h1>
<p>Check your browser's console for output.</p>
<script>
// Your Firebase project configuration
const firebaseConfig = {
apiKey: "YOUR_API_KEY",
authDomain: "YOUR_PROJECT_ID.firebaseapp.com",
databaseURL: "https://YOUR_PROJECT_ID-default-rtdb.firebaseio.com",
projectId: "YOUR_PROJECT_ID",
storageBucket: "YOUR_PROJECT_ID.appspot.com",
messagingSenderId: "YOUR_SENDER_ID",
appId: "YOUR_APP_ID"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
const db = firebase.database();
// Reference to the 'users' node
const usersRef = db.ref('users');
// Sample data to write (only if not already present)
const sampleUsers = {
"user1": { "name": "Alice", "age": 30, "city": "New York" },
"user2": { "name": "Bob", "age": 25, "city": "London" },
"user3": { "name": "Charlie", "age": 35, "city": "New York" },
"user4": { "name": "David", "age": 25, "city": "Paris" }
};
// Write data to the database (only once for demo)
usersRef.once('value', snapshot => {
if (!snapshot.exists()) {
usersRef.set(sampleUsers)
.then(() => console.log('Sample data written successfully!'))
.catch(error => console.error('Error writing sample data:', error));
} else {
console.log('Sample data already exists. Skipping write.');
}
});
console.log('Firebase initialized and sample data check complete.');
</script>
</body>
</html>