Is a productcode always numeric? - data-modeling

I have a table called products, and I want to use the productcode as a unique primary key and I am wondering if it should be A VARCHAR or an INT datatype?

Related

Table indexing with primary key

I have a table with columns id, name, created_at and severity and the table can end up having milions of records.
I am considering to apply indexing on created_at and severity as that is what I am filtering by on UI.
I also need to have composite primary key set on id and created_at
PRIMARY KEY, btree (created_at, id) [Due to some 3rd party tool requirements]
With the above primary key setup do I just need to add a simple index on severity (as created_at is already indexed) or should I create a composite index on [created_at, severity]
According to the docs, if you are going to be filtering on those two fields together, then it's advised that you should do a multicolumn index.
As shown in the docs, if you have a table:
CREATE TABLE test2 (
major int,
minor int,
name varchar
);
and query often with:
SELECT name FROM test2 WHERE major = constant AND minor = constant;
then it's a good idea to index like:
CREATE INDEX test2_mm_idx ON test2 (major, minor);

Insert a constraint for two columns in sql

Hi everyone I created this table for a database
CREATE TABLE IF NOT EXISTS compositions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
id_product INTEGER REFERENCES products(id),
id_receipt INTEGER REFERENCES receipt(id),
quantity INTEGER NOT NULL,
price FLOAT NOT NULL,
id_user VARCHAR REFERENCES users(id),
CONSTRAINT CHK_price_quantity CHECK (price > 0 AND quantity > 0)
);
I would like to insert a constraint that, for a given id_receipt, the id_user must be always the same but I don't know how to implement it.
Could someone give a help?
Thank you in advance.
For this requirement the column id_user should not be defined in the table compositions.
It makes more sense to store it in the table receipt, since each id_receipt is related to 1 and only 1 id_user.
This way you have id_receipt as a foreign key in compositions and through this column you can get (by a join) all the info that you want from receipt, like the id_user.

How do I avoid duplicates on an SQL primary key?

Complete beginner here. I'm trying to create this simple joint table on SSMS but I'm getting this duplicate error regarding the primary key:
Msg 2627, Level 14, State 1, Line 23
Violation of PRIMARY KEY constraint 'PK__FactOffl__B14003C24ECE0589'. Cannot insert duplicate key in object 'dbo.FactOfflineSales'. The duplicate key value is (43659).
What am I doing wrong?
CREATE TABLE FactOfflineSales
(
SalesOrderID int NOT NULL PRIMARY KEY,
SalesOrderNumber nvarchar(20) NOT NULL,
SalesPersonID int NULL,
CustomerID int NULL,
SpecialOfferID int NOT NULL,
TerritoryID int NOT NULL,
ProductID int NOT NULL,
CurrencyRateID int NULL,
OrderQuantity smallint NULL,
UnitPrice money NULL,
SubTotal money NULL,
TaxAmount money NULL,
Freight money NULL,
LineTotal money NULL,
UnitPriceDiscount float NULL,
OrderDate datetime NULL,
ShipDate datetime NULL,
DueDate datetime NULL,
OnlineOrderFlag int NULL
);
INSERT INTO FactOfflineSales (
SalesOrderID
,SalesOrderNumber
,SalesPersonID
,CustomerID
,SpecialOfferID
,TerritoryID
,ProductID
,CurrencyRateID
,OrderQuantity
,UnitPrice
,SubTotal
,TaxAmount
,Freight
,LineTotal
,UnitPriceDiscount
,OrderDate
,ShipDate
,DueDate
,OnlineOrderFlag
)
SELECT
SalesOrderHeader.SalesOrderID
,SalesOrderHeader.SalesOrderNumber
,SalesOrderHeader.SalesPersonID
,SalesOrderHeader.CustomerID
,SalesOrderDetail.SpecialOfferID
,SalesOrderHeader.TerritoryID
,SalesOrderDetail.ProductID
,SalesOrderHeader.CurrencyRateID
,SalesOrderDetail.OrderQty
,SalesOrderDetail.UnitPrice
,SalesOrderHeader.SubTotal
,SalesOrderHeader.TaxAmt
,SalesOrderHeader.Freight
,SalesOrderDetail.LineTotal
,SalesOrderDetail.UnitPriceDiscount
,SalesOrderHeader.OrderDate
,SalesOrderHeader.ShipDate
,SalesOrderHeader.DueDate
,SalesOrderHeader.OnlineOrderFlag
FROM
AdventureWorks2019.Sales.SalesOrderHeader SalesOrderHeader
LEFT JOIN
AdventureWorks2019.Sales.SalesOrderDetail SalesOrderDetail ON SalesOrderHeader.SalesOrderID = SalesOrderDetail.SalesOrderID;
You can not insert the duplicate value in primary key column.
You table FactOfflineSales has primary key on column SalesOrderID which will hold not null and unique values. But looking at your query it seems like there is one-to-many relationship between salesorderheader and salesorderdetails table. so your select query is giving multiple records for single salesorderid, means multiple records with same salesorderid.
It is not allowed to insert duplicate values in FactOfflineSales.salesorderid. Hence, it is throwing an error.
Best practice is to use auto generated sequence for primary key column. You should add one more column in table and declare it as primary key.(something like FactOfflineSales_id)
Your LEFT JOIN on SalesOrderDetail is mutiplying out rows from SalesOrderHeader, from which the primary key comes.
You need to add SalesOrderDetailID to the table, with that (or that and SalesOrderID together) as the primary key
There is a lot going on here. Let me unpack.
A join between tables helps when there is many to many. What does this mean? It means a header has many detail records and a detail record can belong to many headers. If this is not your case, you don't need a join table.
If you really need a join table, you normally do one of two things. The first would be create a composite key on the IDs from both tables. This would only be unique more than once if you load the table with a query that has dupes (solved with DISTINCT). The second (other option) is create a derived key for the primary key (like IDENTITY) and then have the two fields.
As you are learning, neither apply, but you can play with the queries to learn.
See if adding a distinct in the SELECT eliminates dupes. I don't think this will work, but DISTINCT is good to learn.
When the above fails, add a derived key on the table and then rerun your query. You do this by creating this join table with an Id field that is IDENTITY(1,1) for the PRIMARY KEY
As already mentioned by others, your issue is you have dupes on the primary key, which is sales order Id. Why dupes? Because each header has multiple detail records. On record 2, it will fail, as you had the header's id as your primary key.

Best Way to Auto Generate Id in SQL Server

What is the best way to generate Id or Code column(primary key) in a table in SQL Server? My requirement is a big table which stores more than 1000000 rows.
So generally we create auto identity column of a table but is it the best way? For example, I have an employee_master table and there are three columns like
emp_id auto increment
Emp_code varchar(20)
and also default like Rowno of a table.
So in this scenario, it has 3 unique columns of a table. Is it the best way?
Or what is the best way to generate id/code column both master and transaction table.
Also is there any way which we generate financial year wise auto-generate column.(any function)
The following SQL statement defines the "ID" column to be an auto-increment primary key field in the "Persons" table
CREATE TABLE Persons (
ID int NOT NULL AUTO_INCREMENT,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
PRIMARY KEY (ID)
);
I think this will work..

Composite primary key in sql server

I am trying to create a composite primary key in Sql server.
The syntax I have tried is:
create table Installment_details
(
constraint P_key primary key(Account_No,month),
Account_No int not null,
foreign key (Account_No) references Account_details(Account_no) on delete cascade,
Month char(15) not null,
D#te date,
Receipt_no varchar(15),
Amount_received int,
Amount_left int,
Amount_receiver char(50),
)
As far as I know it should create column with column name P_key for primary key but whenever I make a entry in table it doesn't show this column.
You are confused about the terms you're using. It's not the same a Primary Key and a Column. For example, you're creating a Primary Key based on two existing columns, and the name P_Key it's the name of the Primary Key, which is the way SQL SERVER (in this case) can identify a row in the Table (it cannot be two rows with the same values on those two columns).
I hope this clarifies a little bit the issue.
I think you are getting it wrong P_key in your code is constraint's name not a column name.
Also composite key is not a column, it is used when you don't have a column with unique values. So you take combination of two or more column as primary key so that we can uniquely identify a row.

Resources