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
2 votes
3 answers
609 views

How can I get an average from a query dataset in SQL Server?

I am building a parts inventory system, and have a transaction table that stores how often an item in used. Let's say Item A is used 10 times in 2021, 20 in 2022, and 30 in 2023. Of course each ...
Viper75's user avatar
  • 21
1 vote
2 answers
47 views

Query to return latest record between 2 tables

I'm trying to pull the most current date (cusPurDt) and corresponding amount (subAmt) by customer (cusID/subID). Here is some sample data: create table customer ( cusID char(5), cusPurDt ...
tkmagnet's user avatar
2 votes
1 answer
46 views

Query for single return meeting multiple criteria and values

I'm trying to figure out a way to count an ID once when multiple criteria are met in one column while displaying a total of the same criteria in another column. The criteria for the first column can ...
tkmagnet's user avatar
1 vote
1 answer
18 views

In MS Studio how to SELECT from an existing SQL file

I have a complicated query that select parts from an MRP table using several different criteria. The output of the query is a list of parts which includes the key field [PartNum]. I have saved this ...
TonyG614's user avatar
1 vote
1 answer
33 views

MySQL Tennis Ladder View Creation Question

I am creating a Tennis Ladder VIEW using MySQL and wish to do the following: Properly create a view that includes: All player's names These player names will come from the table: User - using the ...
Reno Kendo's user avatar
0 votes
0 answers
30 views

How to use a parameter derived from a Table, given I'm filtering the table in query

