Update data in database using SQL - mysql

I have one table in my database. Field of table are describe below.
ID | NAME | QUALIFICATION
1 | ABC | Phd
2 | XYZ | MBA
3 | ADS | MBA
Now my problem is related to update QUALIFICATION record. Suppose if I update record of QUALIFICATION, it should be append new value to existing value.
For example, I am going to update record of id=1. Now I update "QUALIFICATION" MCA then it should add MCA to the existing record Phd, separated with comma. Output will looks like below.
ID | NAME | QUALIFICATION
1 | ABC | Phd,MCA
2 | XYZ | MBA
3 | ADS | MBA
When "QUALIFICATION" is null then the update should not be add comma before MCA.

Thats a bad database design never store the data as comma separated string, this will make things messy in future.
You should think of normalizing the table something as for the student your table should look like
- id primary key auto_incremented
- name
- other columns related to student
Then another table as student_qualification
- id primary key auto_incremented
- id_student ( id from student table)
- qualification
So for each student you can add as many qualification as possible to this table and can easily do add/edit/delete data
You can later easily retrieve data using simple joining the table.

first u have to select your existing value of Qualification column
that u want to update
Using
select qualification from tb_name where id = 1
Using above query u will get your qualification column value
suppose in
$qulification
Now update that row using
update set tb_name set qualification = '".$qualification."."your new value" where id = 1

May you can try this
update employee set qualification = qualification || ',MCA' where id = 1
the above will work in oracle
EDIT:
Then you can have the case statement with it
update employee set qualification = case when qualification is null then
'MCA' else qualification || ',MCA' end where id = 1

You can test for NULL in the SET clause, and use concatenation to format the string appropriately.
update student
set qualification = concat(if (qualification is not null
, concat( qualification, ',')
, '' )
, 'MBA')
where id = 1;
Here is a working SQL Fiddle (which also demonstrates behaviour with a NULL qualification).
I agree with #Abhik that this is a bad design for this specific data, and normalization is the better approach for the use case you provide However, there are other use cases where doing this sort of update would be perfectly valid so the question is worthy of a proper answer..

Related

How to implement Update Mechanism in MySql?

My Use Case :
I am trying to create a GUI and implement it with MYSQL Database. The problem I am facing is the scenario when I have to update a certain entry in the Database.
I know that we can update an Entry in MYSQL database using :
ALTER TABLE <TABLENAME> SET <PARAMETERS=NEW VALUES> WHERE <CONDITION> ;
For eg : If I want to change the name of the guy who id is 2 , I have to write :
ALTER TABLE StudentInfo SET Name='ABC' WHERE id=2 ;
But the problem is , in a GUI based environment , a user can choose to update any particular value wihtout having a constant condition like id in the previous example.
In the UI , the user can opt to select anything from the parameters and modify it and then click the update button.
Now How will I figure out what <CONDITION> to put in the MYSQL query when I need to update the database ?
Any help would be greatly appreciated !
you update a by using the UPDATE command not ALTER, which will change table. Your gui already knows ho tow identify the row in your case for example by the column name
UPDATE StudentInfo SET Name='ABC' WHERE Name='QUERTY';
SEE example
CREATE TABLE StudentInfo(
Name VARCHAR(20),
class int,
section VARCHAR(2),
roll_no int
);
INSERT INTO StudentInfo VALUES ('abc',12,'A',18), ('xyz',12,'A',17),('QUERTY',12,'A',16)
UPDATE StudentInfo SET Name='ABC',class = 15,section = 'B',roll_no= 99 WHERE Name='QUERTY';
SELECT * FROM StudentInfo
Name | class | section | roll_no
:--- | ----: | :------ | ------:
abc | 12 | A | 18
xyz | 12 | A | 17
ABC | 15 | B | 99
db<>fiddle here
The main problem is to identify the correct row, so you should have a field that is unique.
Like an id auto_increment, that is invisible for the user, but you can identify every row and use this id to update the row.
UPDATE StudentInfo SET Name='ABC' WHERE id = 3;
So that if you have two rows with John Smith you still could update the right one

how to check for multiple groups of values exists in same table from database?

This is my sqlfiddle
http://sqlfiddle.com/#!9/e443688/2
If I have a list of values:
a#test.com
b#test.com
c#test.com
And my table has a column called email I can run a query like
select email from datatable where email in ('a#test.com', 'b#test.com', 'c#test.com')
to find whether they exist.
However, if my list of values consists of at least 2 columns:
a#test.com, manager
b#test.com, editor
c#test.com, editor
And my table has two columns email and job_title, how do I run a query to check if there are rows that match the values I am searching for?
I don't want to know how many there are. I do want to know which value group exists.
Ideally if my query can return back something like this
email | job_title | exists
------|-----------|-------
a#test.com | manager | 1
b#test.com | editor | 0
c#test.com | editor | 1
Or just
email | job_title
------|-----------
a#test.com | manager
c#test.com | editor
That's good enough
What 'marekful' suggested is a pretty good option. If you are looking for an alternative way, here's another option:
select email
from datatable
where (email = 'a#test.com' and job_title = 'manager')
or (email = 'b#test.com' and job_title = 'editor')
or (email = 'c#test.com' and job_title = 'editor');
I used #marekful comment and concatenate the two values.
Also #Strawberry's suggestion works as well.
Here's the fiddle. http://sqlfiddle.com/#!9/e443688/3
And the query was
select id from emails where (email,job_title) in(('a#test.com','manager'),('b#test.com','editor'),('c#test.com','editor'))

