Podcast #128: We chat with Kent C Dodds about why he loves React and discuss what life was like in the dark days before Git. Listen now.

Questions tagged [subquery]

SQL term used to describe when a `SELECT` statement is used as part of a larger SQL statement. The larger statement may be DML and is always found within brackets or parenthesis.

Filter by
Sorted by
Tagged with
0
votes
1answer
27 views

Ordering by field, constructed by subquery is slow

My tables (oversimplified for clarity): documents: registrations: |id| |id|document_id|date| My simplified query: SELECT * FROM (SELECT documents.*, (SELECT max(date) ...
1
vote
1answer
226 views

Having a subquery somehow do the same group by as the outer query

i'm pretty decent with SQL but it's not my main experience of expertise. A colleague asked me a stumper of a question the other day. I was wondering if you guys could provide assistance. Basically we'...
1
vote
1answer
131 views

Single MySQL query with row averages based on conditions

I have problem, where i know how to proceed with multiple queries, but dont really now I Have a table with BP { name: varchar systolic : int diastolic : int timestamp: date } I need to ...
-1
votes
0answers
13 views

how to optimise update using subquery in PostgreSQL

I have got a table with just above 30million records and I have been running this query but I then realised that it is somehow taking too much time update foo_bar set bd_length =foo.total_length ...
0
votes
1answer
33 views

Calculating percentage over sub query SQL

I have a table that records events regarding email campaigns. I want to figure out the percentage of campaigns where there was more than one event happening for the campaign. First I calculated the ...
0
votes
1answer
34 views

Query with a few subqueries and appropriate indicies taking, on average, 613ms to execute

I have a ton of queries that do a similar thing as to what I'm doing here, but none of them have the performance issues this one does: SELECT (SELECT lead_id FROM leads WHERE to_id = lead_id OR ...
5
votes
1answer
2k views

Why does adding ROWNUM to a query improve performance?

I have two queries: 1) This query has a ROWNUM column (takes 20 seconds to execute): SELECT ROWNUM ,ROAD_ID ,VERTEX_INDEX ,SDE.ST_X(ST_POINT) AS X ,SDE.ST_Y(ST_POINT) AS Y ...
2
votes
1answer
666 views

Unable to send WHERE parameters to subquery

I have the following problem (in PostgreSQL in combination with PostGIS): I have the following nice query who clusters multiple records. Although it uses PostGIS function, my problem is not PostGIS ...
0
votes
2answers
99 views

MySQL Function work very slow

I have writed this mysql function, it's worked perfekt but very slowly, what can I do for better performance, have you any idea? note:i need all created virtual columns DROP FUNCTION IF EXISTS ...
0
votes
1answer
55 views

Aggregate function on subquery

I have got a SALES table that has 4 document types, and they are created with reference to each other in the following order: Offer -> Order -> Delivery -> Invoice. For each new row their ...
0
votes
1answer
61 views

optimize query — remove nested selects

How can I rewrite the query to increase performance? Here is the query: SELECT flight.*, DAYOFWEEK(flight.flight_time) AS day_of_week, IF(SUM(...
0
votes
0answers
16 views

adding results of InfluxDB subqueries

I'm trying to get the kWh from multiple entities in InfluxDB in Grafana. I have the following raw query. SELECT ("a" + "b") / 3600000 FROM ( SELECT spread("watt_seconds") AS "a" FROM "W" ...
7
votes
1answer
454 views

Replace long GROUP BY list with a subquery

This is a repost of my question on Stack Overflow. They suggested to ask it here: I found an online article from 2005, where the author claims, that many devs use GROUP BY wrong, and that you should ...
4
votes
1answer
261 views

Spatialite: use of virtual spatial index for distances

I'm currently learning to use spatial access methods for query optimization. I'm going through the examples in spatialite cookbook and got stuck in here http://www.gaia-gis.it/gaia-sins/spatialite-...
0
votes
1answer
363 views

MYSQL join on subquery optimization

This is a distilled version of the query that I am trying to run: SELECT * FROM table1 t1 INNER JOIN (SELECT * FROM table2 WHERE foo = 'bar') t2 ON t1.id = t2.id; The above query is incredibly slow ...
0
votes
1answer
186 views

How to optimize UPDATE with a nested SELECT subquery?

I wrote a complicated UPDATE query, and it works, but it looks menacing. Here's what I'm trying to do: In each topic user 'Bob123' posted anonymously. When you post anonymously in a topic, you get ...
0
votes
1answer
622 views

Merge sub-queries to a single query

I am trying to merge the nested MYSQL queries into one First of all I fire this query select names , city , category from names_data group by names , city ,category ; this produces a result of ~...
0
votes
1answer
44 views

Sub Query with group by returns more than 1 row Issue

I am facing the issue of subquery returns more than 1 row cause I am using group by in the subquery and outer query both to get the desired result. This is my query SELECT Count(*) ...
1
vote
1answer
387 views

Do too many subquries create multiple sleeping processes in MySQL?

I am using java & MySQL to make an app. When I check the process list. I see a lot of sleeping processes. It also reaches to a points when no further connection is allowed. I have read many ...
2
votes
1answer
373 views

Best way to move CTE into query so planner can better optimize and I can add indexes speed it up? [closed]

I'm trying to incorporate the CTE into my final query. I can do it, but it slows it down a lot because I have to do the same sub query for CTE d over and over again (I think): with d AS( SELECT ...
5
votes
2answers
206 views

A better way to write this query?

I have the following schema for my database (Postgresql 10): CREATE TABLE "PulledTexts" ( "Id" serial PRIMARY KEY, "BaseText" TEXT, "CleanText" TEXT ); CREATE TABLE "UniqueWords" ( "Id" serial ...
1
vote
2answers
5k views

Use array expression from subquery in ANY() condition

I have a relatively complicated query with a subquery fetching an array like so: ... ARRAY(SELECT category_id FROM category_schedule_con con WHERE s.id = con.schedule_id ORDER BY category_id) ...
1
vote
2answers
2k views

MySQL Correlated Subquery (with multiple columns) per row

MySQL documentation states that: Subqueries in the FROM clause cannot be correlated subqueries. They are materialized in whole (evaluated to produce a result set) during query execution, so ...
0
votes
1answer
230 views

There is a column named in table but it cannot be referenced from this part of the query

I've been learning Postgres (coming from SQL Server), and this error really confuses me. Here is the code with some sample data: create table T ( ID serial primary key, A varchar(1), B varchar(1), C ...
0
votes
1answer
28 views

Need help with correlated subquery

I have two PostgreSQL tables that each contain a column called date_of_incident. They each also have a column called incident_id and this is how the tables are related. I want to update all rows of ...
3
votes
1answer
2k views

User variable in nested subquery not getting picked up - in complex sort of 2 tables with gaps

I have just recently learned about user variables (ie, @myvar) and am trying to create a complex sorting query that takes 2 tables where the second is missing a column which then gets filled in by a ...
3
votes
2answers
116 views

Can subqueries produce different execution plans than CTE's?

I was talking with the bossman, and he prefers subqueries over CTE's. Personally, I loathe subqueries. He mentioned that subqueries can be faster, but I am not convinced. I ran this short test: ...
0
votes
1answer
39 views

Postgres Pass Subquery results to function that returns TABLE

I have a function that accepts arrays as parameters and returns a table. I can get the arguments passed in correctly, but it is returning rows of type record. If I try to expand the record with FROM I ...
0
votes
1answer
84 views

Optimize slow COUNT in MySQL subquery

I have the following query that takes minutes to complete: SELECT DISTINCT Designation, Model, ( SELECT COUNT( Equipment.EquipmentID ) FROM Equipment INNER JOIN EquipmentDesignation_Vw ...
-2
votes
3answers
81 views

Can a `Select` Subquery be conditionally returned? [closed]

Is it possible in Postgres to return a column(Resulting from a subquery) only when a condition matches? Query: SELECT (SELECT NOW()) AS FIRST, (SELECT NOW()) AS SECOND Outputs: | first | ...
0
votes
2answers
40 views

Select/print data from subquery

In my application I have a table "user", a table "role", and a table "userroles". Userroles is simple table consisting of user, role, where user corresponds to the id column of the user table. As user ...
0
votes
1answer
19 views

Is there a way to alias columns for reference in subqueries?

I have a SQL statement in PostgreSQL that takes the following form: SELECT * FROM db WHERE (b + 1) IN (SELECT b FROM db WHERE a = 7) This query returns each record whose b value, incremented by 1, ...
1
vote
2answers
159 views

MYSQL Update data based on top 10 records of each user

I have a table users and other table user_scores. In user_scores, I save daily score of every user based on a algorithm. Now I want to calculate AVG user_score by only considering latest 10 records of ...
0
votes
1answer
107 views

How do I count and order by unique entries?

I have this: SELECT tblClient.[Printed Name], tblClient.[Address 1] , tblClient.[Address 2], tblClient.City, tblClient.State , tblClient.Zip, tblClient.Phone, tblClient.[Email Address] FROM ...
5
votes
1answer
501 views

Storing prices with price history and different specificity (global, user group, single user) in MySQL database

I need to store prices with their history. A price can have different specificity. It can refer to a single user (most specific), group (less specific) and product price (global - least specific). ...
0
votes
2answers
930 views

Slow mysql query full text search tag database

In the database are ~700k images. Each image has its own tag(s). I want to be able to search images by the tags with a full text search query. The query does exactly what I want but it's very slow. ...
0
votes
1answer
17 views

How to rank an aggregation in each newly formed group?

The problem below that I would like to solve sounds quite simple but it is quite difficult for me to arrive at the solution with SQL. Let's say I have a simplified ERD that looks as follows: This ...
1
vote
2answers
6k views

How to access row value from UPDATE sub query function?

I would need to use UPDATE like this: update offer set (bank, bank_id) = (cost, gid) from ( select cost, osm_points.gid from pgr_kdijkstraCost( 'SELECT gid as id, source, target, walk_cost as cost ...
6
votes
2answers
89 views

Changes access method for non-correlated subquery

Oracle 11g R2 Unfortunately our application has per row security "features". We have a query that looks about like this: Bad, slow: SELECT someRow, someOtherRow FROM bigTableA a WHERE EXISTS ( ...
1
vote
1answer
4k views

Alternate to use LIMIT in subquery in mysql?

I have 2 tables, Resource and views and I'm trying to get the list of all the items from Resource table whose ran_resId don't match with the ran_resId of last 2 records of views table. I'm trying to ...
0
votes
1answer
154 views

Subquery or Inner Join?

I have this simple query that finds all transactions from accounts belonging to a specific login, with some extra conditions on the transactions. SELECT t.id, t.date, t.amount, t.description FROM ...
0
votes
1answer
249 views

Query to find products with all the given attributes

I have a table in mySQL to store product attributes like this: ------------------------------------ | product_id | att_val1 | att_val2 | ------------------------------------ | 1001001 | x202 | ...
1
vote
2answers
92 views

Help combining two MySQL queries to improve performance

I have two MySQL queries. The first one returns a list of codes, which comprise either one or two letters (e.g. "AB", "WO", "G"). This is the query: SELECT d.field_id_105 AS code, title FROM ...
0
votes
1answer
24 views

How to use query result as REPLACE parameters

i'm trying to: 1- Find a string inside a lot of content 2- Replace that specific part of the string with a new one using REPLACE function like this: REPLACE(column_name, query#1, query#2) Is this ...
-1
votes
2answers
36 views

How to get column values in where condition in sub query? [closed]

I am trying to get distinct list of values in where condition through sub query but it shows 0 rows in result set. Here is my query. SELECT a.topic_id, t.id as topicid, t.value as value, t.topic as ...
24
votes
7answers
108k views

Get multiple columns from a select subquery

SELECT *, p.name AS name, p.image, p.price, ( SELECT ps.price FROM product_special ps WHERE p.id = ps.id AND ps.date < NOW() ORDER BY ps....
0
votes
0answers
30 views

Two left joins then two on statements [duplicate]

I stumbled upon a left join function that is throwing me off... I was trying to eliminate a subquery or using another temp table. Both of the following queries produce the exact same values. SELECT * ...
0
votes
0answers
84 views

Subquery caching in join

I have very complex MySQL queries that use the same subquery over and over again. I was wondering if MySQL will run the subquery multiple times or use the previous resultset. Is there any way to tell ...
0
votes
1answer
39 views

Query to get the physical file name of the database

Im trying to get the physical file name of a database, and when i query sys.database_files, under the physical file name column, you get the whole path (ie. S:\Program Files\Microsoft SQL Server\...
0
votes
0answers
21 views

Postresql using subquery select in order by clause

Is it possible to order by a selected columnname? SELECT * FROM tablex ORDER BY quote_ident(( select column_name from information_schema.columns where table_name = tablex AND column_name LIKE '...