SOQL 쿼리 작성

Isa.log·2025년 6월 24일

SOQL (Salesforce Object Query Language)

👉 쉽게 말해 Salesforce 데이터베이스에 질문하는 방법. SQL이랑 비슷하지만 Salesforce 전용.

SELECT Name, Phone FROM Account

➡️ 이건 "모든 계정(Account)에서 이름(Name)과 전화번호(Phone)을 가져와줘!" 라는 뜻

Apex

👉 Salesforce 안에서 코드를 짜서 자동화하거나 기능을 만드는 언어.
Apex는 SOQL을 내부에서 사용 가능. 그래서 데이터베이스에 쉽게 접근 가능!

Account[] accts = [SELECT Name, Phone FROM Account];

➡️ Salesforce 안에서 "Account 데이터를 가져와서 accts라는 변수에 넣어줘" 라는 코드

주요 기능 정리

SELECT : 어떤 필드를 가져올지
FROM : 어떤 객체에서 가져올지
WHERE : 조건을 줄 때
ORDER BY : 정렬할 때
LIMIT : 몇 개만 가져올지 제한

과제

지금까지 배운 SOQL + Apex 클래스를 종합해서 코딩해보는 연습

Create an Apex class that returns contacts based on incoming parameters.
For this challenge, you will need to create a class that has a method accepting two strings. The method searches for contacts that have a last name matching the first string and a mailing postal code matching the second. It gets the ID and Name of those contacts and returns them.
The Apex class must be called ContactSearch and be in the public scope
The Apex class must have a public static method called searchForContacts
The method must accept two incoming strings as parameters
The method should then find any contact that has a last name matching the first string, and mailing postal code (API name: MailingPostalCode) matching the second string
The method should finally return a list of Contact records of type List that includes the ID and Name fields

👉 Apex 클래스를 하나 만들어라. 이름은 ContactSearch
👉 클래스 안에 searchForContacts라는 메서드(함수) 만들어라.
👉 이 메서드는 문자열 2개를 입력으로 받는다. (Last Name / MailingPostalCode)
👉 입력값에 맞는 Contact (연락처) 데이터를 찾아라.
👉 찾은 결과에서 Id와 Name 필드만 포함해서 리스트로 리턴해라.

[SELECT 필드 FROM 객체 WHERE 조건]
public class ContactSearch {
    public static List<Contact> searchForContacts(String lastName, String postalCode) {
        List<Contact> contacts = [
            SELECT Id, Name
            FROM Contact
            WHERE LastName = :lastName
            AND MailingPostalCode = :postalCode
        ];
        return contacts
    }
}

contacts는 리스트 변수

List<Contact> contacts = [...];

변수 contacts의 타입(=데이터 종류)는

List<Contact>

즉, 리스트 타입을 가진 변수. 여러 객체들을 담을 수 있음.
가령 Salesforce에는 수많은 Contact 레코드들이 있음. (예: John Kim, Emily Park, David Lee 등등)
👉🏻

List<Contact>는 Contact 여러 개를 저장하는 리스트

비유하자면 일반 변수는 종이컵이라 한 잔만 담을 수 있다면, 리스트 변수는 아이스박스처럼 잔뜩 담을 수 있다. 둘 다 그릇(변수)이긴 한데 리스트는 한 번에 많은 걸 담을 수 있는 특수한 그릇임.

:(콜론)은 무슨 역할을 할까?

👉 바인딩 변수 (Bind Variable).

Apex 코드 안의 변수를 SOQL에 연결해주는 역할을 한다.

profile
세상을 탐험하던 눈으로, 지금은 디버깅 중

0개의 댓글