Extract the real value of the relationship lookup field in soql - salesforce

I'm a newbie to soql relationship queries. I've been trying to to get this working but not sure if this is even possible.
Select Id, Name, CustomObject__r.name From Account where customobject__c != null
Gives me a result that has a column of 'customobject__c', but which I have to click on to see the real value. I want to see the real value in the table, so that I can extract it to a csv. CustomObject is a lookup field in Account.
Is this possible? Thanks.

You need a better SOQL editor. What are you using at the moment?
Data Loader (officially supported tool) should give you these full relationship "path names" when you export data but it's a bit too clunky to be used on daily basis. You'd be designing your queries in one tool and pasting them to DL...
I'm a big fan of RealForceExplorer ;) See How to add comments in SOQL for some hints and pick your favorite editor.

Related

How can I traverse through multiple related objects based on ID and return some related field?

I'm a little stuck.
I am trying to generate a report that determines whether anyone has made a manual change to certain fields within our order framework. I have figured out the proper fields and structures to audit, and even how to make the report, but I used a combination of extracts from the Dataloader and Excel xlookups to make it. Now, I'm being asked to find a way to automate the generation of the report, and I suspect that means I need to write a SOQL query to figure it out. I'm having trouble traversing multiple relationships based on these ID fields. Essentially, what I'm trying to do is make multiple "left joins" based on the 18 digit Salesforce IDs and extract some related piece of information from those other objects.
For example, if I'm starting with order_product_history (with a field OrderProductID to identify the order product) and I want to bring in "Product Name", I have to first match OrderProductID with the ID field in my order_product "table", then I have to match the Product2ID field in my order_product "table" with the ID in my product "table", then I have to get the matching Product Name as a column in my report:
Matching/Traversal Process
Desired Result
That's one example for one field. I also have to bring in things like User Name from the users "table", and order number from the orders table, but once I get the general idea, I think I'll be OK. I also want to filter the results to only include my Fee__c and UnitPrice fields, ignore the automated users and set a date filter--not sure if I have to do that using a WHERE clause just in my main query, or if I have to filter the subqueries as well.
I am not a programmer and I have no formal Salesforce training; I am just an analyst who is technically inclined and sort of fell into the role of Salesforce Admin. I am familiar with programming concepts and have been writing things using the flow application and have even dipped my toes into some Apex stuff, but it can be a bit of a struggle. I am not asking you to do my job for me and I am willing to work at the problem and learn; any help is appreciated. Sorry about the links; SO won't let me embed images yet.
There's high chance you don't have to write any code for it. I'll give you some tips, experiment a bit and edit the question or post new one?
This diagram might help: https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_erd_products.htm
Developer way
It's all about writing the right query. You can play with it in Developer Console or Workbench for example. Read up about relationship queries in SF.
https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_relationships_understanding.htm
https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_relationships_query_hist.htm
I don't have org with orders enabled but this should be a good start:
SELECT CreatedById, Created.Name,
Parent.Name, Parent.Product2.Name, Parent.Order.Name,
Field, OldValue, NewValue, CreatedDate
FROM OrderItemHistory
If it throws errors about "Parent" see if "OrderItem" will work. Once you have it - WHERE Field IN ('UnitPrice', 'Fee__c') AND CreatedDate = LAST_WEEK might be good next step. (dates can be filtered by date but there are few "constants" that are more human-readable too)
You could even export this with Data Loader, you just have to start the wizard on Order Product history table. But you can ignore the whole query creator and paste a query you've created.
Admin way
Have you ever created a report in Salesforce? There are self-paced trainings (for Lightning and Classic UI) and tons of YouTube videos. Get a feel of making few reports.
What you want might be doable with built-in report type (see if there's new report -> order product history). If nothing exciting - as admin you can make new report type in setup. For example Orders -> Order Products -> Order Product History. Screenshots from here might help.
Just wanted to update this for anyone looking for a solution in the future.
Turns out you can traverse these as a parent-child relationship in the SOQL query. Here's the query I ended up using:
SELECT CreatedBy.Name, FORMAT(CreatedDate), OrderItem.Order.OrderNumber, OrderItem.Product2.Name, OrderItem.Product2.ProductCode, Field, OldValue, NewValue
FROM OrderItemHistory
WHERE (Field = 'Fee__c' OR UnitPrice) AND (CreatedBy.Name != 'Integration User') AND (Created Date >= 2020-11-24T00:00:00.000Z) ORDER BY CreatedDate DESC

Alias in where query in SOQL

I am trying to take the count from the object Lead using SOQL.
When I am hitting the below mention query, I am getting the results.
select 'Lead' as source_table,count(*) as source_count from Lead
But when I am trying to give where condition with this query, then it is throwing me the error.
select 'Lead' as source_table,count() as source_count from Lead where
CreatedDate > 2020-02-24T09:43:51Z
Is there anything that I am missing.
Your query is not a valid SOQL, where exactly are you doing it? In real Salesforce (Apex, developer console, Salesforce APIs) or do you work on some copy of data imported to MSSQL for example?
Even your basic form (select 'Lead' as source_table,count(*) as source_count from Lead) will not parse OK in SOQL. There's no AS keyword and no dummy columns.
Closest would be
SELECT COUNT(Id) source_count
FROM Lead
WHERE CreatedDate > 2020-02-24T09:43:51Z
There will be no artificial column with "Lead" in it. If you need some key-value thing across multiple database tables you'd have to process results in Apex, maybe make a helper class to store results, maybe a Map<String, Integer> would be enough. But if you're doing it as API access then much better idea would be to access the dedicated APIs
getUpdated REST API - has "updated" and "deleted" versions, if you really need "created" it's not that great unless you filter them out later somehow
record count across multiple objects - but it's really count in table, similar to Setup -> Storage Usage. No way to pass a WHERE clause
ask your SF admin to build a report that does what you need (you don't need details, just a count, right?), then access the results with Analytics API. Or even build the report on the fly: example

Querying Salesforce Object Column Names w/SOQL

I am using the Salesforce SOQL snap in a SnapLogic integration between our Salesforce instance and an S3 bucket.
I am trying to use a SOQL query in the Salesforce SOQL snap field "SOQL query*" to return the column names of an object. For example, I want to run a SOQL query to return the column names of the "Account" object.
I am doing this because SOQL does not allow "Select *". I have seen code solutions in Apex for this, but I am looking for a way to do it using only a SOQL query.
You want to query metadata? Names of available tables, names of columns you can see in each table, maybe types instead of real Account/Contact/... data, correct?
You might have to bump the version of the API up a bit, current is 47 / 48 so some objects might not be visible in your current one. Also - what API options you have? SOAP, REST? Is "Tooling API" an option? Because it has very nice official FieldDefinition table to pull this.
It's not perfect but this could get you started:
SELECT EntityDefinition.QualifiedApiName, QualifiedApiName, DataType
FROM FieldDefinition
WHERE EntityDefinition.QualifiedApiName IN ('Account', 'Contact', 'myNamespace__myCustomObject__c')
I don't see the table in the REST API reference but it seems to query OK in Workbench so there's hope.
Generally try to Google around about EntityDefinition, FieldDefinition, EntityParticle... For example this is a decent shot at learning which tables are visible to you:
SELECT KeyPrefix, QualifiedApiName, Label, IsQueryable, IsDeprecatedAndHidden, IsCustomSetting
FROM EntityDefinition
WHERE IsCustomizable = true AND IsCustomSetting = false
Or in a pinch you could try to see which fields your user has permission to query. It's bit roundabout way to do it but I have no idea which tables your connector can "see".
Starting from API version 51.0 there's the FIELDS() function available: it lets you query all fields of a given object similar to "SELECT *"
Example:
SELECT FIELDS(ALL) FROM User LIMIT 200
Reference:
https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_select_fields.htm

Salesforce - how can I search for all Opportunity custom fields that are empty (never been populated) for every Opportunity record?

I need to search for any opportunity's custom field that are empty for every record, so that I can delete those fields that are not used by the users. Can I do this by report or by DevConsole, with some query?
I think there are three options that would work best:
Data Loader
Use their Data Loader to export all of your opportunities into a CSV. Load it up in Excel or some other software of your choice and manually dig through the columns ending in __c looking for at least one value.
SOQL
You could manually write a SOQL query that looks at each field (e.g. SELECT Id FROM Opportunity WHERE YourCustomField1__c != null and repeat for each field)
SOQL (Dynamic)
If you're willing to get your programming hands dirty you could make a describe API call to fetch all the fields on the opportunity object. Once you know all the fields you could find fields that end in __c again and write a dynamic SOQL statement to hit the API with.
The Field Trip app (free in the AppExchange) will do this for you. Here's a link:
https://appexchange.salesforce.com/listingDetail?listingId=a0N30000003HSXEEA4
Run it for an object and it gives you a report that lists all the field and tells you what % of records are filled in for each field. My organization has been using it for several years now.
I'm not connected with Qandor. I'm just a satisfied user.

Querying XML columns in SQLServer 2005

There is a field in my company's "Contacts" table. In that table, there is an XML type column. The column holds misc data about a particular contact. EG.
<contact>
<refno>123456</refno>
<special>a piece of custom data</special>
</contact>
The tags below contact can be different for each contact, and I must query these fragments
alongside the relational data columns in the same table.
I have used constructions like:
SELECT c.id AS ContactID,c.ContactName as ForeName,
c.xmlvaluesn.value('(contact/Ref)[1]', 'VARCHAR(40)') as ref,
INNER JOIN ParticipantContactMap pcm ON c.id=pcm.contactid
AND pcm.participantid=2140
WHERE xmlvaluesn.exist('/contact[Ref = "118985"]') = 1
This method works ok but, it takes a while for the Server to respond.
I have also investigated using the nodes() function to parse the XML nodes and exist() to test if a nodes holds the value I'm searching for.
Does anyone know a better way to query XML columns??
If you are doing one write and a lot of reads, take the parsing hit at write time, and get that data into some format that is more query-able. A first suggestion would be to parse them into a related but separate table, with name/value/contactID columns.
I've found the msdn xml best practices helpful for working with xml blob columns, might provide some inspiration...
http://msdn.microsoft.com/en-us/library/ms345115.aspx#sql25xmlbp_topic4
In addition to the page mentioned by #pauljette, this page has good performance optimization advice:
http://msdn.microsoft.com/en-us/library/ms345118.aspx
There's a lot you can do to speed up the performance of XML queries, but it will never be as good as properly indexed relational data. If you are selecting one document and then querying inside just that one, you can do pretty well, but when your query needs to scan through a bunch of similar documents looking for something, it's sort of like a key lookup in a relational query plan (that is, slow).
If you have a XSD for your Xml then you can import that into your database and you can then build indexes for your Xml data.
Try this
SELECT * FROM conversionupdatelog WHERE
convert(XML,colName).value('(/leads/lead/#LeadID=''xyz#airproducts.com'')[1]', 'varchar(max)')='true'

Resources