Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sql combine value of two columns as primary key

I have a SQL server table on which I insert account wise data. Same account number should not be repeated on the same day but can be repeated if the date changes.

The customer retrieves the data based on the date and account number.

In short the date + account number is unique and should not be duplicate.

As both are different fields should I concatenate both and create a third field as primary key or there is option of having a primary key on the merge value.

Please guide with the optimum way.

like image 321
Danish_k12 Avatar asked Jun 30 '16 12:06

Danish_k12


People also ask

How do you make a primary key with a combination of two columns?

We can set PRIMARY KEY constraint on multiple columns of an existing table by using ADD keyword along with ALTER TABLE statement.

Can we make 2 columns as primary key in SQL?

In Table Designer, click the row selector for the database column you want to define as the primary key. If you want to select multiple columns, hold down the CTRL key while you click the row selectors for the other columns. Right-click the row selector for the column and select Set Primary Key.

How do I concatenate two column values in SQL query?

Query: SELECT *, CONCAT(FIRSTNAME, LASTNAME) AS FIRSTNAME FROM demo_table; Output: Here, we can see that FIRSTNAME and LASTNAME is concatenated but there is no space between them, If you want to add space between the FIRSTNAME and LASTNAME then add space(' ') in CONCAT() function.


1 Answers

You can create a composite primary key. When you create the table, you can do this sort of thing in SQL Server;

CREATE TABLE TableName (
  Field1 varchar(20),
  Field2  INT,
  PRIMARY KEY (Field1, Field2))

Take a look at this question which helps with each flavour of SQL

How can I define a composite primary key in SQL?

like image 195
Rich Benner Avatar answered Oct 09 '22 02:10

Rich Benner