DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • How to Restore a Transaction Log Backup in SQL Server
  • How to Attach SQL Database Without a Transaction Log File
  • A Deep Dive into Apache Doris Indexes
  • Spring Boot Sample Application Part 1: Introduction and Configuration

Trending

  • Blue Skies Ahead: An AI Case Study on LLM Use for a Graph Theory Related Application
  • Concourse CI/CD Pipeline: Webhook Triggers
  • Artificial Intelligence, Real Consequences: Balancing Good vs Evil AI [Infographic]
  • Immutable Secrets Management: A Zero-Trust Approach to Sensitive Data in Containers
  1. DZone
  2. Data Engineering
  3. Databases
  4. Is SQL a Declarative Language?

Is SQL a Declarative Language?

When faced with complex tasks, the difficulty increases sharply, and some tasks cannot be implemented using SQL alone because it is not Turing-complete.

By 
Judy Liu user avatar
Judy Liu
·
Dec. 19, 23 · Opinion
Likes (2)
Comment
Save
Tweet
Share
2.0K Views

Join the DZone community and get the full member experience.

Join For Free

When learning SQL, we often hear the saying that SQL is a declarative language. You just need to tell it what to do; without telling it how to do it, it will find its own implementation method. That is to say, you need to use it only to describe the task objectives without explaining the computational process, which is fundamentally different from conventional procedural languages. Obviously, this programming language sounds much easier to learn and use. 

Is it really that good?

Let’s take a look at an example. We use SQL to query the number of female employees in the sales department. This is the written SQL:

SQL
 
SELECT COUNT(*) FROM employee WHERE department='Sales' AND gender='Female'


It seems like this: we don’t need to care about the specific calculation process (traversing every record in the employee table, adding 1 to the count if it meets the conditions, skipping if it doesn’t, and finally looking at the count), just state the target to be queried.

Let’s take a look at another example: find the average salary of employees aged above 30 by department:

SQL
 
SELECT department,AVERAGE(salary) FROM employee WHERE age>30 GROUP BY department


It looks good, too. Here, we really don’t have to care about how to group and calculate the average.

Although SQL is still a language with strict syntax, we can only write correct statements after a certain amount of learning. However, if we don’t care about the calculation process, it will still save a lot of effort.

Let’s take a look at another example. Identify the major customers who contribute to the top half of sales. If we design the calculation process, it would be like this:

  1. Calculate the total sales revenue of all customers.
  2. Sort customers in reverse order of sales revenue, with the large ones ranking first and the small ones ranking last.
  3. Accumulate the sales revenue of each customer from 0 in this order and stop when it exceeds half of the total sales revenue. Then, the customers that have been traversed are the target customers.

Then, what does it look like to write it in SQL? This is the simplest way I can think of:

SQL
 
SELECT customer, amount, cum_amount
FROM ( SELECT customer,amount,SUM(amount) OVER (ORDER BY amount DESC) cum_amount FROM ordersummary )
WHERE cum_amount < (SELECT SUM(amount) FROM ordersummary)/2


Take a closer look at this SQL statement, which basically describes the above process. There is a sub-query that calculates total sales, followed by a sub-query that sorts sales in reverse. The window function is used to calculate the cumulative sales of each row in the sorted list. The main query then filters out customers whose cumulative sales are less than half of the total sales. The only difference from the above process is the writing order. SQL starts calculating the total sales revenue later. There is also a slight logical difference, as SQL’s ordered calculations and step-by-step calculations are not good. It is necessary to calculate all accumulated sales before finding the top ones.

This SQL statement accurately describes such a process. What about describing the task objective without worrying about the computational process?

Let’s take a simpler example: find the top 10 customers with the highest sales revenue.

Some SQL statements are written as follows: 

SQL
 
SELECT TOP 10 customer FROM ordersummary ORDER BY amount DESC


If using a well-known database, you also need to use subqueries:

SQL
 
SELECT customer
FROM ( SELECT rownumber rn,customer FROM ordersummary ORDER BY amount DESC )
WHERE rn<=10


Both of these SQL statements clearly tell us the calculation process: after sorting by sales revenue in reverse, get the top 10. Moreover, in the syntax of this famous database, it is necessary to artificially create a serial number, which means that the database needs to be more clearly told how to calculate.

If we look at a few hundred rows of SQL (stored procedures), we can see more clearly that SQL still describes the calculation process honestly, and different calculation processes can bring vastly different computational performance and even results.

In fact, any programming language can be said to be a declarative language to some extent: that is, it only needs to care about the goal and not the process.

If you write a program in Java, you only need to care about how variables change without worrying about the actions of registers in the CPU, but in assembly language, you need to care. Similarly, when using assembly language, you need to care about the values of registers, but you don’t have to worry about how the NAND gate operates in the CPU.

When writing code in SQL, there is generally no need to worry about the specific actions of variables and loops. It does not have the concept of variables, but it has the concepts of tables, fields, and related calculation methods, and you also need to pay attention to the process at this level. In this sense, SQL and other programming languages only have different levels of abstraction in describing problems, and there is no essential difference in explaining processes.

Why do so many people think that SQL is a so-called declarative language? This is because the design of SQL deliberately weakens the “procedural” feature, and in order to make the statement more like English, it puts basic operations into each clause of a statement. When all the steps involved in the calculation task are basic operations within the abstract level of SQL, it can be written as one statement, seemingly describing the task goal to SQL.

However, conventional programming languages usually do not design multiple basic operations into clauses or function parameters of one statement and advocate for programmers to combine them. This way, people will feel the need to describe the process and do not have the characteristic of “being declarative.”

However, the clause structure of a statement is limited, even if it is complex. When the task is beyond the scope of this structure and requires the use of nested subqueries or intermediate results to describe it, the so-called “declarative” illusion of SQL will be exposed. It is still necessary to honestly describe the process and approach. Looking back at the previous example, it is clear to see this point.

SQL is indeed easier to learn and use compared to high-level languages like Java when facing some basic query tasks, but it is not because it has stronger “declarative” features than Java but because it has a higher level of abstraction in structured data computation than Java.

SQL deliberately weakens the “procedural” characteristics, such as the absence of intermediate variables, which makes its ability to describe processes very weak. When faced with complex tasks, the difficulty increases sharply, and some tasks cannot be implemented using SQL alone because SQL without procedural capabilities is not Turing complete. So, database vendors later have to supplement and invent stored procedures and CTE syntax.

If we invent a language that has a high level of abstraction for data computation while retaining its procedural features, you will find it easier to learn and use than SQL, especially when facing complex business logic. Well, this is esProc SPL.

Database sql

Published at DZone with permission of Judy Liu. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • How to Restore a Transaction Log Backup in SQL Server
  • How to Attach SQL Database Without a Transaction Log File
  • A Deep Dive into Apache Doris Indexes
  • Spring Boot Sample Application Part 1: Introduction and Configuration

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!