By Amir Fuhl
Flunky
I thought this would be a slam-dunk, but apparently not. I have a SELECT COUNT(id) FROM {table X}, which functions properly.
I then want to divide the results of that COUNT() by the results of another SELECT COUNT() using the “/” operator, but I get a syntax error on that “/”
The exact expression I’m trying to evaluate is below. I want to divide the number of id values in the members table by the number of id values in the orchestras table. The individual SELECT statements function properly, but the “/” is apparently a problem, and I can’t determine why.
Has anyone seen something like this, and/or does someone have any ideas about what to try? I’m really at the end of my proverbial rope.
SELECT COUNT(id) FROM members / SELECT COUNT(id) FROM orchestras
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
Hi there,
The issue you’re facing is related to your SQL syntax.
Basically in SQL, you can’t directly divide the results of two SELECT COUNT()
statements using the /
operator like that.
Instead, you need to use subqueries or CROSS JOIN
to combine the results of the two COUNT()
queries and then perform the division.
Here’s how you can do it using a subquery:
You can use subqueries to first compute each COUNT()
and then divide the results:
SELECT
(SELECT COUNT(id) FROM members) /
(SELECT COUNT(id) FROM orchestras) AS ratio;
Alternatively, you can use a CROSS JOIN
to calculate the ratio in a single query:
SELECT
m.count_members / o.count_orchestras AS ratio
FROM
(SELECT COUNT(id) AS count_members FROM members) m
CROSS JOIN
(SELECT COUNT(id) AS count_orchestras FROM orchestras) o;
SELECT COUNT()
is computed separately, and then the results are divided.CROSS JOIN
combines the results of both COUNT()
queries into a single row, where you can perform the division.Make sure that the COUNT(id)
in both tables doesn’t result in zero to avoid a division by zero error.
These approaches should resolve the syntax issue and allow you to calculate the ratio of the counts from the two tables.
- Bobby
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
Full documentation for every DigitalOcean product.
The Wave has everything you need to know about building a business, from raising funding to marketing your product.
Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.
New accounts only. By submitting your email you agree to our Privacy Policy
Scale up as you grow — whether you're running one virtual machine or ten thousand.
Sign up and get $200 in credit for your first 60 days with DigitalOcean.*
*This promotional offer applies to new accounts only.