Interview: How to handle SQL NOT NULL constraint on the code end - sql

I was recently asked this question in an interview an I'm having trouble formulating the question well enough to find an answer via search engine.
If my SQL database has a NOT NULL constraint placed on the "name" column, how would I be able to create that row, filling it with other data, without tripping the "name" NOT NULL constraint, assuming that you don't have the proper data to insert into the "name" field?
My off the cuff response was to insert an empty string into the "name" field, but I feel like that's too hacky. Does anyone know the proper response?

It's usually a best practice to insert a dummy value such as a -1 that you can easily replace later. A blank string can be more problematic in some cases. To do this you would either use a CASE WHEN statement, or ideally, an ISNULL() function which would look like this ISNULL([ColName], -1) ISNULL is probably the answer they were looking for. That would insert the data if you have it and then if it's null, it would insert a -1.
As Gordon commented, you could also use a DEFAULT value when creating the table. In my answer above, I am assuming you're working with a table that had already been created - meaning you couldn't do that without altering the table.

There are two ways that I can think of for not having to insert name if it is NULL. By far the simpler is to define a default value:
alter table t alter column name varchar(255) not null default '<no name>';
The alternative is to use a trigger, but that is much more cumbersome.
If I were asking a similar question, this is the answer that I would want.

Why bypass the constraint?
In my opinion either your data is wrong or the constraint.
If you bypass constraints, you can't assure some data quality inside the db.
So, i would say the scenario where a table could not be changed even if the constraint is wrong is a huge technical debt which should be solved instead.

Related

Update a field only if it is empty in SQL Server 2005?

i have column which is not mandatory up to now, now it becomes a mandatory field and an unique field, now it contains empty. now i want update that field. i am in quite confusion to do that.see the below picture.update the segment_NO with out dupicates
the answer should be like this
You can write the update query in a loop which test for null condition.
I think you need to add some details to the question.
Still you can use simple INSERT query to insert in the table or either you can use Update query to update a record.
http://msdn.microsoft.com/en-us/library/8hwekas8%28v=vs.80%29.aspx
Refer this URL for further reference.
Kindly specify the issue bluntly and with out any confusions.. Well somewhat i can understand is... You should update your DB table and make a primary key of two columns in composite style..
Hopefully this will be answer for your question

I am stuck on creating constraint on SQL Server

I am totally new to SQL Server management, I tried to add a constraint in a table.
The situation is that I created a column with only 'Y'or 'N' allowed to be valued.
So I tried to create a constraint in Management Studio by right clicking "Constraints" in the table.
However, I really have no idea about the syntax of creating a constraint. Finally, I tried to input the code into "Check Constraint Expression" window by referring the template from the Internet. The SQL Server always tell me "Error Validating constaint".
Can you guys just help me to write the first constraint for me? Because I really dont know how to start.
My requirement is:
I have a table called "Customer"
I created a column called "AllowRefund"
The column "AllowRefund" is only allowed to 'Y' or 'N'
Thanks.
I'd advise against what you are trying to do. There is a datatype (Bit) that is designed to represent values with two states. If you use this type you won't even need the constraint at all. SQL Server will enforce the value to be either one or zero with no additonal work required. You just have to design your app to treat 1 as yes, and 0 as No.
The approach you are attempting is just not a good idea and no good will come of it.
You can do this as follows:
ALTER TABLE Customer
ADD CONSTRAINT CK_Customer_AllowRefund
CHECK (AllowRefund in ('Y','N'))
However #JohnFx is correct - you'd be better off making this column a bit field.
I partly agree with JohnFix, but as knowing the correct syntax to define a check constraint might be useful for you in the future (as you apparently don't read manuals), here is the SQL to create such a constraint:
alter table customer
add constraint check_yes_no check (AllowRefund in ('Y', 'N'));
You probably want to also define the column as NOT NULL in order to make sure you always have a value for that.
(As I don't use "Management Studio" I cannot tell you where and how you have to enter that SQL).

Limit column value to 0 or to be unique on insert

I have a table where a int column should either be set to zero or to a value which does not already exist in the table. Can I prevent inserting non zerod duplicated values in such column with a CHECK CONSTRAINT or should I use a BEFORE INSERT trigger? in case I could do this with both, what design is better?
From the .NET windows forms application we are using a global transaction scope to wrap the save and in both cases I would like the insert to fail and the transaction to roll back completely so I don't know if I should put the rollback inside the trigger, that's why I would rather try with a check if possible.
Database: SQL 2008
Thanks.
See the link in Andriy M's comment, it mention a 2008 new concept : filtered index...
CREATE UNIQUE INDEX indexName ON tableName(columns) INCLUDE includeColumns WHERE columnName != 0
This will create an index of unique items that are not 0.
Any attempt to insert a duplicate non-zero value will breach the uniqueness of the index and cause an error.
why are you using zero instead of null.? If you had it as null then the db would handle it for you easily via a nullable unique constraint..
Check constraint, when used properly, prevent bad data. They do not change the bad data to good. For that reason, I would aim for a trigger instead. If you can get around the need for a 0 as NULL, you could use a unique constraint, but supplying the answer would be the job of a trigger regardless.

MySQL Columns default value is the default value from primary key of another table

(Table)File has many (Table)Words
FK Words.file_id related to a single File.id
Default value of Words.frame is equal to File.frame for that PK/FK
Does this type of default relationship have a name? Examples on getting this setup? (MySQL)
Edit
The reason for this is that words may have the same frame as the file and if they do, we want to use that default, however some may not and need to be set manually. Is this really bad practice to handle it this way as described in one of the answers? Any improvement suggestions?
You may want to use a Trigger. You should be able to mimick the "default value" of Words.frame to be based on the value of another field from the File table.
It doesn't have a name, but feels like denormalization / data duplication to me.
#Daniel Vassallo suggests an insert trigger for this, and I think that would be the best approach as well if this is really what you need.

Constrain a table to have only one row

What's the cleanest way to constrain a SQL table to allow it to have no more than one row?
This related question discusses why such a table might exist, but not how the constraint should be implemented.
So far I have only found hacks involving a unique key column that is constrained to have a specific value, e.g. ALWAYS_0 TINYINT NOT NULL PRIMARY KEY DEFAULT (0) CONSTRAINT CHECK_ALWAYS_0 CHECK (ALWAYS_0 = 0). I am guessing there is probably a cleaner way to do it.
The ideal solution would be portable SQL, but a solution specific to MS SQL Server or postgres would also be useful
The cleanest way (I think) would be an ON INSERT trigger that throws an exception (thus preventing the row from being inserted). This also gives the client app a chance to recover gracefully.
I just solved the same problem on SQL Server 2008 by creating a table with a computed column and putting the primary key on that column:
CREATE TABLE MyOneRowTable (
[id] AS (1) PERSISTED NOT NULL CONSTRAINT pk_MyOneRowTable PRIMARY KEY,
-- rest of the columns go here
);
Use Grant to remove permissions for anyone to insert into the table after adding the one row
Your dba will be able to insert but the dba should only be running schema changes which are checked so should not be a problem in practice