Looping through an array in SQL column - mysql

I have a SQL table that looks something like this:
| ID | Value |
| --- | ----------------------------------------------------- |
| 1 | {"name":"joe", "lastname":"doe", "age":"34"} |
| 2 | {"name":"jane", "lastname":"doe", "age":"29"} |
| 3 | {"name":"michael", "lastname":"dumplings", "age":"40"}|
How can I using SQL select function, select only the rows where "age" (in value column) is above 30?
Thank you.

The column Value as it is it contains valid JSON data.
You can use the function JSON_EXTRACT() to get the the age and convert it to a numeric value by adding 0:
SELECT *
FROM tablename
WHERE JSON_EXTRACT(Value, "$.age") + 0 > 30;
See the demo.

Related

How to loop through an array in SQL where clause?

I have a MySQL table which has the following columns and records:
| Name | Total | GivenBy |
| ---- | -------- | ------------ |
| Z | 200 |['A','B','C'] |
| X | 240 |['A','D','C'] |
I would like to extract Record No. 1 on the basis of 3rd column where the SQL query would be like:
SELECT * FROM mytable WHERE GivenBy='B';
Is there a way I can loop through the list in third column and take out the respective string as required in the SQL WHERE clause in a single query?
Please note that I cannot add more columns in the table.
If you can please provide the query as MySQL compatible, I would really appreciate it.
The "array" you show isn't quite valid JSON, but if you use double-quotes instead of single-quotes, you can use JSON_TABLE() to do this:
CREATE TABLE MyTable
(
Name CHAR(1) PRIMARY KEY,
Total INT NOT NULL,
GivenBy JSON NOT NULL
);
INSERT INTO MyTable VALUES
('Z', 200, '["A","B","C"]'),
('X', 240, '["A","D","C"]');
SELECT Name, Total, g.Value
FROM MyTable
CROSS JOIN JSON_TABLE(GivenBy, '$[*]' COLUMNS(Value CHAR(1) PATH '$')) AS g;
+------+-------+-------+
| name | total | value |
+------+-------+-------+
| X | 240 | A |
| X | 240 | D |
| X | 240 | C |
| Z | 200 | A |
| Z | 200 | B |
| Z | 200 | C |
+------+-------+-------+
But the best choice is not to store "arrays" in MySQL. Store the values one per row in a second table.
You can use the "like" keyword with regex to match your requirements in the third column.
select * from table where givenBy like "%B%";
Something similar would work.
You need to run a script:
Retrieve the list of unique values in the GivenBy column using the following query:
SELECT DISTINCT JSON_EXTRACT(GivenBy, '$[*]') AS GivenByValues
FROM mytable;
Loop through the list of unique values, and for each value, run a query that uses that value in the WHERE clause:
SELECT *
FROM mytable
WHERE JSON_SEARCH(GivenBy, 'one', [current_value_from_loop]) IS NOT NULL;

How do I remove .0 from a db table column?

I converted an Excel file into a SQL file. But, when I imported it into my database. It added .0 at the end of some values. The column type is varchar. How can I update the column values to remove .0 from all the string values?
For example:
Imported Values
12345.0
A119B
65489.0
BD585
123.0
124.0
12.0
Desired Result
12345
A119B
65489
BD585
123
124
12
If the decimal value is not certain, you should consider using SUBSTRING_INDEX() ; either in SELECT or UPDATE. Now you're just showing example of .0 but what if it has more variation than just .0? I assume at least that the unwanted value is always going to be after . so:
SELECT SUBSTRING_INDEX(val,'.',1) FROM mytable;
result:
+----------------------------+
| SUBSTRING_INDEX(val,'.',1) |
+----------------------------+
| 12345 |
| A119B |
| 65489 |
| BD585 |
| 123 |
| 124 |
| 12 |
+----------------------------+
Use same function for the update:
UPDATE mytable
SET val=SUBSTRING_INDEX(val,'.',1)
WHERE val LIKE '%.%';
Demo fiddle
UPDATE table SET colName = REPLACE(colName, ".0", "")
Credit goes to: #WOUNDEDStevenJones
Note: change table with your table name and colName with your column Name.

MySQL - How to use input param having comma separated string value, in an IN clause

I have to query a table in MySQL based on a column which is of string type.
-----------------------------------
id | lookupkeys | productid |
-----------------------------------
1 | key1 | 5GEH03 |
2 | key2 | 7445DW |
3 | key3 | 9DSFDF |
4 | key4 | 5GEH03 |
5 | keyN | 7445DW |
-----------------------------------
A stored procedure to accept multiple values (comma separated) in single input parameter which is to be used in IN clause.
Input : #keys = "key1,key5,key19,key22"
Query : SELECT * FROM MyTable WHERE lookupkeys IN ("key1","key5","key19","key22");
So basically I need a way how to have this comma separated input to individual values for the IN clause ?
Below is a dummy sp
CREATE DEFINER=`xxx_xx`#`%` PROCEDURE `sp_demo_fetch_products`(
IN v_lookupkeys VARCHAR(200)
)
BEGIN
SELECT * FROM products_lookup WHERE lookupkeys IN(here I want to use v_lookupkeys)
AND CONDITION_1
AND CONDITION_2
ORDER BY popularity DESC;
END$$

MySQL - add text prefix before column name in SELECT statement

Here is my table:
| ID | NUMBER |
| 1 | 523 |
| 2 | 293 |
| 3 | 948 |
And now, I want to get all NUMBER values but I want to add in result two numbers - 48 - (without upadting existing results). So finally I want print these results:
| NUMBER |
| 48523 |
| 48293 |
| 48948 |
So I need a query, something like this:
SELECT '48' + `number` FROM `table`
but this query doesn't work fine (this query only update column name from NUMBER to 48 + NUMBER).
Any ideas?
Thanks.
You need CONCAT
SELECT CONCAT('48' , `number`) AS number FROM table
Demo

Count all same comma separated value in one column mysql

I have 2 table and there's a column which contains comma separated value and I want to count all same value of that column, here's the sample table:
Client table
ID | Name | Procedure
1 | Joe | Samp1,Samp2
2 | Doe | Samp1,Samp2,Samp3
3 | Noe | Samp1,Samp2
Desire Output
Summary table ( For Procedure )
ID | NAME | COUNT
1 | Samp1 | 3
2 | Samp2 | 3
3 | Samp3 | 1
Now, do you have any idea or suggestion so i can make it happen ? like add new table or is this possible with single query ?
Try this query
SELECT LENGTH(COLUMN) - LENGTH(REPLACE(COLUMN, ',', '')) FROM TABLE_NAME