Sorry about asking the basics. I am trying to make a new column named new_column as in the code below while keeping the old_column as well. When I run the below query, I do get the results printed out fine on the console, but failed to insert the results to the new_column.
I tried both ways, first creating a column named new_column (empty) and then run the query, and secondly just running the query as below. Both didn't return new_column inserted with integer values. What am I missing?
SELECT old_column CASE
WHEN 'A' THEN 1
WHEN 'B' THEN 2
WHEN 'C' THEN 3
ELSE 0
END AS new_column
FROM table_name
Your syntax is wrong, and doesn't produce anything except an error message as you've written it here.
If I understand your question correctly, this should produce the output you want:
SELECT
old_column,
CASE old_column
WHEN 'A' THEN 1
WHEN 'B' THEN 2
WHEN 'C' THEN 3
ELSE 0
END AS new_column
FROM
table_name
A SELECT does exactly what it says it does - it selects the data, but doesn't actually alter it's content.
To permanently add a new column and populate it, you'll need to first ALTER TABLE to add the new column, and then UPDATE that new column's content.
ALTER TABLE table_name ADD COLUMN newcolumn integer;
UPDATE
table_name
SET newcolumn = CASE oldcolumn
WHEN 'A' THEN 1
WHEN 'B' THEN 2
WHEN 'C' THEN 3
ELSE 0
END;
For future reference: If you want help with your SQL syntax, include the actual code you've tried that isn't working, instead of inventing something as you go or re-typing. With SQL-related questions, it's almost always a good idea to post some sample data and the output you'd like to obtain from that data, along with your actual SQL code trying to produce that output. It makes it much easier to help you when we can understand what you're trying to do and have samples to use.
Related
I've added a new column to the ls_customer table that goes by response_category. I then set an update code to it.
ADD statement:
ALTER TABLE ls_customer
ADD response_category VARCHAR(255)
UPDATE Statement:
UPDATE ls_customer SET response_category = 'Hot Lead' WHERE flag = 3
UPDATE ls_customer SET response_category = 'Warm Lead' WHERE flag = 2
How do I set the above "UPDATE" statement to auto update whenever the flags change in our internal CRM tool?
I then use a SELECT statement to present this data. The problem is this "SELECT" statement is linked to my Tableau analytics. Everytime I refresh Tableau, if there's any changes in the flag, the response category doesn't get updated in the final SELECT statement untill I manually open MySQL and run the above "UPDATE" query again.
The SELECT statement is as follows:
SELECT
cell_phone,full_name,company_name,DATE(date_join),
response_type,response_category,ls_customer.tags AS lead_type,ls_lead_stats_raw_data.last_update,date_join,source
FROM ls_lead_stats_raw_data
INNER JOIN ls_customer
ON ls_lead_stats_raw_data.client_id = ls_customer.customer_id
INNER JOIN ls_company
ON ls_company.company_id = ls_customer.company_id
How do I automate the UPDATE statement to set response_category to 'Hot Lead', 'Warm Lead' everytime I change the flags in our CRM?
Despite mysql version number, there are many different ways you can solve this issue, such as:
creating a before update trigger on your table updating response_category column based on flag column content. But, maybe your CRM already use triggers and will not allow you to add any code to them
creating an database event executed every minute and updating the response_category column. this solution is not the most effective as it will execute the event, even nothing has changed in the flag column.
you can create a reference table with the flag and the response_category columns. It's content would be :
flag
response_category
2
warm lead
3
hot lead
You add this new table with a join on ref_table.flag = ls_customer.flag to your select (replace response_category by ref_table.response_category). But this solution is so obvious, that I think there is a good reason you didn't use it.
So finally I would recommend to use a generated column instead of a regular column for response_category:
ALTER TABLE ls_customer
ADD COLUMN response_category VARCHAR(255) GENERATED ALWAYS
AS (CASE flag WHEN 2 THEN 'Hot lead' WHEN 3 THEN 'Warm lead' END)
STORED ;
Using STORED option will allow you to add an index on this column in case you need to improve your SELECT performance.
Hope this will help.
I am trying to write this below statements in case statements. Trying to update a value in one different TableB for a particular column.
After I do
Update a
set DISMMR =
then trying to check this below condition in case statements
'H01' Is not NULL
and
('H02','H03','HR04','S07','S08','S09') Is NULL
Then 'Unknown'
Here this values are from table name : TableA and column name is Code.
This particular column is designed to be NOT NULL
Here where I say Is NULL means I am trying to say that, this particular value ('H02','H03','HR04','S07','S08','S09') don't exist or present in TableA.
When I say this particular value H01 in TableA for column Code ---- Is not NULL -- means this particular value of column Code exist/present in a column from TableA.
I need to do this one in case statements because once I am done checking this condition , I am writing other case statements started with WHEN to check another condition and update with different value
I am using SQL Server 2008 R2. Now I wrote the below query. It runs fine in SSMS but when i use this Store procedure in SSIS package. My package fails with error.
[Execute SQL Task] Error: Executing the query "execute [dbo].[usp_GetMRF_CHP] ?,?,?" failed with the following error: "Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly
CASE WHEN EXISTS(SELECT 1 FROM dbo.TableA WHERE Code = 'H01')
AND NOT EXISTS(SELECT 1 FROM dbo.TableA
WHERE Code IN ('H02','H03','HR04','S07','S08','S09')
)
THEN 'Unknown'
when ---- I have another case here.
Any help will be very much appreciated. Thanks in advance
If I understand you correct you want to know if a record with Code = 'H01' exists while no record with the other codes exist. The case statement for that would look like this:
CASE WHEN EXISTS(SELECT 1 FROM dbo.TableA WHERE Code = 'H01')
AND NOT EXISTS(SELECT 1 FROM dbo.TableA
WHERE Code IN ('H02','H03','HR04','S07','S08','S09')
)
THEN 'Unknown'
END
I have created a MySQL Trigger BEFORE INSERT on table name agent_mst as below
BEGIN
DECLARE max_id INT;
SET max_id=(SELECT MAX(agent_id_pk)+1 FROM `agent_mst`);
IF (max_id IS NULL) THEN
SET max_id=1;
END IF;
SET NEW.date_added=NOW(),
NEW.date_updated=NOW(),
NEW.agent_code = CONCAT('SDA', LPAD(max_id, 4,'0'));
END
So what it does is, every time we inset a record, it generates agent_code field value to something like SDA0001, SDA0002, SDA0003, ...
Now suppose I delete a record with code SDA0003 and insert new record, it will definitely generate the agent code as SDA0004. As it is taking the max_id and increasing it with 1. But here I want to get SDA0003 again. So that all agent_codes can stay in sequence. How to do that?
Thanks in advance.
you need to identify the first (smallest) missing id.
check out in this link, a nice way to do it in a select query:
Find mininum not used value in mysql table
To know next auto increment id try to run below query and check column "Auto_increment":
SHOW TABLE STATUS FROM DBName where name = 'tableName'
Is it possibile to have a mysql UNIQUE index on a varchar field not based on the words order?
I mean if there is a row with key1 key2, and I try to insert key2 key1 mysql should throw an error.
You could achieve this effect by adding before insert and before update triggers to the table; they could check whether a row with the fields reversed exists or not before inserting/updating if it doesn't, or forcing an error if it does.
See here for more information.
If you set the indexed to UNIQUE, you will not be able to enter the identical data twice - numbers, words or otherwise.
If you wish to achieve something otherwise, you'll have to set a new non-unique field in your database then you'll be able achieve it using external code and queries (PHP, C#).
Create a trigger to do this.
i.e.
CREATE TRIGGER trigger_name BEFORE INSERT ON table_name
FOR EACH ROW
BEGIN
IF ((SELECT COUNT(*) FROM table WHERE col2=NEW.col1 OR col1=NEW.col2) <> 0)
THEN
CALL this_procedure_does_not_exist();
END IF
END
I have a need for unique identifiers in my application. To that end, I created a table in my database that only contains 1 column 'unique_id" (BIGINT) and 1 row.
The idea is to use a stored procedure to get the next identifier when I need it. I figured a 1-line operation like this would do the job:
UPDATE identifier_table SET unique_id = unique_id + 1 OUTPUT INSERTED.unique_id
Can someone confirm if this operation is atomic, or do I need to setup a lock on the table?
Thanks!
It is atomic. It is just a single update statement, and will have no problem at all with concurrency since that will be managed by the engine with update locks. You can use OUTPUT as shown, or you can do something like this:
DECLARE #unique_id bigint;
UPDATE identifier_table
SET
#unique_id = unique_id + 1,
unique_id = unique_id + 1;
SELECT #unique_id uniqueid;
If you make #unique_id an OUTPUT parameter, then you can get the value without a select statement or use it easily in another stored procedure.