Query snippets are parts of a query that often repeat themselves, and hence can be reused.
For example, a join between tables, a large where [not] in, or simply a frequently used constraint.
Use of the query snippets is time-saving, since now you can autocomplete large pieces of SQL code in seconds, and it can be shared between colleagues.
To create query snippets, go to Settings | Query snippets:
On the query snippets screen, you will see all the previously created snippets.
Click on the +New Snippet button to start creating a new snippet.
The new query snippet page is displayed and the following fields need to be filled in:
Trigger: This is the word that will be used to invoke the query snippet. The query editor will suggest auto-completion for this word when the user starts to type in the first few letters.
Description: This includes several words to describe the query snippet.
Snippet: This is where the user types the query snippet code.
Let's look at a quick example. Suppose I have the following query (outputs visualization types and count per type):
SELECT TYPE,
COUNT(*)
FROM visualizations
GROUP BY TYPE
ORDER BY COUNT(*);
We will create a snippet from the GROUP BY TYPE ORDER BY COUNT(*) part.
Fill in all the fields as described previously with the following:
- Trigger will be group_type_cnt
- Description: The group by type and order by count snippet test (this field is not mandatory and can be left blank)
- Snippet: GROUP BY TYPE ORDER BY COUNT(*)
After we save the snippet, let's write our query again, but this time we can autocomplete the snippet part by starting to type its trigger word:
We can see that the autocomplete finds the snippet (and even marks its type as snippet). When we select it, it will simply insert the snippets code into our query – fast and easy: