Declarative query languages encapsulate complexity
The first databases organized data as one big tree. Developers explicitly identify the chain of links to follow from the root record, called the access path, to find a data point.
This approach was:
- Fragile - Access path would need an update with data format changes.
- Rigid - The program logic rigidly fixed the access paths.
- Sequential - The database stored the data in a specific order.
- Complicated - The program difficult to read and understand.
Declarative query languages gained popularity because they solved many of these issues. SQL was one of the first declarative query languages based on Relational Algebra, created to overcome the problems faced in the first hierarchical databases of the 1970s.
Declarative query languages do not deal with the How. They only specify the pattern of data to fetch, leaving the algorithm to the database implementation. The database engine encapsulates the query mechanism, exposing a functional yet straightforward API to the external world. Since the algorithm is not rigidly defined, each database has the opportunity to custom define it to leverage its unique features.
Since the query language does not have to deal with optimization or construction, it tends to remain simple, concise, and clear. Developers can intelligently combine them to construct more complex queries for complicated data requirements.
Declarative queries also adapt well to improving technology. For example, with increased CPU speeds in recent years because of additional cores, database systems can parallelize the query processing across multiple cores and multiple machines.
SQL is the most popular example of query languages, but others like Cypher and SPARQL were built to overcome the imperative query limitations for graph databases.
Declarative query languages are not restricted only to databases. CSS and XSL are interesting parallels that support declarative queries for the browser. Apart from being concise and easy to understand, being declarative helps web browsers improve performance without breaking compatibility to existing web pages.