How do I handle moving data from tinyint into a text field - mysql

We have a field which stores data (e.g. 1, 0) in a tinyint(1) column, and I have to move this into a text column and a simple transformation stores the data in text field with additional spaces instead of just 1 or 0. How should I do this correctly?
create table A (id, foo tinyint(1));
create table B (id, bar text);
I am trying to copy all elements of A into B using insert into B (id, bar) select id, foo from A; which is causing the transformation problem.

There is nothing wrong with your insert statement. The problem lies with the way MySQL compares strings.
Even the following query will match:
SELECT * FROM B where TRIM(bar) = '1 ';
The following works correctly (IE, does not match):
SELECT * FROM B where bar LIKE '1 ';

MySQL masters implicit conversion. Since you are converting a number to a string type, I don't see any problem which could occur. Therefore, something like UPDATE table1 SET text_column = CONCAT(' ',tinyint_column,' ') should work.

Related

SQL - Want to output the ones with the same first name but different last name. Full name in the same column

How do i go on about on a query for where i wanna extract the same first name but the last name is different?
NAME
------
Chris Stutter
Chris Lamb
Alfred Dark
Kristine Light
output:
Chris Stutter
Chris Lamb
I've made a script for you for this specific condition. Based on the info you shared, I've created the test scripts below. You can test this script and see the result really quickly at https://onecompiler.com/mysql/
-- create
CREATE TABLE YOUR_TABLE (
Name TEXT NOT NULL
);
-- insert
INSERT INTO YOUR_TABLE VALUES ('Chris Stutter');
INSERT INTO YOUR_TABLE VALUES ('Chris Stutter');
INSERT INTO YOUR_TABLE VALUES ('Chris Stutter');
INSERT INTO YOUR_TABLE VALUES ('Chris Lamb');
INSERT INTO YOUR_TABLE VALUES ('Alfred Dark');
INSERT INTO YOUR_TABLE VALUES ('Alfred Dark');
INSERT INTO YOUR_TABLE VALUES ('Kristine Light');
-- fetch
SELECT DISTINCT *
FROM YOUR_TABLE
WHERE SUBSTRING_INDEX(Name, ' ', 1) IN (
SELECT *
FROM (
SELECT SUBSTRING_INDEX(Name, ' ', 1) as firstName
FROM YOUR_TABLE
GROUP BY firstName
HAVING COUNT(DISTINCT Name) > 1
) AS DuplicatedFirstNames
);
You should be able to utilize this fetch script as a reference and modify it accordingly for your own purpose now.
You want to work with first name and last name in your database, but your table doesn't provide that information. It only has a column for the full name. This means that your database design is not appropriate for the task. The information you seek is not stored atomic, but in a concatenated form and thus violates the first normal form. (This also shows that database normalization sometimes depends on how you want to work with the data.) The best way to deal with this problem is hence to change your database and make first and last name separate columns.
If you cannot change the database design, the first task is to find out in which formats the names are stored. So far you have shown "first name - one blank - last name". If this is the only format, then it is rather easy to split the two. If, however, you also have to deal with 'Smith, John' or 'Arthur Conan Doyle', it gets more complex. Let's say all names are in the same format. So, split first name and last name and work with these.
Once you have separate first and last name, the task becomes easy. You are looking for names for which exists another last name with the same first name, i.e. use EXISTS.
WITH names AS
(
SELECT
SUBSTRING_INDEX(name, ' ', 1) AS first_name,
SUBSTRING_INDEX(name, ' ', -1) AS last_name
FROM mytable
)
SELECT first_name, last_name
FROM names
WHERE EXISTS
(
SELECT NULL
FROM names other
WHERE other.first_name = names.first_name
AND other.last_name <> names.last_name
)
ORDER BY first_name, last_name;

How can I fill in the data from another table based on a single attribute [duplicate]

