The SQL Query to power Google Suggest
You probably know Google Suggest or one of its derivatives. An input item on a web-page or another user interface where you can enter a value that all of a sudden becomes active and helpful by displaying a number of suggestions. For example a Country field that we can enter the country into within the previously selected Region (Europe in this case):
After entering Bel, the suggestions are displayed as shown in the screenshot. This article describes the SQL we could use for producing the list of suggestions.
The data returned by the query should satisfy these conditions:
- only countries can be shown that are equal to what was entered, start with the value that was entered or come alfabetically after the value that was entered
- if there is no value at all that starts with the string entered, then no values may be displayed
- no more than five values can be shown
When we type an extra g, Belarus disappears as suggestion since it does not start with Belg. Finland is added as fifth (and not very logical) suggestion.
When we enter Belgr, we see no suggestions at all, since no single value starts with Belgr.
The data displayed in this example is retrieved from two tables: REGIONS and COUNTRIES that are linked through a REGION_ID column. The join query looks like this:
select region_name<br /> , country_name<br /> from regions<br /> join<br /> countries<br /> using (region_id)<br /> order<br /> by region_name<br /> , country_name
If we only want to see countries in Region=Europe, we have the following query:
select country_name<br />from regions<br /> join<br /> countries<br /> using (region_id)<br />where region_name = 'Europe' <br />
Now we want to create the Google Suggest Query, based on the requirements indicated above. The following query does exactly what we need:
select country_name<br />from ( select country_name<br /> , first_value( country_name) <br /> over (order by country_name) first_country_value<br /> from ( select country_name<br /> from regions<br /> join<br /> countries<br /> using (region_id)<br /> where region_name = 'Europe' <br /> )<br /> where country_name >= 'VALUE_ENTERED_BY_USER'<br /> order<br /> by country_name<br /> ) <br />where first_country_value like 'VALUE_ENTERED_BY_USER%'<br />and rownum < 6<br />/<br />
Some results of using this query:
- Analytical Power
- SQL*Plus or Report style Break Groups in SQL Query
- Find the number of descendant nodes in a SQL query – how many employees work (indirectly) for me? And what do they earn on average?
- Hierarchical query with nodes from different tables – DEPT and EMP nodes in one tree
- Cost Based Optimizing through time travel? – the value of meta-data for enabling Query Rewrite