Mysql CAST(CONCAT_WS trying to get correct syntax - mysql

This works
SELECT EntryId FROM 2_1_journal
WHERE CAST(CONCAT_WS('-', RecordYear,RecordMonth,RecordDay) AS DATE) = ?
But want before WHERE to define "virtual" column name for date with column name for example RecordDate.
Tried
SELECT EntryId FROM 2_1_journal
CAST(CONCAT_WS('-', RecordYear,RecordMonth,RecordDay) AS DATE) RecordDate
WHERE RecordDate = ?
SELECT EntryId FROM 2_1_journal
CAST(CONCAT_WS('-', RecordYear,RecordMonth,RecordDay) AS DATE) AS RecordDate
WHERE RecordDate = ?
SELECT EntryId FROM 2_1_journal
CAST((CONCAT_WS('-', RecordYear,RecordMonth,RecordDay) AS DATE) AS RecordDate)
WHERE RecordDate = ?
In all cases get error Syntax error or access violation: 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 'CAST.
Please advice what is correct synatax

http://dev.mysql.com/doc/refman/5.5/en/select.html:
β€œIt is not permissible to refer to a column alias in a WHERE clause, because the column value might not yet be determined when the WHERE clause is executed. See Section C.5.5.4, Problems with Column Aliases.”
If you want to select the result of an operation in the WHERE clause as a column value as well, then you will have to write that operation two times – once in the WHERE clause, without an alias, and in the column list after SELECT as well.

Related

How to get count in SQL if the column value is something specific

I want to show the count in the SQL query, but I have a problem with it. I want to search for count only if there is something specific in the value column. Here is an example of my query:
SELECT COUNT(IF status='F') FROM relation WHERE from='7'
So, here I want to get the amount of "relation" from the column "status" from the table, when the status value is F.
With the above code, I get an error message:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '`status`='F') FROM `relation` WHERE `from`='7' LIMIT 0, 25' at line 1
I think two common ways are:
SELECT
COUNT(CASE WHEN status='F' THEN 1 END)
FROM relation
WHERE from='7'
and
SELECT
SUM(CASE WHEN status='F' THEN 1 ELSE 0 END)
FROM relation
WHERE from='7'
The first one uses count but since it only counts non-null values, it only counts the ones you want. The second uses sum, but since we sum 1 if your condition is true and 0 if your condition is false it's equivalent to counting where the condition is true.
Although in your case since you're not doing a group by you could just use
SELECT
COUNT(*)
FROM relation
WHERE from='7' AND status='F'
You can count this way to get only counts where the value of status is F
SELECT COUNT(*) FROM relation WHERE from='7' AND status='F';
I prefer summing a boolean expression:
SELECT SUM(status = 'F') AS cnt
FROM relation
WHERE `from` = '7';
Note that FROM is a reserved MySQL keyword. If you really did name a column FROM, then you will have to forever escape it in backticks. You should avoid naming your database objects using reserved keywords.

Use result of WITH clause to filter WHERE ... IN columnName

I want to use the result of a WITH clause to filter a query like below:
WITH Max_Dates AS (
SELECT MAX(created_date) AS maxdate
FROM transactions
GROUP BY DATE (created_date)
)
SELECT *
FROM transactions
WHERE created_date IN Max_Dates -- can I somehow reference column maxdate as a list here?
The syntax is incorrect. I know I can use the content of the WITH clause as a subquery in the WHERE below to get the result I want, but I want to know specifically if the WITH result can be used.
My question is, is there a general syntax for using a column from a WITH clause to filter as a list in a WHERE ... IN {list}?
As per this blog it seems it should be possible to use WHERE created_at IN Max_Dates.maxdate, but I'm using MySQL 8.0.29 and it doesn't like that syntax - 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 'Max_Dates.maxdate' at line 8")
WITH Max_Dates AS
(
SELECT MAX(created_date) AS maxdate
FROM transactions
GROUP BY DATE (created_date)
)
SELECT *
FROM transactions
WHERE created_date IN (select maxdate from Max_Dates)
The CTE (Common Table Expression) Max_Dates is a resultset that potentially has multiple columns, so you must specify the specific column from Max_Dates that should be used to build the list of values for the IN expression.

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;

when i fetch the data from database it give error on sql command . how can i fixed the code

SELECT (SUM(MAX(identifier)+1) FROM student_ids WHERE state ='state' AND year='year');
SELECT (SUM(MAX(identifier)+1) FROM student_ids WHERE state ='state' AND year='year')
LIMIT 0, 25
MySQL said: Documentation
#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 student_ids WHERE state ='state' AND year='year')
LIMIT 0, 25' at line 1
how can i fix the error
The SUM function is for taking aggregates of columns, across multiple rows. You don't need to use it to add a scalar value:
SELECT MAX(identifier) + 1 AS max_id
FROM student_ids
WHERE state = 'state' AND year = 'year';
Additionnaly to #tim-biegeleisen, use ` for column names and table names, like this : `year`, `state`, ...
Because some words you uses are reserved. YEAR is reserved word and could return an error if you uses it as column name. SQL thinks you are calling the year function instead of a column named year.
SELECT MAX(`identifier`) + 1 AS `max_id`
FROM `student_ids`
WHERE `state` = 'state'
AND `year` = 'year' ;
Here is documentation about reserved words in mySQL :
https://dev.mysql.com/doc/refman/5.5/en/keywords.html

MySQL error 1064 (v 5.0.96) GROUP BY clause

I'm used to running on an Oracle database, so I'm not really quite sure how to trouble shoot this problem. I've narrowed down a simple example of my query to the following:
SELECT 0 as gm_rowID,
'-ALL Grantmakers-' as grantmakerName
FROM dual
GROUP BY 2
phpMyAdmin runs the SQL with the following 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 'ORDER BY 2 LIMIT 0, 30' at line 1
Oracle can run this query just fine. MySQL can run the query without the GROUP BY clause. Any ideas?
--Here is the entire query:
SELECT
p.grantmaker_rowid as gm_rowID,
gm.grantmaker_companyName as grantmakerName
FROM grantmaker_info gm, proposal_submission p
WHERE 0=0
AND p.grantmaker_rowid = gm.grantmaker_rowid
UNION
SELECT
0 as gm_rowID,
'-ALL Grantmakers-' as grantmakerName
FROM dual
ORDER BY 2
GROUP BY 2
LIMIT 0 , 30
Columns selected for output can be referred to in ORDER BY and GROUP BY clauses using column
names, column aliases, or column positions. Column positions are
integers and begin with 1
From: http://dev.mysql.com/doc/refman/5.0/en/select.html
Unless you only have 1 column in that table, it should run fine. My suggestion however would be to reference the column name (or alias) of whatever you're trying to GROUP BY.
edit: My only other suggestion is to include the SHOW CREATE TABLE output for that table.
edit2: Ok I see you've updated your question. Why not instead of ORDER BY 2, you ORDER BY grantmakerName (if that's the column you want to order by?)