Sql Server 2008 unique columns by condition - sql-server

Let's assume I have following table in the database:
Id ProductId ColorId IsDeleted
1 1 1 1
2 1 1 0
3 2 3 0
I want to make ProductId and ColorId columns unique but only for those rows where IsDeleted = 0. How do I can achieve this requirement?
I know, I can create a constraint which will call a stored function. And stored function will try to find an entry with the same values. But I think it is to complex way. May be there is a better decision...

In SQL Server 2008 and newer, you can take advantage of filtered indices to achieve this:
CREATE NONCLUSTERED UNIQUE INDEX ProductColor
ON dbo.YourTable(ProductID, ColorID)
WHERE IsDeleted = 0;
See the Filtered Index Design Guidelines for some more background and best practices.

Related

How to eliminate duplicate ids depending on another id

For my project in jsp ,
I want to insert values into the database
I have shop_Id and clothe_id (there are many shop each one having I'd).
I want to add clothes(there are many clothes and they too have I'd) ,
but for each shop the cloth I'd should not be repeated.
what query should I write to handel it in jsp .
shop_id and clothes_id are coming dynamically
Eg:- a) correct
shop I'd clothe I'd
0 0
0 1
0 2
1 0
1 1
1 2
Eg:-b) wrong
shop I'd clothe I'd
0 0
0 0 (wrong duplicate value)
1 0
The eg:- b) cause's data duplication.
What query should I write to Handel it
This is managed by your database
CREATE TABLE shop_cloth(
shop_id integer REFERENCES shop,
cloth_id integer REFERENCES cloth,
PRIMARY KEY(shop_id, cloth_id) --ensure uniqueness of combinaison shop_id, cloth_id or UNIQUE(shop_id, cloth_id) if you use another field for primary key
);
You should learn how works database and SQL (SQL is the language used by most relational database, like PostgreSQL)

SQL Server : recreate table in appropriate order

I've deleted some records (more precisely row 4) from a table in a SQL Server database. Now the first column goes like this (1,2,3,5) without row 4:
ID Name
------------
1 Luk
2 Sky
3 Philips
5 Andrey
How can I recreate this table and insert all data again in appropriate order?
Like this:
ID Name
--------
1 Luk
2 Sky
3 Philips
4 Andrey
EDIT:
But if i have another column (number) that is not a key, like this:
ID Number Name
------------
1 1 Luk
2 2 Sky
3 3 Philips
5 5 Andrey
Then can i recreate column Number and Name,
ID Number Name
------------
1 1 Luk
2 2 Sky
3 3 Philips
5 4 Andrey 'Can i do this, and if can HOW?
I would make a pretty strong case for never storing this number, since it is calculated, instead you could just create a view:
CREATE VIEW dbo.YourView
AS
SELECT ID,
Number = ROW_NUMBER() OVER(ORDER BY ID),
Name
FROM dbo.YourTable;
GO
This way after you have deleted rows, your view will already be in sync without having to perform any updates.
If you need to store the value, then almost the same query applies, but just placed inside a common table expression, which is then updated:
WITH CTE AS
( SELECT ID,
Number,
NewNumber = ROW_NUMBER() OVER(ORDER BY ID)
FROM dbo.YourTable
)
UPDATE CTE
SET Number = NewNumber;
You can use dbcc command
DBCC CHECKIDENT('tableName', RESEED, 0)
It would reset identity to 0.
Note it would require to truncate table first.
You can make the ID to auto increment which by default, the starting value for AUTO_INCREMENT is 1, and it will increment by 1 for each new record.
E.g MSSQL uses IDENTITY keyword to auto increment whereas MySQL uses the AUTO_INCREMENT keyword to perform an auto-increment feature.
MSSQL
ID int IDENTITY(1,1) PRIMARY KEY
MySQL
ID int NOT NULL AUTO_INCREMENT

how Unique key works on multiple columns

i have a table T with following columns
col1 col2 col3 col4
1 1 1 1
1 1 1 2
1 1 2 1
1 1 2 1
if i set a column col2,col3,col4 as unique. how does the unique works ? will it take uniqueness of combination of each column?
See here: http://www.w3schools.com/sql/sql_unique.asp
The syntax for setting multiple columns as unique is different from that of setting one column unique. If you have multiple columns as unique it is the set that is viewed for uniqueness.
Yes, the "unique-ness" is a result of all columns involved in the constraint. See SO Question
You can easily write yourself a table and test how it handles INSERTs
I'm not entirely sure, but I think the unique attribute has to do with indexing the table. Whichever column you set as unique, that column should be the one you call on to find a certain row. For example in a call like
UPDATE table_name SET column_name = some_value WHERE ID = some_number
the ID column should be set to unique, though I don't know whether not doing so would actually stop you from finding a specific row.

Inserting one table's complete column data to a particular column in another table in SQL Server

Inserting one table's complete column data to a particular column in another table in SQL SERVER
I have two tables i.e AuditCalendar, ScheduleAudit
Audit Calendar has two columns Taskid, TaskTypeId
Schedule Audit has two columns Scheduleid, Taskid
Audit Calendar looks like this
Taskid (Auto increment) TaskTypeId
-------------------------------------
1 1
2 2
3 3
4 1
5 1
But I want Taskid column data from Audit Calendar table based on TaskTypeId .Columns
After completion of query, the ScheduleAudit table should look like this
Scheuleid (AutoIncrement) Taskid
-------------------------------------
1 1
2 1
3 1
I have to run this query seems to look like a error
Subquery returns more than one value
Query is:
INSERT INTO ScheduleAudit(TaskId)
VALUES ((SELECT TaskId FROM AuditCalendar Where TaskTypeId = 1))
Please can you suggest how I can do this approach I am new to SQL Server but someone says that use cursors.... I am really confused last 1 week on words. And also search google but not get it now...Please can you give me any one valuable suggestions.
insert ... values is supposed to insert a single row. So what you have in the parentheses is supposed to produce a single row, or else it would fail.
There's no need to use insert ... values, when you can use insert ... select:
INSERT INTO ScheduleAudit(TaskId)
SELECT TaskId FROM AuditCalendar Where TaskTypeId=1
...however, that would produce
1 1
2 4
3 5
I'm not sure I understand the logic behind producing your example output.

Putting clustered index on a join used column vs heavily scanned column?

I have this simple table :
Table Users
userId | name
---------------------
1 'a1'
2 'a2'
3 'a3'
4 'a4'
5 'a5'
Table Cities
cityId | name
---------------------
1 'c1'
2 'c2'
3 'c3'
4 'c4'
5 'c5'
Each user is can be in more than one city. :
So the mapping table is :
userId | CityId
------------------------------------
1 4
1 4
1 4
2 5
5 6
Table users is heavily scanned by name .
Question :
For the mapping table I have no issues. both columns together are primary/clustered index.
But i'm struggling with myself about the first 2 tables :
I think that Users should have userId column as primary key. why ? because it is used throug the join to the mapping table.
but I also need clustered index on the name column cause this table is heavily scanned by name.
(leave aside the unique problem. lets say all columns are unique)
What is the best practice decision for this case ?
The best decision depends on how exactly you use the data returned by a query.
A clustered index means that the data in the page files are ordered based on this index.
A regular index will have it's own page files to order the index and a pointer to the physical row.
Thus a clustered index will serve better for theses queries that return a range of value instead of unique rows.
So, unless you do a lot of queries with like operations on the Name column, you would be better to keep your clustered index on the ID column, for this index will be constantly scanned and used to return recordsets to support your join operations.

Resources