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

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

Related

Swap data in two columns using single sql query

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

SQL Server Insert with no specified columns

I have a table with an auto-generated ID column (and that's all!)
CREATE TABLE [dbo].[EmailGroup](
[EmailGroupGuid] [uniqueidentifier] NOT NULL
CONSTRAINT [PK_EmailGroup] PRIMARY KEY CLUSTERED ([EmailGroupGuid] ASC)
) ON [PRIMARY]
ALTER TABLE [dbo].[EmailGroup]
ADD CONSTRAINT [DF_EmailGroup_EmailGroupGuid] DEFAULT (newsequentialid()) FOR [EmailGroupGuid]
I want to INSERT into this table and extract the generated ID. but, I can't work out if it's possible. It seems to complain about the lack of values/columns.
DECLARE #Id TABLE (Id UNIQUEIDENTIFIER)
INSERT INTO EmailGroup
OUTPUT inserted.EmailGroupID INTO #Id
Is there any way to do this? I mean I could add a dummy column to the table and easily do this:
INSERT INTO EmailGroup (Dummy)
OUTPUT inserted.EmailGroupID INTO #Id
VALUES (1)
however I don't really want to.
I could also specify my own ID and insert that, but again, I don't really want to.
Though I'm not sure why would you need such a table, the answer to your question is to use the keyword DEFAULT:
INSERT INTO EmailGroup (EmailGroupGuid)
OUTPUT inserted.EmailGroupGuid INTO #Id
VALUES(DEFAULT);
Another option is to use DEFAULT VALUES, as shown in Pawan Kumar's answer.
The key difference between these two options is that specifying the columns list and using the keyword default gives you more control.
It doesn't seem much when the table have a single column, but if you will add columns to the table, and want to insert specific values to them, using default values will no longer be a valid option.
From Microsoft Docs on INSERT (Transact-SQL):
DEFAULT
Forces the Database Engine to load the default value defined for a column.
If a default does not exist for the column and the column allows null values, NULL is inserted.
For a column defined with the timestamp data type, the next timestamp value is inserted.
DEFAULT is not valid for an identity column.
DEFAULT VALUES
Forces the new row to contain the default values defined for each column.
So as you can see, default is column based, while default values is row based.
Please use this.
CREATE TABLE [dbo].[EmailGroup]
(
[EmailGroupGuid] [uniqueidentifier] NOT NULL CONSTRAINT [PK_EmailGroup] PRIMARY KEY CLUSTERED ([EmailGroupGuid] ASC)
) ON [PRIMARY]
ALTER TABLE [dbo].[EmailGroup]
ADD CONSTRAINT [DF_EmailGroup_EmailGroupGuid] DEFAULT (newsequentialid()) FOR [EmailGroupGuid]
DECLARE #Id TABLE (Id UNIQUEIDENTIFIER)
INSERT INTO EmailGroup
OUTPUT inserted.EmailGroupGuid INTO #Id DEFAULT VALUES
SELECT * FROM #Id
last 3 OUTPUTs from my Laptop
--92832040-7D52-E811-B049-68F728AE8695
--2B6ADC5F-7D52-E811-B049-68F728AE8695
--0140AF66-7D52-E811-B049-68F728AE8695

NULL constraint after attribute in CREATE TABLE?

I'm new to SQL and I'm trying to figure out what this NULL is doing. Here a simple example:
CREATE TABLE test (
bla VARCHAR NULL
);
So I tried to figure out wether this is set to be the default value, but it is null as default wether I put it there or not, right?
Also I wondered if it has to stay null (for whatever reason) but when I tried to insert a value it was possible anyway. So does it do anything?
From CREATE TABLE:
NULL
The column is allowed to contain null values. This is the default.
You could write:
INSERT INTO test(bla)
VALUES (NULL);
-- it holds NULL
INSERT INTO test(bla)
VALUES (default);
-- it holds NULL
INSERT INTO test(bla)
VALUES ('a');
-- it holds 'a'
You could also omit column:
CREATE TABLE test2(bla VARCHAR NULL, col2 INT NOT NULL);
INSERT INTO test2(col2) VALUES (1);
-- it contains NULL, 1
If you specify column as:
CREATE TABLE test(bla VARCHAR NOT NULL);
INSERT INTO test(bla) VALUES (NULL);
-- error
EDIT:
You don't have to specify NULL explicitly.
CREATE TABLE test(bla VARCHAR);
is the same as:
CREATE TABLE test (bla VARCHAR NULL);
You are parameterizing the column can be NULL

default column value

i'm trying to have a table with a column that has a default value.
right now i can only get this by having a trigger change the value to the default, is it possible to have it declared on the table right from the start?
Would it be possible to have something like the Identity, where i don't have to pass the value into the insert?
egx: insert into Direct values(2)
and the table would become
id | item
1 | 2
the id = 1, would be the deafult value
thanks in advance!
you can create constraints at time of table creation or later.
create table
#test
(
id int identity(1,2),
name char(255) default newid(),
code int default 2
)
---if a table contains all default values,you can insert like below
insert into #test
default values
updated as per comments:
create table
#test1
(
id int identity(1,2),
name char(255) default newid(),
code int default 2,
notdf int
)
---if a table contains one default value and rest all are default
insert into #test1(notdf)
select 2
Further if you want to add a default value after table creation you can do it like below
create table
tt1
(
valuue int,
address char(2) not null
)
insert into tt1
select 1,'a'
ALTER TABLE tt1 ADD CONSTRAINT test1 DEFAULT null FOR address;
Use default. You can change an existing column by doing:
ALTER TABLE t ADD CONSTRAINT df_t_column DEFAULT 1 for id;
An identity is trickier. I would suggest copying the data over to a temporary table, dropping the table, creating it with an identity column and reloading the data.

SQL Server - Default value

I don't know if this is possible, but i would like to know if when we create a table on which a field has a default value, we can make this Default value get the value of another column upon row insertion.
Create Table Countries (
ID Int Not Null Identity(1,1),
CountryCode Char (2) Not Null,
Country Varchar (50) Not Null,
CountryRegion Varchar (50) Null Default ('Country'),
Nationality Varchar (75) Not Null Default ('Not Known'),
InsertDate Datetime2 Not Null Default Getdate(),
Constraint PK_CountryCode Primary Key (CountryCode));
On CountryRegion field, I could place an ('Unknown') default value, but like I said, is it possible this field gets by default the value inserted on Country field if nothing is placed on it?
Using a trigger would do - UPDATE a column right after insertion
CREATE TRIGGER CountriesTrigger ON Countries AFTER INSERT
AS
BEGIN
SET NOCOUNT ON
UPDATE Countries
SET
Countries.CountryRegion = inserted.Country
FROM Countries, inserted
WHERE Countries.ID = inserted.ID
AND inserted.CountryRegion is null
END
I think there is no easy of doing this at TABLE level. There are some workarounds to do this :
1. If you are using stored procs then you can write your logic over there.
2. Trigger is also an option but overhead in terms of execution.
Thanks.