Swap data in two columns using single sql query - sql

User has entered data in wrong columns.
For example, I have a table with two columns applicant name and father name. Data operator has entered father name in applicant name column and applicant name in father name column. Please suggest a way to swap the data in both columns i.e data in applicant name column should move to father name column and data in father name column should move to applicant name column. Using single sql query

It may sounds funny, But you can easily alter the table and change the column name with correct labeling.

CREATE TABLE `swap_test` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`x` varchar(255) DEFAULT NULL,
`y` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB;
INSERT INTO `swap_test` VALUES ('1', 'a', '10');
INSERT INTO `swap_test` VALUES ('2', NULL, '20');
INSERT INTO `swap_test` VALUES ('3', 'c', NULL);
Solution would be :
UPDATE swap_test SET x=(#temp:=x), x = y, y = #temp;
More info can be found here.

You can simply assign the names
update the_table
set applicant_name = father_name,
father_name = applicant_name
where ...; -- make sure to only do that for the rows that need it
The SQL standard requires that the values used on the right side are evaluated before the assignment.
This works with every modern DBMS, but not with MySQL. See dexter's answer if you need a workaround for MySQL.
Online example: https://rextester.com/RIK34525

Related

I need to validate data in a Table where 1 column has multiple values but 1 value can only be present in 1 row by unique key

Example:
A table Keyed by Unique Name and Email Address with a column for Type
The Type column can have Original, Work, Personal
where you can have multiple work and personal emails but only 1 Original email
I am using DB2 for i SQL and I want to constrain the data using UNIQUE or CHECK constraints but not sure how I can do this data set.
Scott scott#hotmail.com Original
Scott scott#gmail.com Personal
Scott scott#live.com Personal
Scott scott#NBC.com Work
Scott scott#ABC.com Work
Scott scott#yahoo.com Original
I want to identify that I cant have yahoo as Original if I already have hotmail as original.
the rest are valid.
Let me know if I need to add more.
If you have Db2 for IBM i, then you may create a UNIQUE INDEX with the corresponding WHERE clause.
CREATE TABLE TEST_IND_EXPR
(
NAME VARCHAR (20) NOT NULL
, EMAIL VARCHAR (20) NOT NULL
, TYPE VARCHAR (20) NOT NULL
);
CREATE UNIQUE INDEX TEST_IND_EXPR1 ON TEST_IND_EXPR (NAME, EMAIL);
CREATE UNIQUE INDEX TEST_IND_EXPR2 ON TEST_IND_EXPR (NAME, TYPE) WHERE TYPE = 'Original';
INSERT INTO TEST_IND_EXPR VALUES ('Scott', 'scott#hotmail.com', 'Original');
INSERT INTO TEST_IND_EXPR VALUES ('Scott', 'scott#gmail.com', 'Personal');
INSERT INTO TEST_IND_EXPR VALUES ('Scott', 'scott#live.com', 'Personal');
INSERT INTO TEST_IND_EXPR VALUES ('Scott', 'scott#yahoo.com', 'Original');
The last statement returns SQL0803 as this row violates uniqueness of the TEST_IND_EXPR2 index.

How to make the default selection of a value in sql out of multiple choices?

I have a column in my SQL table i.e. Gender and there can be one of two possible values for it, 'M' and 'F'.
For those values, I am able to pass two values by using a check constraint as option when creating the table:
Gender varchar(6) CHECK (Gender IN ('M', 'F'))
Also, one of those value is defined as the default:
Gender varchar(6) DEFAULT 'M'
But here, if I am trying to merge those two queries while table creation, I am not getting the output. I want to pass two choices for column value and default as 'M'.
Both can be used as part of the create table syntax:
create table t(gender char(1) default('M') check(gender in ('M','F')));
Demo Fiddle
You can easily use both in the CREATE TABLE statement - and preferably, define explicit names for your constraints!
CREATE TABLE Person
(
FirstName VARCHAR(50) NOT NULL,
LastName VARCHAR(50) NOT NULL,
Gender CHAR(1) NOT NULL
CONSTRAINT CHK_Person_Gender CHECK (Gender IN ('M', 'F'))
CONSTRAINT DF_Person_Gender DEFAULT ('M')
)

Copying two columns from a foreign table into another table

INSERT INTO Confirmed (TotalDeaths, Population)
SELECT TotalDeaths, Population
FROM Deaths
WHERE UID IS NOT NULL;
Copy the values for the columns named TotalD and Pop from the Deaths Table to the Confirmed Table (same names, both contains UID primary Key)
Failed to execute query. Error:
Cannot insert the value NULL into column 'UID', table 'dbo.Confirmed'; column does not allow nulls. INSERT fails. The statement has been terminated.
I keep running into a problem where I get compiler errors due to the primary key not allowing nulls. I'm not sure where the null keys are even coming from when it shouldn't be null to begin with.
Both tables have very similar columns, but in this case all that needs to be mentioned is that there are three columns in both tables that are crucial, which are: UID int NOT NULL, TotalDeaths int NOT NULL, Population int NOT NULL.
Seems to be UID is not null column. Use below query
INSERT INTO Confirmed (UID, TotalDeaths, Population)
SELECT UID, TotalDeaths, Population
FROM Deaths
WHERE UID IS NOT NULL;

How to specify two value as DEFAULT on a column by shuffling between two values on any insertion

I have a table called user_profile with these three columns. What i am trying to do is when i don't specify any value for cover_pic column then it must insert the default random value from the given two values.
Like example sometime it insert ABC.png as default value and sometime XYZ.png.
CREATE TABLE user_profile(
profileId int(11) NOT NULL AUTO_INCREMENT,
profile_pic VARCHAR(200) DEFAULT "profile.png",
cover_pic VARCHAR(200) DEFAULT RAND("ABC.png","xyz.png"),
CONSTRAINT pk_profileId PRIMARY KEY(profileId)
)ENGINE=InnoDB DEFAULT CHARSET=latin1;
This is not possible with the DEFAULT on the table directly. But you can use a TRIGGER to set a random picture filename to the column cover_pic if NULL:
CREATE TRIGGER insert_cover_pic BEFORE INSERT ON user_profile
FOR EACH ROW
SET NEW.cover_pic = IF(NEW.cover_pic IS NULL, ELT(FLOOR(RAND()*2)+1, 'pic1', 'pic2'), NEW.cover_pic);
Using this TRIGGER you can use a INSERT INTO without specify the column cover_pic (or using NULL on column cover_pic):
INSERT INTO user_profile (profile_pic) VALUES ('test.png');
INSERT INTO user_profile (profile_pic, cover_pic) VALUES ('test.png', NULL);
demo on dbfiddle.uk

How do I select insert into select a table which already has values in the primary key column without adding new rows?

I'm working on a database for my school project in which I have to produce a functional database by normalizing sample tables given to us.
One table I'm having trouble with is itineraries. I produce 3 tables from the normalization which are "Destinations", "Itineraries" and "Itinerary_Destinations".
The code for Destinations is:
create table Destinations
(
DestinationID varchar(5) primary key,
Name varchar(45)
);
The code for Itineraries is:
create table Itineraries
(
ItineraryID varchar(5),
Name varchar(45)
);
The code for the last table is:
create table Itinerary_Destinations
(
DI varchar(5) primary key,
ItineraryID varchar(5) foreign key references Itineraries(ItineraryID),
Itinerary_Name varchar(45),
DestinationID varchar(5) foreign key references Destinations(DestinationID),
Destination_Name varchar(45)
);
Data has already been inserted into all 3 tables with the exception of 'Destination_Name' and 'Itinerary_Name' columns. The code I'm attempting to use is returning as error. The code is shown below.
insert into Itinerary_Destinations (Itinerary_name)
select Name from Itineraries where
Itineraries.ItineraryID = ItineraryID;
The error it returns is
Msg 515, Level 16, State 2, Line 1 Cannot insert the value NULL into
column 'DI', table 'DDDAssignment.dbo.Itinerary_Destinations'; column
does not allow nulls. INSERT fails. The statement has been terminated.
Is there a method to accomplish the task of inserting the Destination_Name and Itinerary_Name without creating new records that require primary keys?
Or should I do it manually?
If you want to modify records which already exist, then you should be using an UPDATE rather than an INSERT:
UPDATE a
SET Itinerary_name = b.Name
FROM Itinerary_Destinations a
INNER JOIN Itinerary_name b
ON a.ItineraryID = b.ItineraryID;
But, if you do have some data which is not already logically associated with the Itinerary_Destinations table, then using an insert is appropriate.
use coalesce funtion in case null it will insert blank string, as your column does not allow null value thats why you got that error in your query
insert into Itinerary_Destinations (Itinerary_name)
select coalesce(Name,' ') from Itineraries where
Itineraries.ItineraryID = ItineraryID;