I am trying to INSERT INTO a table using the input from another table. Although this is entirely feasible for many database engines, I always seem to struggle to remember the correct syntax for the SQL engine of the day (MySQL, Oracle, SQL Server, Informix, and DB2).
Is there a silver-bullet syntax coming from an SQL standard (for example, SQL-92) that would allow me to insert the values without worrying about the underlying database?
Try:
INSERT INTO table1 ( column1 )
SELECT col1
FROM table2
This is standard ANSI SQL and should work on any DBMS
It definitely works for:
Oracle
MS SQL Server
MySQL
Postgres
SQLite v3
Teradata
DB2
Sybase
Vertica
HSQLDB
H2
AWS RedShift
SAP HANA
Google Spanner
Claude Houle's answer: should work fine, and you can also have multiple columns and other data as well:
INSERT INTO table1 ( column1, column2, someInt, someVarChar )
SELECT table2.column1, table2.column2, 8, 'some string etc.'
FROM table2
WHERE table2.ID = 7;
I've only used this syntax with Access, SQL 2000/2005/Express, MySQL, and PostgreSQL, so those should be covered. It should also work with SQLite3.
To get only one value in a multi value INSERT from another table I did the following in SQLite3:
INSERT INTO column_1 ( val_1, val_from_other_table )
VALUES('val_1', (SELECT val_2 FROM table_2 WHERE val_2 = something))
Both the answers I see work fine in Informix specifically, and are basically standard SQL. That is, the notation:
INSERT INTO target_table[(<column-list>)] SELECT ... FROM ...;
works fine with Informix and, I would expect, all the DBMS. (Once upon 5 or more years ago, this is the sort of thing that MySQL did not always support; it now has decent support for this sort of standard SQL syntax and, AFAIK, it would work OK on this notation.) The column list is optional but indicates the target columns in sequence, so the first column of the result of the SELECT will go into the first listed column, etc. In the absence of the column list, the first column of the result of the SELECT goes into the first column of the target table.
What can be different between systems is the notation used to identify tables in different databases - the standard has nothing to say about inter-database (let alone inter-DBMS) operations. With Informix, you can use the following notation to identify a table:
[dbase[#server]:][owner.]table
That is, you may specify a database, optionally identifying the server that hosts that database if it is not in the current server, followed by an optional owner, dot, and finally the actual table name. The SQL standard uses the term schema for what Informix calls the owner. Thus, in Informix, any of the following notations could identify a table:
table
"owner".table
dbase:table
dbase:owner.table
dbase#server:table
dbase#server:owner.table
The owner in general does not need to be quoted; however, if you do use quotes, you need to get the owner name spelled correctly - it becomes case-sensitive. That is:
someone.table
"someone".table
SOMEONE.table
all identify the same table. With Informix, there's a mild complication with MODE ANSI databases, where owner names are generally converted to upper-case (informix is the exception). That is, in a MODE ANSI database (not commonly used), you could write:
CREATE TABLE someone.table ( ... )
and the owner name in the system catalog would be "SOMEONE", rather than 'someone'. If you enclose the owner name in double quotes, it acts like a delimited identifier. With standard SQL, delimited identifiers can be used many places. With Informix, you can use them only around owner names -- in other contexts, Informix treats both single-quoted and double-quoted strings as strings, rather than separating single-quoted strings as strings and double-quoted strings as delimited identifiers. (Of course, just for completeness, there is an environment variable, DELIMIDENT, that can be set - to any value, but Y is safest - to indicate that double quotes always surround delimited identifiers and single quotes always surround strings.)
Note that MS SQL Server manages to use [delimited identifiers] enclosed in square brackets. It looks weird to me, and is certainly not part of the SQL standard.
Two approaches for insert into with select sub-query.
With SELECT subquery returning results with One row.
With SELECT subquery returning results with Multiple rows.
1. Approach for With SELECT subquery returning results with one row.
INSERT INTO <table_name> (<field1>, <field2>, <field3>)
VALUES ('DUMMY1', (SELECT <field> FROM <table_name> ),'DUMMY2');
In this case, it assumes SELECT Sub-query returns only one row of result based on WHERE condition or SQL aggregate functions like SUM, MAX, AVG etc. Otherwise it will throw error
2. Approach for With SELECT subquery returning results with multiple rows.
INSERT INTO <table_name> (<field1>, <field2>, <field3>)
SELECT 'DUMMY1', <field>, 'DUMMY2' FROM <table_name>;
The second approach will work for both the cases.
To add something in the first answer, when we want only few records from another table (in this example only one):
INSERT INTO TABLE1
(COLUMN1, COLUMN2, COLUMN3, COLUMN4)
VALUES (value1, value2,
(SELECT COLUMN_TABLE2
FROM TABLE2
WHERE COLUMN_TABLE2 like "blabla"),
value4);
Instead of VALUES part of INSERT query, just use SELECT query as below.
INSERT INTO table1 ( column1 , 2, 3... )
SELECT col1, 2, 3... FROM table2
Most of the databases follow the basic syntax,
INSERT INTO TABLE_NAME
SELECT COL1, COL2 ...
FROM TABLE_YOU_NEED_TO_TAKE_FROM
;
Every database I have used follow this syntax namely, DB2, SQL Server, MY SQL, PostgresQL
This can be done without specifying the columns in the INSERT INTO part if you are supplying values for all columns in the SELECT part.
Let's say table1 has two columns. This query should work:
INSERT INTO table1
SELECT col1, col2
FROM table2
This WOULD NOT work (value for col2 is not specified):
INSERT INTO table1
SELECT col1
FROM table2
I'm using MS SQL Server. I don't know how other RDMS work.
This is another example using values with select:
INSERT INTO table1(desc, id, email)
SELECT "Hello World", 3, email FROM table2 WHERE ...
Just use parenthesis for SELECT clause into INSERT. For example like this :
INSERT INTO Table1 (col1, col2, your_desired_value_from_select_clause, col3)
VALUES (
'col1_value',
'col2_value',
(SELECT col_Table2 FROM Table2 WHERE IdTable2 = 'your_satisfied_value_for_col_Table2_selected'),
'col3_value'
);
Simple insertion when table column sequence is known:
Insert into Table1
values(1,2,...)
Simple insertion mentioning column:
Insert into Table1(col2,col4)
values(1,2)
Bulk insertion when number of selected columns of a table(#table2) are equal to insertion table(Table1)
Insert into Table1 {Column sequence}
Select * -- column sequence should be same.
from #table2
Bulk insertion when you want to insert only into desired column of a table(table1):
Insert into Table1 (Column1,Column2 ....Desired Column from Table1)
Select Column1,Column2..desired column from #table2
from #table2
Here is another example where source is taken using more than one table:
INSERT INTO cesc_pf_stmt_ext_wrk(
PF_EMP_CODE ,
PF_DEPT_CODE ,
PF_SEC_CODE ,
PF_PROL_NO ,
PF_FM_SEQ ,
PF_SEQ_NO ,
PF_SEP_TAG ,
PF_SOURCE)
SELECT
PFl_EMP_CODE ,
PFl_DEPT_CODE ,
PFl_SEC ,
PFl_PROL_NO ,
PF_FM_SEQ ,
PF_SEQ_NO ,
PFl_SEP_TAG ,
PF_SOURCE
FROM cesc_pf_stmt_ext,
cesc_pfl_emp_master
WHERE pfl_sep_tag LIKE '0'
AND pfl_emp_code=pf_emp_code(+);
COMMIT;
Here's how to insert from multiple tables. This particular example is where you have a mapping table in a many to many scenario:
insert into StudentCourseMap (StudentId, CourseId)
SELECT Student.Id, Course.Id FROM Student, Course
WHERE Student.Name = 'Paddy Murphy' AND Course.Name = 'Basket weaving for beginners'
(I realise matching on the student name might return more than one value but you get the idea. Matching on something other than an Id is necessary when the Id is an Identity column and is unknown.)
You could try this if you want to insert all column using SELECT * INTO table.
SELECT *
INTO Table2
FROM Table1;
I actually prefer the following in SQL Server 2008:
SELECT Table1.Column1, Table1.Column2, Table2.Column1, Table2.Column2, 'Some String' AS SomeString, 8 AS SomeInt
INTO Table3
FROM Table1 INNER JOIN Table2 ON Table1.Column1 = Table2.Column3
It eliminates the step of adding the Insert () set, and you just select which values go in the table.
This worked for me:
insert into table1 select * from table2
The sentence is a bit different from Oracle's.
INSERT INTO yourtable
SELECT fielda, fieldb, fieldc
FROM donortable;
This works on all DBMS
For Microsoft SQL Server, I will recommend learning to interpret the SYNTAX provided on MSDN. With Google it's easier than ever, to look for syntax.
For this particular case, try
Google: insert site:microsoft.com
The first result will be http://msdn.microsoft.com/en-us/library/ms174335.aspx
scroll down to the example ("Using the SELECT and EXECUTE options to insert data from other tables") if you find it difficult to interpret the syntax given at the top of the page.
[ WITH <common_table_expression> [ ,...n ] ]
INSERT
{
[ TOP ( expression ) [ PERCENT ] ]
[ INTO ]
{ <object> | rowset_function_limited
[ WITH ( <Table_Hint_Limited> [ ...n ] ) ]
}
{
[ ( column_list ) ]
[ <OUTPUT Clause> ]
{ VALUES ( { DEFAULT | NULL | expression } [ ,...n ] ) [ ,...n ]
| derived_table <<<<------- Look here ------------------------
| execute_statement <<<<------- Look here ------------------------
| <dml_table_source> <<<<------- Look here ------------------------
| DEFAULT VALUES
}
}
}
[;]
This should be applicable for any other RDBMS available there. There is no point in remembering all the syntax for all products IMO.
INSERT INTO FIRST_TABLE_NAME (COLUMN_NAME)
SELECT COLUMN_NAME
FROM ANOTHER_TABLE_NAME
WHERE CONDITION;
Best way to insert multiple records from any other tables.
INSERT INTO dbo.Users
( UserID ,
Full_Name ,
Login_Name ,
Password
)
SELECT UserID ,
Full_Name ,
Login_Name ,
Password
FROM Users_Table
(INNER JOIN / LEFT JOIN ...)
(WHERE CONDITION...)
(OTHER CLAUSE)
select *
into tmp
from orders
Looks nice, but works only if tmp doesn't exists (creates it and fills). (SQL sever)
To insert into existing tmp table:
set identity_insert tmp on
insert tmp
([OrderID]
,[CustomerID]
,[EmployeeID]
,[OrderDate]
,[RequiredDate]
,[ShippedDate]
,[ShipVia]
,[Freight]
,[ShipName]
,[ShipAddress]
,[ShipCity]
,[ShipRegion]
,[ShipPostalCode]
,[ShipCountry] )
select * from orders
set identity_insert tmp off
IF you want to insert some data into a table without want to write column name.
INSERT INTO CUSTOMER_INFO
(SELECT CUSTOMER_NAME,
MOBILE_NO,
ADDRESS
FROM OWNER_INFO cm)
Where the tables are:
CUSTOMER_INFO || OWNER_INFO
----------------------------------------||-------------------------------------
CUSTOMER_NAME | MOBILE_NO | ADDRESS || CUSTOMER_NAME | MOBILE_NO | ADDRESS
--------------|-----------|--------- || --------------|-----------|---------
A | +1 | DC || B | +55 | RR
Result:
CUSTOMER_INFO || OWNER_INFO
----------------------------------------||-------------------------------------
CUSTOMER_NAME | MOBILE_NO | ADDRESS || CUSTOMER_NAME | MOBILE_NO | ADDRESS
--------------|-----------|--------- || --------------|-----------|---------
A | +1 | DC || B | +55 | RR
B | +55 | RR ||
If you go the INSERT VALUES route to insert multiple rows, make sure to delimit the VALUES into sets using parentheses, so:
INSERT INTO `receiving_table`
(id,
first_name,
last_name)
VALUES
(1002,'Charles','Babbage'),
(1003,'George', 'Boole'),
(1001,'Donald','Chamberlin'),
(1004,'Alan','Turing'),
(1005,'My','Widenius');
Otherwise MySQL objects that "Column count doesn't match value count at row 1", and you end up writing a trivial post when you finally figure out what to do about it.
If you create table firstly you can use like this;
select * INTO TableYedek From Table
This metot insert values but differently with creating new copy table.
In informix it works as Claude said:
INSERT INTO table (column1, column2)
VALUES (value1, value2);
Postgres supports next:
create table company.monitor2 as select * from company.monitor;

How to check if exact slug (either single occurence or multiple occurence) is present in a Mysql DB?

I am creating new slug. Say my slug variable is $slug = 'About-Us'.
I have a table where there is a field called slug. The values of slug column can be like this:-
'About-Us'
'About-Us-2',
'About-Us-3',
'About-Us-5'
In case of duplicate slugs, we are appending a numeric value after the last dash.
'About-Us-2',
'About-Us-3',
'About-Us-5'
When inserting new data, we need to check if a slug is either present in exact form, or the part followed by the last "-" dash is a numeric one.
I wanted to check this by using this query
"SELECT COUNT(*) FROM table WHERE SLUG LIKE 'About-Us%'"
The above query has a problem. If a slug is present like "About-Uses", then it is returning a count 1. What we need to check is whether the section after the last dash is numeric or not.
Also slugs like "About-Us-2-Know" must be considered different from 'About-Us', while 'About-Us-2' or 'About-us-3' must be considered as multiple occurence of 'About-Us'
EDIT:
This is not duplicate. It is not about only checking with last character as numeric. It is about checking whether the string before last dash is exact match and string after last dash is a numeric.
Here is how I solved using only MySql. May need to tweak for your needs, but using SUBSTRING_INDEX is the main solution for me.
/*
'About-Us'
'About-Us-2',
'About-Us-3',
'About-Us-5'
*/
DROP TABLE IF EXISTS `bleach`;
DROP TABLE IF EXISTS `bleach2`;
CREATE TABLE bleach (slug VARCHAR (255) NOT NULL);
INSERT INTO bleach SELECT 'About-Us';
INSERT INTO bleach SELECT 'About-Us-2';
INSERT INTO bleach SELECT 'About-Us-3';
INSERT INTO bleach SELECT 'About-Us-5';
INSERT INTO bleach SELECT 'About-Us-6-extra';
INSERT INTO bleach SELECT 'About-Us-NoMatch';
-- About us match
CREATE TABLE bleach2
SELECT slug, SUBSTRING_INDEX(slug,'-',2) AS about_us,
SUBSTRING_INDEX(slug,'-',-1) AS first_numeric,
SUBSTRING_INDEX(SUBSTRING_INDEX(slug,'-',-2),'-',1) AS second_numeric
FROM bleach;
SELECT * FROM bleach2;
-- All but About-Us-NoMatch should return
SELECT * FROM bleach2 WHERE about_us='About-Us' AND
(first_numeric IN ('1','2','3','4','5','6','7','8','9') OR second_numeric IN ('1','2','3','4','5','6','7','8','9'))
OR second_numeric='About';

I have a column "POLICY_RATE_AMOUNT" WHICH IS IN VARCHAR DATATYPE AND IT HOLDS THE DOLLAR VALUE

Now i want to add a thousand separator to that column.
but when i add this query to that column
select REPLACE(CONVERT(VARCHAR,CONVERT(MONEY,POLICY_RATE_AMOUNT),1), '.00','') from table
i am getting this error
cannot convert a char value to money.
Please help
First of all: Always use appropriate types to store your values!
Secondly: Never use (n)char (same with (n)varchar) without a size! (Aaron Bertrand: Bad habits to kick)
Third: Never store information, which is just a formatting issue together with the value (the dollar symbol).
Now check this
SELECT CONVERT(MONEY,'$1234.56') --This works. The leading "$" is ignored.
SELECT CONVERT(MONEY,'1234.56$') --Breaks with your error message
As a repair fix you can use replace to get rid of the symbol:
select REPLACE(CONVERT(VARCHAR,CONVERT(MONEY,REPLACE(POLICY_RATE_AMOUNT,'$','')),1), '.00','') from xyz
If the $ is after the value, like 100$ then below query will help in converting.
create table #tmp (POLICY_RATE_AMOUNT varchar(10))
insert into #tmp values ('$100'),('-$150')
select REPLACE(CONVERT(MONEY,RIGHT(POLICY_RATE_AMOUNT,LEN(POLICY_RATE_AMOUNT)-1)), '.00','')
FROM #tmp
WHERE LEN(POLICY_RATE_AMOUNT)=LEN(REPLACE(POLICY_RATE_AMOUNT,'-',''))
UNION ALL
select REPLACE(CONVERT(MONEY,RIGHT(POLICY_RATE_AMOUNT,LEN(POLICY_RATE_AMOUNT)-1)), '.00','')
FROM #tmp
WHERE LEN(POLICY_RATE_AMOUNT)!=LEN(REPLACE(POLICY_RATE_AMOUNT,'-',''))
drop table #tmp

INSERT INTO with SubQuery MySQL

I have this Statement:
INSERT INTO qa_costpriceslog (item_code, invoice_code, item_costprice)
VALUES (1, 2, (SELECT item_costprice FROM qa_items WHERE item_code = 1));
I'm trying to insert a value copy the same data of item_costprice, but show me the error:
Error Code: 1136. Column count doesn't match value count at row 1
How i can solve this?
Use numeric literals with aliases inside a SELECT statement. No () are necessary around the SELECT component.
INSERT INTO qa_costpriceslog (item_code, invoice_code, item_costprice)
SELECT
/* Literal number values with column aliases */
1 AS item_code,
2 AS invoice_code,
item_costprice
FROM qa_items
WHERE item_code = 1;
Note that in context of an INSERT INTO...SELECT, the aliases are not actually necessary and you can just SELECT 1, 2, item_costprice, but in a normal SELECT you'll need the aliases to access the columns returned.
You can just simply e.g.
INSERT INTO modulesToSections (fk_moduleId, fk_sectionId, `order`) VALUES
((SELECT id FROM modules WHERE title="Top bar"),0,-100);
I was disappointed at the "all or nothing" answers. I needed (again) to INSERT some data and SELECT an id from an existing table.
INSERT INTO table1 (id_table2, name) VALUES ((SELECT id FROM table2 LIMIT 1), 'Example');
The sub-select on an INSERT query should use parenthesis in addition to the comma as deliminators.
For those having trouble with using a SELECT within an INSERT I recommend testing your SELECT independently first and ensuring that the correct number of columns match for both queries.
Your insert statement contains too many columns on the left-hand side or not enough columns on the right hand side. The part before the VALUES has 7 columns listed, but the second part after VALUES only has 3 columns returned: 1, 2, then the sub-query only returns 1 column.
EDIT: Well, it did before someone modified the query....
As a sidenote to the good answer of Michael Berkowski:
You can also dynamically add fields (or have them prepared if you're working with php skripts) like so:
INSERT INTO table_a(col1, col2, col3)
SELECT
col1,
col2,
CURRENT_TIMESTAMP()
FROM table_B
WHERE b.col1 = a.col1;
If you need to transfer without adding new data, you can use NULL as a placeholder.
If you have multiple string values you want to add, you can put them into a temporary table and then cross join it with the value you want.
-- Create temp table
CREATE TEMPORARY TABLE NewStrings (
NewString VARCHAR(50)
);
-- Populate temp table
INSERT INTO NewStrings (NewString) VALUES ('Hello'), ('World'), ('Hi');
-- Insert desired rows into permanent table
INSERT INTO PermanentTable (OtherID, NewString)
WITH OtherSelect AS (
SELECT OtherID AS OtherID FROM OtherTable WHERE OtherName = 'Other Name'
)
SELECT os.OtherID, ns.NewString
FROM OtherSelect os, NewStrings ns;
This way, you only have to define the strings in one place, and you only have to do the query in one place. If you used subqueries like I initially did and like Elendurwen and John suggest, you have to type the subquery into every row. But using temporary tables and a CTE in this way, you can write the query only once.