Simplest way to do an array literal in MySQL - mysql

I would like to get the array [1,2,3] in mysql. For example:
with tbl (id) as (
select 1 union select 2 union select 3
) select 'something', json_arrayagg(id) from tbl
# something, json_arrayagg(id)
# 'something', '[1, 2, 3]'
Would there be a simpler way to do this rather than sort of 'building up a table' in a CTE and then grouping it outside it?
For example, I am trying to do something like this (if possible):
SELECT '1', [1,2,3]
MySQL '8.0.20' Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '[1,2,3]) ids from sort group by letter order by ids asc SELECT '1', [1,2,3]' at line 4

After much commenting above, your actual question has come out, which is that you are confused about how to work with JSON literals in MySQL. Valid JSON literals in MySQL always are surrounded by single quotes, just like string literals. Consider this small example:
WITH yourTable AS (
SELECT '1' AS id, '[1,2,3]' AS array
)
SELECT Id, JSON_EXTRACT(array, '$[2]') AS third
FROM yourTable;
This outputs 1, 3 as the demo link shows. The key here is that the JSON array literal, which you already know how to form, is in single quotes.

Related

Get unique values of a field and prints its length

Table Name: Worker,
Fields : worker_id | first_name | last_name | department
I have a table name worker and i wanted to write an SQL query that fetches the unique values of DEPARTMENT from Worker table and prints its length. So i tried running this : (Database- Mysql)
select length(distinct(department)) from worker;
But it is giving an error saying:
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'distinct(department)) from worker' at line 1
But when i ran below query, it works perfectly fine:
select distinct(length(department)) from worker;
Can somebody please explain me why interchanging distinct and length function makes query works?
Thanks in advance!
Try not to use distinct like function but clause otherwise it will give syntax error.
Below sql statement will execute as shown below:
select distinct (length('xyz')) ---- length('xyz') : 3
select distinct (3) ---- output : 3
Distinct is not properly a function but a clause
select distinct length(department) from worker;
Anyway in MySQL work also with function syntax
select distinct( length(department)) from worker;
The code with the exchanged token don't work because DISTINCT produce an aggregated result removing the duplicated values,this implies that the outer length() function work on not correct set of rows or better the db engine see that there an improper use of the DISTINCT clause and raise the syntax error
select length( distinct 'A' ) this raise an error
If you want use the outer length() function you should code this way
select length(my_col) from (
select distinct department my_col from worker
) ;
correct answer :
select distinct <column_dept> as department***,*** (len(<column_dept>) as length_column_dept from xyz_table
select distinct( length(department)),department from worker group by department;
select distinct (Department) as 'Unique department', len(Department) as 'length of name' from Worker;

REPLACE function but with entire column - MySQL

I learned about the select replace('string','to be replaced','with this') function, but I'm wondering is there a way I can do something to a whole column, like this
select replace(table.column1,'replace this', 'with this');
Right now, the command is returning Query 1 ERROR: Unknown table 'private_db' in field list
You need a FROM clause.
SELECT replace(column1, 'replace this', 'with this') AS new_column1
FROM yourTable
This will return all the values in column1 with the replacement made.

MySQL: Ordering of columns when using a wildcard with group by has odd behavior

What is the difference between these two MySQL statements?
Works:
select *, count(mycol) c from mytable group by mycol;
Doesn't work:
select count(mycol) c, * from mytable group by mycol;
The first statement works as I'd expect, while the second one gives me a syntax error. Why does the order matter?
I'm having trouble finding an answer from Google, because I'm not entirely sure if I'm asking the question correctly.
Edit:
Here's the sanitized error message. I'm using MySQL Workbench, if that's relevant.
Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '* from mytable group by id' at line 1
Just alias the table and the syntax error will go away.
select count(t.id) c, t.* from mytable t group by id;
See this db fiddle.
It looks like MySQL allows bare (unqualified) * only as immediatly following SELECT. The following query also raises a syntax error :
select 1, * from mytable t;
The documentation prevents against using bare * combined with other items in the SELECT list :
A select list consisting only of a single unqualified * can be used as shorthand to select all columns from all tables.
Use of an unqualified * with other items in the select list may produce a parse error. To avoid this problem, use a qualified tbl_name.* reference.

MySQL - Using * in a conditional statement

I am attempting to execute the following statement...
SELECT
SUM(CASE WHEN CLG ='A*' THEN 1 END) as A*
From Grades
However, I receive the following error...
"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '*,"
I realise of course that * is used in select statements to select all the rows of a table. However in my case, I want to find the number of records that contain the value of A*. Would anyone be able to point out what I can do to solve this error without having to remove the A* values from my table?
You need to use backticks:
SELECT SUM(CASE WHEN CLG ='A*' THEN 1 END) as `A*`
From Grades;
Actually you could skip CASE:
SELECT SUM(CLG ='A*') as `A*`
From Grades
Your problem is the column alias. Don't use inappropriate characters for column names. Do something like this:
SELECT SUM( CLG = 'A*' ) as A_star
From Grades;
Having to deal with identifiers that use unusual characters is just a pain -- making queries hard to write and to read.

Concat a string to SELECT * MySql

The following query works fine with MySQL:
SELECT concat(title,'/') FROM `socials` WHERE 1
It Concat / to the selected title field.
However, when I try to do the following:
SELECT concat(*,'/') FROM `socials` WHERE 1
It returns the follwoing Error:
#1064 - You have an error in your SQL syntax;
check the manual that corresponds to your MySQL server version for the right syntax to use near '*,'/') FROM `socials` WHERE 1 LIMIT 0, 30' at line 1
So is there any way to make such sql query to work with MySql
You simply can't do that in SQL. You have to explicitly list the fields and concat each one:
SELECT CONCAT(field1, '/'), CONCAT(field2, '/'), ... FROM `socials` WHERE 1
If you are using an app, you can use SQL to read the column names, and then use your app to construct a query like above. See this stackoverflow question to find the column names: Get table column names in mysql?
If you want to concatenate the fields using / as a separator, you can use concat_ws:
select concat_ws('/', col1, col2, col3) from mytable
You cannot escape listing the columns in the query though. The *-syntax works only in "select * from". You can list the columns and construct the query dynamically though.
You cannot concatenate multiple fields with a string. You need to select a field instand of all (*).
You cannot do this on multiple fields. You can also look for this.