by mg · 2y ago · 0 comments
SELECT AVG(price) FROM cars
WHERE brand='BMW'
GROUP BY year
ORDER BY year
without SQL?So far, every alternative syntax I have encountered was less human readable and/or less concise.
I think SQL will never be replaced because it is not really something that was invented but rather the simple consequence of wanting to store and retreive data.
You could replace "SELECT" with "GET" or "FETCH". But in the end you need to define what action you want to perform. You could replace "WHERE" with "FILTER" or "CONDITION". But in the end you need to define what you want to retreive. Etc. So by just stating the neccessary information, you always end up with SQL. And every real alternative has the problem of being less concise, less easy to read and less easy to write.
from cars
filter brand == "BMW"
group year (
aggregate [
average_price = average price
]
)
sort year
select average_price
A bit longer, but I love that it reads from top to bottom. When you have a complex SQL query, I’ve sometimes found it easier to write it as PRQL and then convert it to SQL return Cars
.query()
.select(avg('price'))
.where( { brand: "BMW" })
.groupBy('year')
.orderBy('year')The trade-offs are usually worth it, vs, doing something like:
const row = db.query('select whatever from wherever');
const obj = {
id: row.id,
brand: row.brand,
... etc
};On our projects, which are moderately small, I genuinely don't know if it is/was worth the hassle of setting up, vs. writing some repeated code. (We also have a pretty decent testing culture in place, so I would be much more accepting of DRY-violations.)
Some issues come to mind:
Grouping on the client would mean that you have to send the ungrouped data over the wire/air. Which might be orders of magnitude more data than the client needs. What if "cars" is a table of car photos made over the last 15 years and there are 20 million photos of BMWs in there? You send all the 20 million rows to the client to crunch it down to 15 rows?
The ungrouped data might be something the client is not allowed to see.
Depending on the type of grouping, the client would have to reimplement fast and efficient algorithms that have been tested and optimized for decades in RDBMs. Good luck, matching that by writing some JS for the browser.
And writing the query in SQL is probably also faster than trying to write down the prompt.
Sometimes it can be used to optimize your queries, but it isn't its strength either.
range of c is cars
retrieve (avg(c.price) where c.brand = 'BMW' by c.year)I suppose if your example is using a NoSQL (meaning non-relational) database, that is ironically queried using SQL, then you might need something else. But my understanding is that we're back on the relational kick these days.