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.
523
questions
1
vote
2answers
21 views
How to get sum of 3 sub count queries and group them using an attribute
I have 3 queries as follows:
For the date 2019-12-02, I am calculating 3 type of values. The total value for 2019-12-02 must be the sum of these 3 queries.
Q1
SELECT count(*)
FROM ...
1
vote
2answers
22 views
Column not like any value in column in other table - function
The two tables in question are:
completed_types
id | type
---|--------
1 | XXX
2 | YYY
all_types:
id | type | sub_type
---|-------|---------
1 | XXX X | aaa
2 | XXX-Y | bbb
3 | YYY-X | ccc
4 ...
2
votes
2answers
32 views
Postgresql expanding view multiple times instead of executing it once
I have a rahter long subquery which I store as a view
CREATE VIEW scans_minmax AS
SELECT tmp.source,
value ->> 'Ok' AS "Ok",
...
0
votes
1answer
29 views
select subquery condition in where statement
I am getting this error:
ORA-06550: line 43, column 16: ORA-00904: "STOCK_BALANCE": invalid identifier
...for the following query:
select PARTY_ID,
PARTY_NAME,
IT_ID,
IT_ID ||...
0
votes
1answer
31 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
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
37 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
35 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 ...
0
votes
1answer
56 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
0answers
19 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
478 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 ...
0
votes
1answer
57 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(*) ...
0
votes
1answer
62 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
1answer
337 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
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
2answers
41 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
95 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
1answer
41 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
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, ...
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
votes
2answers
37 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 ...
0
votes
1answer
25 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 ...
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
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
22 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 '...
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 ...
1
vote
1answer
39 views
selecting data after filtering out
I am using RDBMS MySQL 5.7. I have 3 tables with the following structures:
Table A - primary table - products:
+----+-----------+-------------+------------+--------+
| id | title | description |...
0
votes
0answers
24 views
Finding matching sub values?
So not too sure how to go about this, but ideally I want to pull out matching & non-matching info from an array of rows in a table, so I have a table with info like this:
12,2019-07-15 06:02:52,...
0
votes
1answer
39 views
Problem with How to join with subquery
I'm trying to create a report in Postgresql that shows some columns from some tables with join. But one of them is subquery that to show a customer with the location. My Problem is, I always get ...
0
votes
1answer
40 views
Why last table don't using index for joining?
By the help of others members i get an Query idea for my previous problem. But after writing this, the EXPLAIN showing that my last table do't using index for join but the joining ROW is PRIMARY KEY, ...
0
votes
0answers
23 views
How can i remove filesort for this subqueires?
This is the Query:
SELECT
A.*
FROM
messages_thread_user mtu,
LATERAL (SELECT
m.*, u.userName
FROM
messages m
JOIN
...
0
votes
0answers
255 views
Sql subquery for nested parent child data
I have two tables , on parent table (categories ) and child table (features).. I have this query
select c.* ,
(select GROUP_CONCAT(f.featuresId , f.featuresTitle )
from ...
0
votes
1answer
21 views
MySQL - Optimize subquery in Select, where and order by
Im running a query like below.
SELECT DISTINCT c.`id`
, c.`job-cat`
, (
SELECT COUNT(*)
FROM `jobs` j
WHERE j.`mul_category` IN (c.`id`)
AND j.`ending` >...
0
votes
2answers
51 views
Postgres select using lateral
I'm after running a query with a subquery (perhaps inefficient) that using a regular expression pattern it can return how many instances of a characters are included with a given record.
In doing so, ...
0
votes
1answer
106 views
Query to Find Multiple Start Time and End Time on a Single Day based on Boolean Value
I want to find the multiple Start Time and End time in a single Day based on the Boolean value where data is divided into each half hour interval for a day. So Each day is divided into 24hrs/2 = 48. ...
0
votes
1answer
33 views
How do I create a table with count of instances of an id before an event date that is individual to that id?
I am very new to SQL and have a relatively complex query to write, any help would be appreciated.
I have data with the following columns:
ORDER_ID
CUST_ID
ORDER_DATE
RETURNED(1/0)
I need a table ...
0
votes
1answer
39 views
Slecting specific query returnned data related records from another table [closed]
Product table:
productId | productName | unitPrice | supplierId
_______________________________________________
1 | Iphone8 | 1500 | 3
2 | Nokia 6 | 800 | 1
...
4
votes
1answer
456 views
How to take make OFFSET & LIMIT with COUNT (OVER?) when having a subquery?
It appears I have a case I can't quite wrap my brains around. So coming here in hopes to find pointers to a query that maybe could be helpful to someone else too.
In the following, I have a query ...
1
vote
1answer
598 views
Limit left join for multiple rows
Since MySql doesn't support main alias reference in subquery is a bit challenging to create query with multiple rows where you have to limit rows of left join tables.
Let's overview simple example.
...
0
votes
1answer
28 views
Two aggregated sub queries wont run
I am having trouble with the below, I need to average two columns in a correlated subquery and I cannot get it to work, how do i get both aggregate sub queries to run then go through the outer query? ...
2
votes
2answers
62 views
What am I doing wrong with subquery
I cannot work this out, how do I get the subquery to return the lowest course weight for each lecturer, it currently only returns the lowest and is my subquery wrong or outer query?
Question: Show ...
3
votes
1answer
72 views
Why is an empty rowset not equivalent to null when assigning a query result to a variable and how best to work around?
I have a cursor. Within my loop I select a single column and assign the result to a variable. When the select returns an empty rowset, nothing is assigned to the variable. In particular, the variable ...
0
votes
1answer
76 views
Cannot get a user function to co-operate with a subquery in mariadb
The following is a demo of an issue we are having with a function and a subquery. I'm interested to know if it is a bug or if there is a reasonable explaination why it is failing.
Notes:
Problem ...
1
vote
1answer
235 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'...
2
votes
3answers
81 views
Return ALL rows based on a matching date also matching a specific value in another column
I'm using SQL Server 2014, exact version: 12.0.5579.0.
I've tried a subquery under a SELECT and WHERE statement and it brings back false results with rows of any row with a 1/1/2019 date. It just ...
0
votes
1answer
217 views
When to use lateral joins vs correlated subqueries in Postgres?
These two queries:
SELECT username, location, task, ts_next - ts AS diff
FROM (
SELECT username, location, task, ts, (
SELECT ts AS ts_next
FROM switches
...
0
votes
2answers
104 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 ...
-3
votes
1answer
59 views
Print Two Different Columns with Union All- SQL
I have an SQL statement like this,
SELECT *
FROM (select "John" as FirstName Union All select "Mary" Union All select "Alis"),
(select "Doe" as LastName union all select "Queen" union all ...