The task is to find what fraction of total users have logged in at least for one more consecutive day after their first login. SELECT ROUND( COUNT( b.player_id )/COUNT( DISTINCT (SELECT a....
Pixel_Bear's user avatar
-2 votes
3 answers
48 views

Query to find values based on a like and a not like

I have a column in a table: ID - this column can have a value of '123456' but can also have value '123456x'. I need to return all the numbers where there is an 'x' and the same number but without an '...
Daniel Blake's user avatar
0 votes
1 answer
47 views

Efficient PostgreSQL query syntax for duplicating the result

Assuming I have the following PostgreSQL query: SELECT ( SELECT SUM (t.customers) FILTER ( WHERE id = 1 AND date BETWEEN %(start)s AND %(stop)s ...
jvkloc's user avatar
  • 133
1 vote
0 answers
48 views

Inconsistent result when running same query on slightly distinct MariaDB versions

I'm investigating the difference in the results given by the same SQL query on two servers running slightly different versions of MariaDB (10.5 and 10.11). Test query is: SELECT a.Name FROM Artist a ...
joanq's user avatar
  • 111
1 vote
2 answers
59 views

Is there a "correct" way for an optimizer to process a subquery if the outer query has additional where filters?

This topic came up for me as the result of investigating an error in Redshift. We have a table containing a column of numbers represented as text, but for rows where no value is present a single ...
MattB's user avatar
  • 111
0 votes
2 answers
65 views

How do I optimize this query that gets the newest entry of each group?

I have a query, that finds the newest item of each group based on the ID returned by a subquery. The problem is, that the table has a bit over 5000 entries and even with only this amount of entries ...
nyoatype's user avatar
0 votes
1 answer
79 views

The most recent rows in for each type/agent

I have a table (still on MySQL 5.7) with lots of data. This table is written by some scripts. It works like a "checkin", where each agent is checking in in some period of time. It looks like ...
Marek's user avatar
  • 13
0 votes
1 answer
87 views

Calculate (n) workdays from a given date, using a calendar table

As shown on below image, I have two tables; Customer : with about 4 million records; and 3 columns [Customer] : Customer ID [Date] : Creation date [Num_Days] : Number of working days to calculate ...
LEOPOLDO's user avatar
1 vote
1 answer
195 views

Query for repeating sequences in SQLite

I have an SQLite DB, let's assume the id can be considered as the order of rows, I want to find repeating sequences in the table according to certain criteria. consider this example (http://sqlfiddle....
yossico's user avatar
  • 167
1 vote
0 answers
19 views

postgresql sub query

I have three tables kit - contains kit_id and kit_type (kit type is with android or IOS) appointment - contains appointment_id, created_datetime, kid_id, created_by_id user - contains user_id, user ...
Stephen 's user avatar
-3 votes
1 answer
109 views

subquery vs join which is better [closed]

SELECT * FROM table1 WHERE t2id in ( SELECT id FROM table2 WHERE t3id = (SELECT id FROM table3 WHERE id = '1') ); SELECT * ...
guradio's user avatar
  • 97
1 vote
1 answer
473 views

Return Subquery with Multiple Columns as JSON Array of JSON Objects

In my setup, the relevant tables for this problem are: Items Users Collections (of Items) — each user can have multiple Collection Items — where I track what items are in each collection. The items ...
psygo's user avatar
  • 121
0 votes
1 answer
63 views

Why the following first of two queries in MSSQL is faster as I want the second one?

1st Query: result 32 seconds (1,758,220 rows) SELECT CAST(ID.PYYY AS varchar(8))+','+ CAST(ID.SYYY AS varchar(8))+','+ ( SELECT TOP 1 ( CAST(IMM.INVOICE_DATE1 AS varchar(8))+','+ CAST(...
mesutuk's user avatar
  • 101
1 vote
1 answer
279 views

How to update a foreign key with random values from the referenced table?

In order to generate test data for a postgres database, I want to update a foreign key in a table, let's say 'users' with random values from the referenced table, let's say 'shift'. How to do it? I ...
Edilson Vieira's user avatar
0 votes
0 answers
17 views

Why SQL subquery returns no error on trying to select not existing column? [duplicate]

I use PostgreSQL 15 and have two tables: table 1 has only one column id1 (pkey) and has 6 rows (values 1-6) table 2 has only one column id2 (pkey) and has 6 rows with some another values Then I try ...
Denis's user avatar
  • 1
0 votes
0 answers
21 views

Query that accesses 2 feilds of document in collection

I have a users collection of documents containing fields city_name, and income. How can I write a query which gives me the documents data of the top 10 cities which have the highest number of users ...
Frecoder's user avatar
0 votes
1 answer
65 views

Compose a complex query in Postgresql

I have a huge table like following: CREATE TABLE public.huge_table ( sampl_day date NOT NULL, tick_time timestamp(6) with time zone NOT NULL, crit_feat integer NOT NULL, --- --- ...
Leon's user avatar
  • 347
1 vote
1 answer
229 views

How to return list of content from subquery for the main query?

I have a create that have sub query. To show as example, here is a query that has similarity with my own. Personally I have more table and more arguments on table (The subquery have left join for ...
Elikill58's user avatar
  • 213
3 votes
1 answer
8k views

postgres - copy values from one column to another column (same table)

I want to copy the entire content from one column to another (same datatype) and thought of a subselect to be part of the equasion. UPDATE tab01 SET column2=(SELECT column1 FROM tab01); ERROR: ...
vrms's user avatar
  • 185
1 vote
0 answers
22 views

query customer retention over range

I am trying to find the best way to accomplish the following. Get the beginning customer count, which carries from the previous day Get New Customer count Get the number of Customers who have not ...
thedemon's user avatar
  • 111
1 vote
2 answers
90 views

MySQL with subquery becomes slow

I have 3 MySQL tables: products, orders and users. I want to show all ordered products where not all products are "pre-orders" or "discounts". Note: one user can have multiple ...
screaming SiLENCE's user avatar
1 vote
1 answer
113 views

Combining Multiple queries from the same table inrto 1 query

I am looking to find a way to achieve the below... I have tried using Joins and SubQueries but no joy as yet... I have a table that keeps track of wins/loses/draws as so Date WLD 01/01/23 Win 05/01/...
Paulmcf1987's user avatar
0 votes
2 answers
97 views

Using a WHERE colname NOT LIKE (select * from otherTable)

So in essence what im trying to do is this: Given TBL1 (around 8,000 rows) letters abababa bcbcbcb cdcdcdc and TBL2 (around 2,000 rows) letters ab bc I want to write a query to find every row ...
Shahzad Ansari's user avatar
0 votes
1 answer
265 views

Join result of crosstab to main query

I'm trying to get this column structure: | id | name | main_image | rating | shop_names | prices | urls | 2 | 3 | My table structure looks like this CREATE TABLE products ( id SERIAL PRIMARY KEY, ...
broken_cursor's user avatar
3 votes
3 answers
7k views

"ERROR: column "a" does not exist" when referencing column alias

I am attempting to retrieve either a null or boolean value from a query. Here is my query: SELECT EXISTS (SELECT 1 FROM employee where add_uuid = '7e53fa47-ade3-4e94-8efd-b25f998b09c6') ...
Aamir's user avatar
  • 133
1 vote
1 answer
321 views

Parallel index-only scan with two sub-queries is slow

I'm trying to analyze a slow query that uses parallel index-only scan of two filters (using sub-queries). Specifically I'm the number of 'open_questions' that returned by either subplan1 OR subplan2. ...
Cowabunga's user avatar
  • 135
0 votes
2 answers
47 views

I have a database with a player, tournament, and registration table. I need to query all players that played in 2 types (attributes) of tournaments

I currently have two tournaments that have matches. Wimbledon and Atlanta open which I have one as a grand slam and the other as a masters 1000, and I want to get the players who played in both This ...
zaria palmer's user avatar
2 votes
2 answers
77 views

DB2 query not working

Customer (parent table) Id Charge Amt C1 10 C2 20 C3 30 C4 40 Payment (child table) Id pymt amt C1 10 C2 5 C4 40 Select Id and pending balance from customer and payment tables Pending ...
user2215220's user avatar
1 vote
1 answer
134 views

DIV and GROUP by issues

I have one query, made it in MySQL. And now try to run on PostgreSQL, but get syntax error twice. Once on the DIV command, and then on the GROUP BY. Here is my code: UPDATE status_table SET Status_CG ...
Database_operator's user avatar
2 votes
1 answer
69 views

How to calculate latlong difference from last 15 min ago and last 1 min ago without using correlation subqueries

Problem I would like to find logs that are active and do not hit a distance quota of 12.5km, comparing from last 15 min ago and latest (within last 1 min ago) Sample data select version(); version() ...
bik555's user avatar
  • 79
0 votes
1 answer
401 views

How do I filter a set of child records to get a single child record for each parent? [duplicate]

Sorry if it's a simple question but I can't wrap my head around it. I have two tables, users and carts. For each user record I need to get it's most recent cart (ordered by created_at desc). I've ...
pinkfloyd90's user avatar
0 votes
1 answer
100 views

optimization with subquery not working as expected

I have a MySQL InnoDB database. One table called affymetrixProbeset contains more than 300 million rows. Querying this table with INNER JOIN to other tables, with an ORDER BY and offset/limit takes ...
jwollbrett's user avatar
0 votes
2 answers
557 views

Postgres sort results by id's from subquery

In postgres 11 im implementing something in type of suggesting new tag for user. To achieve that im first counting amount of activities of specific user in specific category. Query looks as follows ...
LSM2236's user avatar
  • 15
0 votes
0 answers
62 views

How to subquery and FULL Join onto the same table

I have a SQL Table with alot of Team Names and Queries For Example: I want to do a FULL JOIN to compare the Red Team and Blue Team Only to see who is in Red, in Blue, or in Both. To Get Something ...
user1207381's user avatar
1 vote
1 answer
485 views

How to GROUP BY boolean when im already grouping by time frames 8hr/11hr/14hr/17hr/20hr in MySQL

I need to group 2 tables (Key = analysis_id <=> id) where my output should show the last week or month or year, grouped by a Time frame and grouped by bolean "R" or "L". I ...
Rollo's user avatar
  • 29
0 votes
0 answers
24 views

Mysql Query need to optimize

I have below query having proper indexes (all columns in where clause), But still query is very slow. Can anyone help me to optimize this mysql query? SELECT centerID, compID, ...
Madhura's user avatar
0 votes
1 answer
242 views

How to group by week/month/year and time frame 8hr/11hr/14hr/17hr/20hr in MySQL

I need to group 2 tables (Key = analysis_id <=> id) where my output should show the last week or month or year, grouped by a Time range. I have around 4000 inputs from users. Example of tables ...
Rollo's user avatar
  • 29
0 votes
1 answer
669 views

Why cannot I reference the second alias from a subquery containing a UNION?

Why cannot I use Qty2 as an alias in my query? I receive this error: Error Code: 1054. Unknown column 'qty2' in 'field list' SELECT mat, qty, qty2, SUM(qty), (ifnull(SUM(qty - qty2),0)) as TotalQty ...
Paul Haro's user avatar
4 votes
1 answer
370 views

Concurrent update on two different tables fail

I'm using PostgreSQL with the following database schema: CREATE TABLE plans ( slug VARCHAR(500) PRIMARY KEY ); CREATE TABLE users ( id VARCHAR(16) PRIMARY KEY, org_id VARCHAR(16) NOT NULL ...
Valentin Nasraty's user avatar
0 votes
0 answers
330 views

MySQL query: multiple select with different conditions and LIMIT for each, but also LIMIT whole query + paginator friendly

I would like to write SQL query (for MySQL) that is able to SELECT x rows by condition1 from table1 y rows by condition2 from table1+join1 z rows by condition3 from table1+join2 But on every page (...
Nick's user avatar
  • 1
-2 votes
1 answer
22 views

Extracting data from two tables

I have( for example) a table called A and a table called B. Table A contains tons of user data( age, country bla bla) and is connected to B by forein_key=id( B only has ID/NAME. I want to find out how ...
Gal Mor's user avatar
0 votes
0 answers
109 views

Is the use of a dependent subquery justified in this case?

SELECT a.id, (SELECT ARRAY( SELECT c.id FROM table_c c JOIN table_d d ON d.id = c.id JOIN table_e e ON e.id = d.id WHERE a_id = a.id AND ...
Don Draper's user avatar
0 votes
2 answers
824 views

How to Select The Lowest Date in one field that's higher than the date in another field

The below aim isn't actually what my query is for, but I'm using it as an analogy to explain more simply what I am trying to achieve: I am trying to build a BigQuery Script which looks at all arcade ...
Phil Tomlinson's user avatar
0 votes
1 answer
234 views

Doesn't T-SQL support correlated CROSS JOINs?

This query works SELECT QMC.HAUSKEY, t1.STRNAME, t2.HAUS_NR FROM SWOPS.MIGR.QMCAddresses QMC CROSS JOIN (SELECT STRNAME FROM SWOPS.MIGR.EB_DICT_STREET_QMC WHERE FK=8055909) t1 CROSS JOIN ...
Mediterrano's user avatar
2 votes
2 answers
133 views

SELECT groups by individual members AND sum other values

Using MySqL 5.7.34 and having a table, groups_members, with 4 columns ID group member organization 1 A Bob Apple 2 A Susan Apple 3 A Joe Apple 4 B Steve Microsoft 5 B Mike Microsoft 6 B Bob ...
Jonathon Doesen's user avatar

1
2 3 4 5
15