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

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')
)

Related

How to prevent a input of certain letters using Oracle

The code is the category of the video, it is represented by one upper case character, excluding I, O,
Q, V, Y and Z, followed by a numeric character.
So far, I took a guess and got this. Any suggestions on how to fix it?
create table channelTable (
channelID number NOT NULL,
ChannelName varchar(100) NOT NULL,
ChannelDate date NOT NULL,
UserName varchar(100) NOT NULL UNIQUE,
TopicCode varchar(4) NOT NULL);
CONSTRAINT channelID_pk PRIMARY KEY (channelID)
CONSTRAINT c_topicCode LIKE '[A-Za-z][0-9] NOT (I,O,Q,N,Y,Z)
);
Some comments:
NOT NULL is not needed for PRIMARY KEY columns.
In Oracle, use VARCHAR2().
Then, I would suggests regular expressions. If the value is supposed to be exactly two characters, then declare it as such:
create table channelTable (
channelID number,
ChannelName varchar(100) NOT NULL,
ChannelDate date NOT NULL,
UserName varchar2(100) NOT NULL UNIQUE,
TopicCode char(2) NOT NULL;
CONSTRAINT channelID_pk PRIMARY KEY (channelID)
CONSTRAINT check (REGEXP_LIKE(c_topicCode, '^[A-HJ-NPR-UYZ][0-9]$')
);
Or perhaps more simply:
CONSTRAINT REGEXP_LIKE(c_topicCode, '^[A-Z][0-9]$') AND NOT REGEXP_LIKE(c_topicCode, '^[IOQNYZ]'))
All that said, I would rather see a table of TopicCodes that is populated with the correct values. Then you can just use a foreign key relationship to define the appropriate codes.
Use the regular expression ^[A-HJ-MPR-X]\d$ to match an upper-case character excluding I,O,Q,N,Y,Z followed by a digit:
CREATE TABLE channels (
id number CONSTRAINT channel__id__pk PRIMARY KEY,
Name varchar(100) CONSTRAINT channel__name__nn NOT NULL,
DateTime date CONSTRAINT channel__date__nn NOT NULL,
UserName varchar(100) CONSTRAINT channel__username__NN NOT NULL
CONSTRAINT channel__username__U UNIQUE,
TopicCode varchar(4),
CONSTRAINT channel__topiccode__chk CHECK ( REGEXP_LIKE( topiccode, '^[A-HJ-MPR-X]\d$' ) )
);
db<>fiddle
Also, you don't need to call the table channeltable just call it channels and you don't need to prefix the column names with the table name and you can name all the constraints (rather than relying on system generated constraint names which makes it much harder to track down issues when you are debugging).
Consider the following check constrait:
create table channelTable (
...
topicCode varchar(4) not null
check(
substr(c_topicCode, 1, 1) not in ('I', 'O', 'Q', 'V', 'Y', 'Z')
and regexp_like(topicCode, '^[A-Z]\d')
),
...
);
The first condition ensures that the code does not start with one of the forbidden characters, the second valides that it stats with an upper alphabetic character, followed by a number.
To avoid using two conditions, an alternative would be to list all allowed characters in the first position:
check(regexp_like(topicCode, '^[ABCDEFGHJKLMNPRSTUVWX]\d'))
This works in Oracle, and in very recent versions of MySQL.

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 2014 : help creating tables

I am new to MSSQL 2014 Server, my professor listed these steps to make a table, I don't know the proper steps to create tables in the pictures listed below, please help.
Create and populate (insert values) the following tables per table description and data values provided
DEPARTMENT
EMPLOYEE
PROJECT
ASSIGNMENT
Add a SQL Comment to include /* * Your First Name_Your Last Name* */ when inserting corresponding values for each table.
What I tried so far:
CREATE TABLE DEPARTMENT(
DepartmentName Text(35) PRIMARY KEY,
BudgetCode Text(30) NOT NULL,
OfficeNumber Text(15) NOT NULL,
Phone Text(12) NOT NULL, );
I have put this to my query and the error is
Msg 2716, Level 16, State 1, Line 1 Column, parameter, or variable #1: Cannot specify a column width on data type text.
Try this(I assume that your table exists in dbo schema):
IF OBJECT_ID(N'dbo.DEPARTMENT', N'U') IS NOT NULL
BEGIN
DROP TABLE DEPARTMENT
END
GO
CREATE TABLE DEPARTMENT(
DepartmentName varchar(35) PRIMARY KEY,
BudgetCode varchar(30) NOT NULL,
OfficeNumber varchar(15) NOT NULL,
Phone varchar(12) NOT NULL
);
You can not define width for Text data type. In case which you need to define width you can use char or varchar data types. Also keep in mind that if you need to work with Unicode characters then you will need to use nchar or nvarchar instead.

SQL constraint “at least one of two attributes”

I need to create a table User with telephone_number and e_mail_adress columns. Each row must have at least one of those columns set. It could have both or just one, but it must have at least one of them.
How can I express that constraint in SQL?
create table Users (
/* Whatever */
TelephoneNumber varchar(2000) null,
EmailAddress varchar(5) null,
constraint CK_AtLeastOneContact CHECK (
TelephoneNumber is not null or
EmailAddress is not null
)
)
You may want to adjust the data types :-)

SQL SVR 08 R2 Limit a field to specific values

For example, say I have field 'Gender' and I want to allow only the values Male, Female or Unisex. Is this possible in the SQL server management studio?
Update: So far the solution is pointing towards the 'Check constraints' function which can be found by right-clicking on the desired column.
Still, I'm getting syntax errors. Any thoughts on how I should type up the constraint?
Answer: Turns out I just needed to type it likes this
Gender = 'Male' OR Gender = 'Female' OR Gender = 'Unisex'
Unlike MySQL, MSSQL doesn't have ENUM data type. The only want you can do this is to trap the value in the application level. Or by using CHECK constraint
ColumnName varchar(10)
CHECK(ColumnName IN ('Male', 'Female', 'Unisex'))
DEFAULT 'Unisex'
You could do the following:
- Create another table and create a one to many relationship from the primary table to the Gender.
- Create an constraint like the following one:
CREATE TABLE Person
(
Id int NOT NULL,
Gender varchar(200)
CONSTRAINT chk_Gender CHECK (Gender IN ('Male', 'Unisex', 'Female'))
)