While working on a system I’m creating, I attempted to use the following query in my project:
SELECT
topics.id,
topics.name,
topics.post_count,
topics.view_count,
COUNT( posts.solved_post ) AS solved_post,
(SELECT users.username AS posted_by,
users.id AS posted_by_id
FROM users
WHERE users.id = posts.posted_by)
FROM topics
LEFT OUTER JOIN posts ON posts.topic_id = topics.id
WHERE topics.cat_id = :cat
GROUP BY topics.id
«:cat» is bound by my PHP code as I’m using PDO. 2 is a valid value for «:cat».
That query though gives me an error: «#1241 — Operand should contain 1 column(s)»
What stumps me is that I would think that this query would work no problem. Selecting columns, then selecting two more from another table, and continuing on from there. I just can’t figure out what the problem is.
Is there a simple fix to this, or another way to write my query?
Bill Karwin
535k85 gold badges665 silver badges824 bronze badges
asked Dec 26, 2012 at 22:08
Your subquery is selecting two columns, while you are using it to project one column (as part of the outer SELECT
clause). You can only select one column from such a query in this context.
Consider joining to the users
table instead; this will give you more flexibility when selecting what columns you want from users
.
SELECT
topics.id,
topics.name,
topics.post_count,
topics.view_count,
COUNT( posts.solved_post ) AS solved_post,
users.username AS posted_by,
users.id AS posted_by_id
FROM topics
LEFT OUTER JOIN posts ON posts.topic_id = topics.id
LEFT OUTER JOIN users ON users.id = posts.posted_by
WHERE topics.cat_id = :cat
GROUP BY topics.id
answered Dec 26, 2012 at 22:10
cdhowiecdhowie
157k24 gold badges285 silver badges299 bronze badges
3
In my case, the problem was that I sorrounded my columns selection with parenthesis by mistake:
SELECT (p.column1, p.column2, p.column3) FROM table1 p WHERE p.column1 = 1;
And has to be:
SELECT p.column1, p.column2, p.column3 FROM table1 p WHERE p.column1 = 1;
Sounds silly, but it was causing this error and it took some time to figure it out.
answered Sep 7, 2020 at 15:15
Mauro BilottiMauro Bilotti
5,5294 gold badges43 silver badges63 bronze badges
3
This error can also occur if you accidentally use commas instead of AND
in the ON
clause of a JOIN
:
JOIN joined_table ON (joined_table.column = table.column, joined_table.column2 = table.column2)
^
should be AND, not a comma
answered Apr 1, 2016 at 6:29
silkfiresilkfire
24.4k15 gold badges82 silver badges103 bronze badges
1
This error can also occur if you accidentally use =
instead of IN
in the WHERE
clause:
FOR EXAMPLE:
WHERE product_id = (1,2,3);
Jin Kwon
19.9k14 gold badges109 silver badges179 bronze badges
answered May 26, 2017 at 9:43
2
COUNT( posts.solved_post ) AS solved_post,
(SELECT users.username AS posted_by,
users.id AS posted_by_id
FROM users
WHERE users.id = posts.posted_by)
Well, you can’t get multiple columns from one subquery like that. Luckily, the second column is already posts.posted_by
! So:
SELECT
topics.id,
topics.name,
topics.post_count,
topics.view_count,
posts.posted_by
COUNT( posts.solved_post ) AS solved_post,
(SELECT users.username AS posted_by_username
FROM users
WHERE users.id = posts.posted_by)
...
answered Dec 26, 2012 at 22:10
Ry-♦Ry-
217k55 gold badges459 silver badges475 bronze badges
I got this error while executing a MySQL script in an Intellij console, because of adding brackets in the wrong place:
WRONG:
SELECT user.id
FROM user
WHERE id IN (:ids); # Do not put brackets around list argument
RIGHT:
SELECT user.id
FROM user
WHERE id IN :ids; # No brackets is correct
answered Oct 15, 2020 at 13:28
Janac MeenaJanac Meena
3,13334 silver badges32 bronze badges
2
This error can also occur if you accidentally miss if
function name.
for example:
set v_filter_value = 100;
select
f_id,
f_sale_value
from
t_seller
where
f_id = 5
and (v_filter_value <> 0, f_sale_value = v_filter_value, true);
Got this problem when I missed putting if in the if
function!
answered Aug 21, 2019 at 13:04
Another place this error can happen in is assigning a value that has a comma outside of a string. For example:
SET totalvalue = (IFNULL(i.subtotal,0) + IFNULL(i.tax,0),0)
kgui
3,9955 gold badges41 silver badges53 bronze badges
answered Sep 12, 2018 at 19:50
iAndyiAndy
113 bronze badges
(SELECT users.username AS posted_by,
users.id AS posted_by_id
FROM users
WHERE users.id = posts.posted_by)
Here you using sub-query but this sub-query must return only one column.
Separate it otherwise it will shows error.
answered Dec 8, 2019 at 5:53
I also have the same issue in making a company database.
this is the code
SELECT FNAME,DNO FROM EMP
WHERE SALARY IN (SELECT MAX(SALARY), DNO
FROM EMP GROUP BY DNO);
Nathan
78911 silver badges20 bronze badges
answered Oct 1, 2022 at 13:39
I also had this error message using Dapper with MySQL. Example code below:
SELECT ColA, ColB, ColC
FROM Table
WHERE ColA IN (@listOfColumns);
The issue with the above code is Dapper will automatically add the brackets for
the @listOfColumns parameter substitution meaning the brackets in the snippet above will double wrap the list of columns causing the error.
answered Apr 12 at 5:46
The “operand should contain 1 column(s)” could appear if your subquery selects two columns where you should select only one. There are a lot of other causes of this error as well. This article contains the experts’ solutions with coding examples.
Keep reading this article to learn everything about “operand should contain 1 column(s)” error.
Contents
- Why You Are Getting the Operand Should Contain 1 Column(s) Error?
- – Subquery Selecting Two Columns
- – Typing Mistakes
- – Comma Outside of a String
- – Getting Error in Rails
- How To Fix the Error?
- – Subquery Returning Two Columns
- – Another Way of Solving the Issue
- – Typing Mistakes
- – Comma Outside of a String
- – Getting Error in Rails
- FAQs
- – What Is the Mysql Group by Statement?
- – What Is Mysql Join?
- – How Many Types of Mysql Join?
- Conclusion:
Why You Are Getting the Operand Should Contain 1 Column(s) Error?
There could be many reasons to appear this error. Let’s see some of the possible causes.
– Subquery Selecting Two Columns
If you are using to select only one column and your subquery is selecting two columns, this error can appear. So make sure your subquery is not selecting two columns, because this error can occur in this scenario. You can select only one column from the query.
– Typing Mistakes
If you accidentally used the commas instead of “AND” in the “ON” clause of a “JOIN,” or used ‘=’ instead of “IN” in the “WHERE” clause, or missing “IF” function name, or using a parenthesis mistakenly, you can get this error.
– Comma Outside of a String
Another cause of this error could be the presence of a comma outside of a string. If you are assigning a value that has a comma outside of a string, you might get to see this error.
– Getting Error in Rails
If you are using an active record in SQL and passing a single value as an array, it is okay. However, if you are passing multiple values as an array, you might get the operand should contain 1 column(s) error. You can not pass it as an array to user_id. This could be the cause of the error in your case.
How To Fix the Error?
We covered all the causes of the error. Let’s now find the solutions to those causes.
– Subquery Returning Two Columns
If you are sure that the leading cause of this error is that your subquery is selecting two columns, the best solution for you could be to use the “users” table instead of the subquery. The “users” table will allow you to select what columns you want from users with flexibility.
– Another Way of Solving the Issue
Suppose you have two tables named “members” and “cars.” Where the “member” table contains the “first_name” and the “country” of the people who have cars. While the “cars” table includes the “owners,” “models,” and “conditions.” Keep in mind that we are adding five owners of five cars. Here the “first_name” and the “owner” columns are related, so you would want to use the subquery to display the data from both.
SELECT ‘first_name’ AS ‘owner’,
(SELECT ‘models’, ‘condition’
FROM cars WHERE cars.owner = members.first_name)
FROM members;
Here the bad news is the above query is wrong. Because it will throw the error code like operand should contain 1 column(s). Here the MYSQL wants the subquery to return only one column, but the subquery returns more than one column. So to fix this MYSQL error, we need to create two subqueries so that each subquery can return only one value and the error can be avoided.
Create Two Subqueries as the Following Method.
SELECT ‘first_name’ AS ‘owner’,
(SELECT ‘models’
FROM cars WHERE cars.owner = member.first_name) AS ‘models’,
(SELECT ‘age’
FROM cars WHERE cars.owner = members.first_name) AS ‘condition’
FROM members;
The above query is correct, but here is another bad news: now the subquery is returning more than one row because we added five owners of five cars. Hence, to avoid that error, let’s add one owner’s name with the car to the car’s table. The subquery will return the “model” and “condition” row for the newly added owner. And here, another error occurred.
So to fix all the errors, now we need to use the “JOIN” class instead of the subqueries. Keep in mind that you can only do this when you need to select data from one table, but you also need another table to filter the result. If you would have some owner’s name in the “cars” table that was not mentioned in the “members” table, then you should have used the subquery in the “WHERE” clause to display rows in the “cars” table that are also mentioned in the “members” table.
This is how you can use the subquery to avoid the operand should contain 1 column(s) error:
SELECT ‘owner’, ‘models,’ ‘age.’
FROM cars
WHERE ‘owner’ IN (SELECT ‘first_name’ FROM members);
But if you can’t use the subquery, this is how you can JOIN the table:
SELECT ‘owner’, ‘models,’ ‘condition.’
FROM cars JOIN members
ON cars.owner = members.first_name;
Both ways, you will get the same result and can avoid the operand should contain 1 column(s) error.
– Typing Mistakes
Make sure there is no typing mistake; if there is, correct it according to the syntax. Let’s see a few examples of the most common typing mistakes.
Examples of Some Typing Mistakes
JOIN joined_table ON (joined_table.column = table.column, joined_table.column2 = table.coumn2)
In the above example, the comma is placed between table.column and joined_table.column2 instead of “AND,” which is a mistake.
WHERE product_id = (4,5,6);
Here you can see that ‘=’ is mistakenly used instead of AND.
In the above example, you can see that brackets are used around the fields in the select clause, which is actually a mistake, and you are not following the correct syntax. In that case, you can get the operand should contain 1 column(s) error.
Also, ensure that you don’t use the parenthesis around column selection. This mistake is widespread in some beginner developers; they often write like this:
SELECT (p.column1, p.column2, p.column3) FROM table1 p WHERE p.column1 = 1;
The above line is the incorrect way of writing SELECT clauses where the correct way is as follows
SELECT p.column1, p.column2, p.column3 FROM table1 p WHERE p.column1 = 1;
– Comma Outside of a String
If the cause of this error is the presence of a comma in your case, then you should follow the correct syntax as follows.
SET totalvalue = (IFNULL(i.subtotal,0) + IFNULL(i.tax,0),0)
– Getting Error in Rails
If you need to pass the multiple values, make sure you pass a list of strings.
FAQs
– What Is the Mysql Group by Statement?
The operand should contain 1 column(s) GROUP BY statement in MYSQL groups the rows into summary rows of the same values. The GROUP BY statement is mostly used with the function like (COUNT(), MAX(), MIN(), SUM(), AVG()). The GROUP BY groups the result-set of these functions by one or more columns.
– What Is Mysql Join?
The MYSQL JOIN retrieves data from different tables when more than one table is joined in the SQL statement.
– How Many Types of Mysql Join?
There are multiple types of MYSQL JOINs:
-
Mysql Inner Join
This type of JOIN is the most common type of join called the simple join. This JOIN returns all rows from multiple tables where more than one table is joined, and the join condition is met. This JOIN returns the result where all the tables intersect. The syntax of the MYSQL INNER JOIN is as follows:
SELECT columns
FROM table1
INNER JOIN table2
ON table1.column = table2.column;
-
Mysql Left Outer Join
The MYSQL LEFT OUTER JOIN, also known as LEFT JOIN, is used to return all the rows from the table on the left and only those rows from the other table where the join condition is met. As a result, you will get all the records of the table only those records of table two that intersect with table one. The syntax of the LEFT OUTER JOIN is as follows:
SELECT columns
FRO table1
LEFT [OUTER] JOIN table2
ON table1.column = table2.column;
-
Mysql Right Outer Join
The MYSQL RIGHT OUTER JOIN, also known as RIGHT JOIN, returns all the rows of the right table and only those rows from the other table where the join condition is met. As a result, you will get all the records from the right table and only those from the left table that intersect the record of the right table. The syntax of this type of JOIN is as follows:
SELECT orders.order_id, orders.order_date, suppliers.supplier_name
FROM suppliers
RIGHT JOIN ordersx`
ON suppliers.supplier_id = order.supplier_id;
Conclusion:
Let’s understand what we learned today:
- There could be many causes of the operand should contain 1 column(s) error, but the major reasons could be the subquery returning more than one column or any typing mistake.
- If the subquery is returning more than one column in your case, try using the USERS table to avoid this error.
- You can also use Subquery in the WHERE clause to display the rows of one table but mentioned in the other table.
- You can also use the JOIN class, but remember that you can only use this when you need to select data from one table and use the other table to filter that data.
- If you find any typing mistakes that lead you to face the error, correct that mistake by using the correct syntax.
We covered all the causes of the operand should contain 1 column(s) error. We understood why this error appeared, and we fingered out two primary reasons; the subquery returning more than two columns or typing mistake. If you be a little careful about these mistakes and avoid them, you won’t see this error. If you ever get the same error, you can use this article as a solution guide to that error.
- Author
- Recent Posts
Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL. Meet The Team
The error Operand should contain 1 column(s)
is most likely caused by a subquery that’s returning more than one column.
Here’s a typical SELECT
query that causes this error:
SELECT column_one,
(SELECT column_two, column_three FROM table_two)
FROM table_one;
The above subquery returns column_two
and column_three
, so MySQL throws the Operand should contain 1 column(s)
error.
Most often, you only need to check your subquery and make sure that it returns only one column.
If you need more guidance on how to fix this MySQL error, then you may read the next section.
How to fix Operand should contain 1 column(s) error
To illustrate an example, imagine you have two tables that have related data named members
and pets
.
The members
table contain the first_name
of people who have pets as shown below:
+----+------------+----------------+
| id | first_name | country |
+----+------------+----------------+
| 1 | Jessie | United States |
| 2 | Ann | Canada |
| 3 | Joe | Japan |
| 4 | Mark | United Kingdom |
| 5 | Peter | Canada |
+----+------------+----------------+
While the pets
table contain the owner
and the species
column as follows:
+----+--------+---------+------+
| id | owner | species | age |
+----+--------+---------+------+
| 1 | Jessie | bird | 2 |
| 2 | Ann | duck | 3 |
| 3 | Joe | horse | 4 |
| 4 | Mark | dog | 4 |
| 5 | Peter | dog | 5 |
+----+--------+---------+------+
The first_name
and the owner
columns are related, so you may use a subquery to display data from both tables like this:
SELECT `first_name` AS `owner_name`,
(SELECT `species`, `age`
FROM pets WHERE pets.owner = members.first_name)
FROM members;
However, the above SQL query is wrong, and it will throw an error like this:
ERROR 1241 (21000): Operand should contain 1 column(s)
This is because MySQL expects the subquery to return only one column, but the above subquery returns two.
To fix the error, you may create two subqueries with each subquery returning only one column as in the following SELECT
statement:
SELECT `first_name` AS `owner_name`,
(SELECT `species`
FROM pets WHERE pets.owner = members.first_name) AS `species`,
(SELECT `age`
FROM pets WHERE pets.owner = members.first_name) AS `age`
FROM members;
While the above query works, it will throw another error once the subquery returns more than one row.
Let’s add another pet that’s owned by “Jessie” to the pets
table as shown below:
+----+--------+---------+------+
| id | owner | species | age |
+----+--------+---------+------+
| 1 | Jessie | bird | 2 |
| 2 | Ann | duck | 3 |
| 3 | Joe | horse | 4 |
| 4 | Mark | dog | 4 |
| 5 | Peter | dog | 5 |
| 6 | Jessie | cat | 4 |
+----+--------+---------+------+
Now the subqueries will return two species
and age
rows for “Jessie”, causing another related error:
mysql> SELECT `first_name` AS `owner_name`,
-> (SELECT `species`
-> FROM pets WHERE pets.owner = members.first_name)
-> FROM members;
ERROR 1242 (21000): Subquery returns more than 1 row
To properly fix the error, you need to replace the subquery with a JOIN
clause:
SELECT `first_name` AS `owner_name`, `species`, `age`
FROM members JOIN pets
ON members.first_name = pets.owner;
Subqueries can be used to replace JOIN
clauses only when you need to SELECT
data from one table, but you need to filter the result by another table column.
For example, maybe you have some owner names in the pets
table that aren’t recorded in the members
table. You can use a subquery in the WHERE
clause to display rows in the pets
table that are also recorded in the members
table.
Here’s an example of using a subquery in the WHERE
clause:
SELECT `owner`, `species`, `age`
FROM pets
WHERE `owner` IN (SELECT `first_name` FROM members);
Without using a subquery, you need to JOIN the table as shown below:
SELECT `owner`, `species`, `age`
FROM pets JOIN members
ON pets.owner = members.first_name;
The two queries above will produce the same result set.
And that’s how you can fix the Operand should contain 1 column(s)
error in MySQL.
You need to check your subquery before anything else when you encounter this error.
Всем привет! Выходит это ошибка при вставке в таблицу данные.
Этот же код нормально работает для триггера Before Update, а для Before Insert выдает ошибку, типа много чем одной строки как я понял.
Вот мой код:
DROP TRIGGER IF EXISTS `InsertBuildingAnalysis`;
CREATE TRIGGER `InsertBuildingAnalysis` BEFORE INSERT ON `MDepartments` FOR EACH ROW BEGIN
DECLARE population INT;
DECLARE normative, isnornamtive INT;
DECLARE locality VARCHAR(1256);
DECLARE loc_dis_id int;
DECLARE loc_isCenter int;
DECLARE sub_pop int;
DECLARE sub_cpop int;
DECLARE dis_pop int;
SET population = (SELECT new_fnc(new.ParentId));
SET locality = (SELECT * FROM Localities WHERE Localities.Id = new.LocalityId);
SET loc_dis_id = (SELECT Localities.DistrictId FROM Localities WHERE Localities.Id = new.LocalityId);
SET loc_isCenter = (SELECT Localities.IsCenter from Localities WHERE Localities.Id = new.LocalityId);
SET sub_pop = (SELECT new_fnc2(new.SubRegionId));
SET sub_cpop = (SELECT new_fnc3(new.SubRegionId));
SET dis_pop = (SELECT new_fnc4(loc_dis_id));
IF (new.TypeId = 4 ) THEN
IF (population < 50) THEN
SET new.Normative = 0;
SET new.IsNormativePositive = 1;
ELSEIF (population > 8000) THEN
SET new.Normative = 0;
SET new.IsNormativePositive = 0;
ELSE
SET new.Normative = 1;
END IF;
ELSEIF (new.TypeId = 3) THEN
IF (population < 800) THEN
SET new.Normative = 1;
SET new.IsNormativePositive = 1;
ELSEIF (population > 2000) THEN
SET new.Normative = 0;
SET new.IsNormativePositive = 0;
ELSE
SET new.Normative = 1;
END IF ;
ELSEIF (new.TypeId = 2) THEN
IF (population > 800 && population <= 2000) THEN
SET new.Normative = 2;
ELSEIF (population > 2000 ) THEN
SET new.Normative = 1;
ELSE
SET new.Normative = 0;
SET new.IsNormativePositive = 1;
END IF;
ELSEIF (new.TypeId = 57) THEN
IF(population < 10000) THEN
SET new.Normative = 0;
SET new.IsNormativePositive = 1;
ELSE
SET new.Normative = 1;
END IF;
ELSEIF (new.TypeId = 26)THEN
IF (!locality) THEN
SET new.Normative = -1;
ELSEIF (loc_isCenter != 1) THEN
SET new.Normative = -2;
ELSE
SET new.Normative = 1;
END IF;
ELSEIF (new.TypeId = 35) THEN
SET population = sub_pop + sub_cpop;
IF(population >= 100000) THEN
SET new.Normative = 1;
ELSE
SET new.Normative = 0;
SET new.IsNormativePositive = 1;
END IF;
ELSEIF (new.TypeId = 27) THEN
SET population = dis_pop;
IF(population > 5000) THEN
SET new.Normative = 1;
ELSE
SET new.Normative = 0;
SET new.IsNormativePositive = 1;
END IF;
ELSEIF (new.TypeId = 25) THEN
SET new.Normative = 1;
END IF;
END;
Не знаю как исправить! Ваши варианты пож-а!
You cannot have multiple columns being returned in a subquery like that, so you have several ways that you would have rewrite this query to work.
Either you can unpivot the data in the team
table so you are only returning one column:
select *
from players
where sport='football'
and position='DEF'
and pname!='Binoy Dalal'
and pname not in (select player1
from team where sap='60003100009'
union all
select player2
from team where sap='60003100009'
union all
select player3
from team where sap='60003100009'
union all
select player4
from team where sap='60003100009'
union all
select player5
from team where sap='60003100009'
union all
select player6
from team where sap='60003100009'
union all
select player7
from team where sap='60003100009'
union all
select player8
from team where sap='60003100009')
order by price desc;
Or you can use a NOT EXISTS
query:
select *
from players p
where sport='football'
and position='DEF'
and pname!='Binoy Dalal'
and not exists (select *
from team t
where sap='60003100009'
AND
(
p.pname = t.player1 OR
p.pname = t.player2 OR
p.pname = t.player3 OR
p.pname = t.player4 OR
p.pname = t.player5 OR
p.pname = t.player6 OR
p.pname = t.player7 OR
p.pname = t.player8
))
order by price desc;
Or you would have to use multiple WHERE
filters on the player name:
select *
from players
where sport='football'
and position='DEF'
and pname!='Binoy Dalal'
and pname not in (select player1
from team where sap='60003100009')
and pname not in (select player2
from team where sap='60003100009')
and pname not in (select player3
from team where sap='60003100009')
and pname not in (select player4
from team where sap='60003100009')
and pname not in (select player5
from team where sap='60003100009')
and pname not in (select player6
from team where sap='60003100009')
and pname not in (select player7
from team where sap='60003100009')
and pname not in (select player8
from team where sap='60003100009')
order by price desc;
However, ideally you should consider normalizing the team
table so you have one column with the player name and another column that assigns them a player number. Similar to this:
create table team
(
player varchar(50),
playerNumber int
);
Then when you are searching the team data you only have to join on one column instead of 8 different columns.