MsSQL Books


Tuesday, May 19, 2009

CONCAT in MySQL

 

Here I will show you how to do string concatenation in MySQL select statement.

Assume you have a table like below

Table: employee (before concatenation)
idfirstname
lastname
1 John Doe

 

and you want your query to return like this:

Table: employee (after concatenation)
idfullname
1 John Doe

 

Its easy, the query is like this:

SELECT id, CONCAT(firstname, ' ', lastname) AS fullname FROM employee

If you want it to be return like for example: Firstname: John, Lastname: Doe

Try this: SELECT id, CONCAT('Firstname: ', firstname, ', Lastname: ', lastname) AS fullname FROM employee

See how to do this in VistaDB

Wednesday, May 17, 2006

Convert string to date in mySQL 2

In my previous blog, I've show how to convert a string in database to a datetime format. That syntax is only supported in mySQL 4.0 and above. In that version, it uses this syntax:

STR_TO_DATE(date,'%d/%m/%Y')

So, for mySQL 4.0 and below, just change the syntax to:

DATE_ADD( CONCAT(SUBSTRING_INDEX(`date`,'/',-1) , '-' , SUBSTRING_INDEX(substring_index(`date`,'/',2),'/',-1) , '-', SUBSTRING_INDEX(`date`,'/',1)), interval 0 day)

Example:

4.0 and above:
SELECT STR_TO_DATE(date,'%d/%m/%Y') AS myNewdate FROM myTable

below 4.0
SELECT DATE_ADD( CONCAT(SUBSTRING_INDEX(`date`,'/',-1) , '-' , SUBSTRING_INDEX(substring_index(`date`,'/',2),'/',-1) , '-', SUBSTRING_INDEX(`date`,'/',1)), interval 0 day) AS myNewdate FROM myTable

Tuesday, April 18, 2006

Convert string to date in mySQL

if you have a date column in a table that has a string datatype, it is impossible to query or find the record between 2 durations of date. for example, you have a table "myTable"

myTable

---------------------------
Column  | Type
---------------------------
date            | varchar

it is impossible to query like this
SELECT * FROM myTable WHERE date>='@dtFrom' AND date<='@dtTo' the correct way to get the record between the 2 dates is like this SELECT * FROM myTable WHERE STR_TO_DATE(date,'%d/%m/%Y') <= '@dtFrom' AND STR_TO_DATE(date,'%d/%m/%Y') <= '@dtTo' STR_TO_DATE(date,'%d/%m/%Y') the type '%d/%m/%Y' is depend on how you store the date into the table. In my case, I store it as 18/04/2006 more help can be found here - dev.mysql.com