How to generate a unique id based on different id category?

I have a table as shown below
| id | name | doc_no |
|:-----------|------------:|:------------:|
| 1 | abc | D11710001
| 2 | efg | D21710001
| 3 | hij | D31710001
| 4 | klm | D41710001
| 5 | nop | D51710001
| 1 | qrs | D11710002
I want to generate an unique id based on the id given. For example, when i have item to be stored in this table, it will generate an unique id based on the id of the table.
Note: The id in this table is a foreign key. The doc no can be modified by user into their own format manually.
The id format - D 'id' 'year' 'month' 0001(auto increment)
How can i write the sql to generate unique id during storing data?
Continuing with the comment by #strawberry I might recommend not storing the ID in your database. Besides the fact that accessing the auto increment ID at the same time you are inserting the record might be tricky, storing this generated ID would be duplicating the information already stored elsewhere in your table. Instead of storing your ID, just generate it when you query, e.g.
SELECT
id, name, doc_no,
CONCAT('D', id, STR_TO_DATE(date, '%Y-%m'), auto_id) AS unique_id
FROM yourTable;
This assumes that you would be storing the insertion date of each record in a date column called date. It also assumes that your table has an auto increment column called auto_id. Note that having the date of insertion stored may be useful to you in other ways, e.g. if you want to search for data in your table based on date or time.
You could create Trigger and update the column or you can write the update state just after your INSERT
insert into <YOUR_TABLE>(NAME,DOC_NO) values('hello','dummy');
update <YOUR_TABLE> set DOC_NO=CONCAT('D',
CAST(YEAR(NOW()) AS CHAR(4)),
CAST(MONTH(NOW()) AS CHAR(4)),
LAST_INSERT_ID())
WHERE id=LAST_INSERT_ID();
Please note, as above SQL may cause race condition, when simultaneously server get multiple requests.
#Tim Biegeleisen has good point though, as it is better to construct the id when you are SELECTing the data.

Update table row value to a random row value from another table

I have 2 MySQL tables.
One table has a column that lists all the states
colStates | column2 | column 3
------------------------------
AK | stuff | stuff
AL | stuff | stuff
AR | stuff | stuff
etc.. | etc.. | etc..
The second table has a column(randomStates) with all NULL values that need to be populated with a randomly selected state abbreviation.
Something like...
UPDATE mytable SET `randomStates`= randomly selected state value WHERE randomStates IS NULL
Can someone help me with this statement. I have looked around at other posts, but I don't understand them.
this works for me with trial data in SQLite:
UPDATE mytable
SET randomStates = (SELECT colStates FROM
(SELECT * FROM first_table ORDER BY RANDOM())
WHERE randomStates IS NULL)
without the first SELECT portion, you end up with the same random value inserted into all the NULL randomStates field. (i.e. if you just do SELECT StateValue FROM counts ORDER BY RANDOM() you don't get what you want).

sql loop to update data

Alright having a real tough time getting this working.
I have a database of employees. I am looking to better condition this data. By this i mean that many entries in the table have rows where the employee_sales_id is "?". Each employee can have multiple rows (each time they change jobs). For the same employee some entries have the employee_sales_id while others don't. I want to scan my table and update all "?" where the value can be picked out from another row. The Employee_id is unique for each employee.
DB Looks like this:
Employee_id | employee_sales_id | name
1234 | abc | Jim Smith
1234 | abc | Jim Smith
1234 | ? | Jim Smith
1234 | abc | Jim Smith
You see the 3rd row. I want to fix that and update it with abc. There are many employees so i cant do this manually. It has to be a sql script. Also would be great to have it process the data on insert.
UPDATE employee
JOIN
(SELECT employee_id,employee_sales_id FROM employee
GROUP BY employee_id
HAVING COUNT(employee_sales_id)>1
AND employee_sales_id!='?')x
ON employee.employee_id=x.employee_id
SET employee.employee_sales_id=x.employee_sales_id
WHERE employee.employee_sales_id='?'
SQL FIDDLE
Try
UPDATE employee
SET Employee_sales_id = ES.employee_sales_id
FROM
(SELECT DISTINCT Employee_id, employee_sales_Id
FROM Employee
where employee_sales_id <> '?') ES
INNER JOIN Employee E on E.Employee_id = ES.Employee_id
WHERE E.employee_sales_id = '?'
By the way I assume you have some sort of primary key and/or further attributes on the Employee table that we are not seeing in your question text otherwise you have duplicate rows in your table which are going to cause problems for you somewhere.
Update
Sorry, I'm using Sql Server. Did not see your question related to MySql.
Try:
update employees x join (select employee_id,
min(employee_sales_id) as good_id,
jobcode,
job_start_date
from employees
where employee_sales_id <> '?') y on x.employee_id = y.employee_id
and x.jobcode = y.jobcode
and x.job_start_date = y.job_start_date
set x.employee_sales_id = y.employee_sales_id
where x.employee_sales_id = '?'
If the employee_sales_id changes over time, then you would want the row with the ? to be populated with the last employee_sales_id value for the given employee_id where the job is the same as the current job and start date, I assume.