Sub topic 12
Confirming the org with a SOQL query and Apex
You have signed up, set a password, registered multi-factor authentication (MFA), and authorized the Salesforce CLI. This chapter checks that the org you connected is the one you meant to create. You will do that in two ways: with a SOQL query run from the CLI, and with Apex run as an anonymous script.
This chapter assumes you have:
- A Developer Edition org that you can log in to.
- The Salesforce CLI (
sf) installed and authorized with the aliasmy-dev-org, as in the previous chapter. - Basic familiarity with SQL-style queries, and enough Apex to read a single statement.
Why verify at all
A successful login only proves that some org accepted your credentials. It does not prove that:
- The CLI alias points at the org you intended.
- The org is a Developer Edition org and not a sandbox or Trailhead Playground.
- You are logged in as the user you expect.
These mix-ups are common when you hold several orgs and reuse a browser session. A browser logged in to one org can quietly authorize the CLI against that org instead of the new one. Two short checks remove the doubt before you build anything.
The checks look at the org from two sides:
| Check | Where it runs | What it proves |
|---|---|---|
| SOQL query on `Organization` | CLI, through the API | The alias reaches an org of the expected name and edition |
| Anonymous Apex with `UserInfo` | Inside the org | The org name and user the code runs as |
If both agree, the CLI, the browser, and the org all describe the same thing.
Check 1: query the Organization object
SOQL (Salesforce Object Query Language) reads records from objects. The Organization object is a special case. Every org has exactly one Organization record, and it stores facts about the org itself. Run this command:
sf data query --target-org my-dev-org --query "SELECT Name, OrganizationType FROM Organization"The flags are:
--target-org(short form-o) names the org by alias or username.--query(short form-q) holds the SOQL text. Wrap it in quotes so your shell does not split it.
The output is a table with one row. It looks roughly like this, although the exact layout varies with the CLI version:
Querying Data... done
Name OrganizationType
───────────── ──────────────────
Example Corp Developer Edition
Total number of records retrieved: 1.Name is the company name from your sign-up form, and OrganizationType should read Developer Edition. If Name is not what you typed at sign-up, the alias probably points at a different org.
Add fields that settle ambiguous cases
OrganizationType alone is not always decisive. Other free orgs can report the same edition. A Trailhead Playground can also show Developer Edition, and so can a scratch org. A wider query helps:
sf data query --target-org my-dev-org --query "SELECT Id, Name, OrganizationType, IsSandbox, InstanceName, NamespacePrefix, TrialExpirationDate, CreatedDate FROM Organization"How to read each field:
Idis the 15-character org ID, which starts with00D. The query API usually returns it in this form.IsSandboxisfalsefor a production-type org, which includes Developer Edition. It istruefor sandboxes and scratch orgs.InstanceNameis the server instance, such asNA123orCS45. It confirms where the org is hosted.NamespacePrefixis normally empty in a new org.TrialExpirationDateis normally empty for a sign-up Developer Edition org. A value suggests a trial or a scratch org with a lifespan.CreatedDateshould match the day you signed up. An older date means you connected to an org that already existed.
Taken together, IsSandbox = false, an empty TrialExpirationDate, and a CreatedDate from today are good evidence that you reached your new Developer Edition org.
Get machine-readable output
Add --json when you want to script the check. The result is JSON, and the records sit under result.records:
sf data query --target-org my-dev-org --query "SELECT Name, OrganizationType FROM Organization" --jsonYou can also use --result-format csv for spreadsheet-style output. These flags change only the format and have no effect on the data.
Related command
sf org display --target-org my-dev-org prints the org ID, the username, the instance URL, and the connection status from the CLI's own stored authorization. It does not query the org. It shows what the CLI believes. The SOQL query shows what the org says. When they disagree, trust the query.
Check 2: anonymous Apex
Apex is Salesforce's server-side programming language. Anonymous Apex is a block of code that runs once, with no class or trigger saved in the org. It is useful for quick checks because it executes with your user's permissions inside the org.
The UserInfo class exposes details about the running user and the org. This script prints two of them to the debug log:
System.debug('Org: ' + UserInfo.getOrganizationName());
System.debug('User: ' + UserInfo.getUserName());Run it in the Developer Console
- In the org, click the gear icon and choose Developer Console.
- Choose Debug, then Open Execute Anonymous Apex Window.
- Paste the two lines. Keep Open Log ticked and click Execute.
- In the log window, tick Debug Only to hide the system noise.
You should see two lines starting with USER_DEBUG, one with the org name and one with your username. The username has the email format you chose at sign-up, and it may differ from your email address.
Run it from the CLI
You can run the same script without leaving the terminal. Save it as verify.apex, then run:
sf apex run --target-org my-dev-org --file verify.apexThe command compiles and executes the script, then prints the debug log to the terminal. Look for the USER_DEBUG lines. This path also exercises the CLI authorization, which is the thing you are verifying.
A richer script
You can also read the Organization record from inside Apex. This script compares the two approaches and flags a sandbox:
Organization org = [SELECT Name, OrganizationType, IsSandbox FROM Organization LIMIT 1];
System.debug('Org name: ' + org.Name);
System.debug('Edition: ' + org.OrganizationType);
System.debug('Is sandbox: ' + org.IsSandbox);
System.debug('Org ID: ' + UserInfo.getOrganizationId());
System.debug('User ID: ' + UserInfo.getUserId());
System.debug('Username: ' + UserInfo.getUserName());
if (org.IsSandbox) {
System.debug('WARNING: this is a sandbox, not a Developer Edition org.');
}Two points about this script:
- A query written in square brackets is inline SOQL. When it is assigned to a single record variable, it throws an exception if it returns no rows.
LIMIT 1keeps the result to one row. UserInfo.getOrganizationId()returns an 18-character ID. The API query often shows the 15-character form. They identify the same org, and the first 15 characters match.
Reading the results together
Compare the two outputs against a short checklist:
- The org name from the query equals the name from
UserInfo.getOrganizationName(). - The edition reads
Developer EditionandIsSandboxisfalse. - The username in the log is the one you registered, and it matches the username shown by
sf org display. CreatedDateis from the day you signed up.
If every line matches, the org is confirmed. Note the username and the org ID somewhere safe. You will need them when you troubleshoot or enable Dev Hub.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `No authorization information found for my-dev-org` | The alias was never saved, or it has a typo | Run `sf org list` to see the saved aliases. Authorize again with `sf org login web --alias my-dev-org`. |
| `INVALID_SESSION_ID` or an expired-token message | The authorization was revoked, or the password or MFA settings changed | Run `sf org login web` again to refresh the stored token. |
| The query works but returns the wrong org name | The alias points at another org | Run `sf org list`. Re-authorize the alias against the correct org, using a private browser window so an existing session is not reused. |
| `unexpected token` or a parse error in the query | The shell broke up the query | Wrap the whole query in double quotes. Use single quotes inside it for string values. |
| Developer Console shows no `USER_DEBUG` lines | **Debug Only** is unticked, or the log did not open | Tick **Debug Only**, or reopen the log from the **Logs** tab. |
| A browser opens on a login page you do not recognize | The CLI is using a custom login URL | Check for an `--instance-url` setting in earlier commands. For a Developer Edition org the default login URL is correct. |
Edge cases
- Several orgs, one alias. Aliases are local to your machine. Assigning an existing alias to a new org replaces the old mapping without a warning. Run
sf org listbefore and after you authorize a new org. - Default org. If you set a default target org, you can leave out
--target-org. This is convenient, but it is also how people run commands against the wrong org. Always pass--target-orgwhile you are learning. - Permissions. The Developer Edition user you created is a System Administrator, so these queries work. In other orgs, a restricted profile may not be able to run anonymous Apex.
- Inactive orgs. If the org was left unused for a long time, login can fail even though the sign-up worked. The limits chapter covers how to keep the org active.
Exercise
You run sf data query --target-org my-dev-org --query "SELECT Name, OrganizationType FROM Organization" and it prints Developer Edition, but the Name is a company you do not recognize. Which two additional checks would you run to find out what happened, and what would each tell you?
Show answer
First run sf org list to see which org and username the alias my-dev-org actually maps to. The alias may have been assigned to a different org during authorization. Then run the wider query with Id, IsSandbox, CreatedDate (or anonymous Apex with UserInfo.getUserName()) to see which org and user you reached. If the user or the creation date is not yours, re-authorize with sf org login web --alias my-dev-org in a private browser window, logging in as the new Developer Edition user, and repeat the checks.
Exercise
Why does the chapter recommend running the same check both with SOQL from the CLI and with anonymous Apex, instead of only one of them?
Show answer
The two checks look at the org from different sides. The SOQL query shows what the org says about itself through the API, using the CLI's stored authorization. The anonymous Apex runs inside the org as the logged-in user and shows the org name and username. If both give the same org name, edition, and user, you can be confident that the CLI, the browser session, and the org all refer to the same Developer Edition org. A mismatch points to a wrong alias or a wrong login session.