create table patient (
p_code number(5) primary key,
p_name varchar2(50) not null,
DOB date(15) not null,
p_phone number(30) default null,
st varchar2(20) not null,
city varchar2(15) not null,
state varchar2(15) default null,
zip_code number(10) not null,
w_code number(5) references ward (w_code)
)
it gives me ORA-00907: missing right parenthesis
In all databases, the default value for a column is NULL when you leave out not null. So, you can write:
create table patient (
p_code number(5) not null primary key,
p_name varchar2(50) not null,
DOB date not null,
p_phone number(30),
st varchar2(20) not null,
city varchar2(15) not null,
state varchar2(15),
zip_code number(10) not null,
w_code number(5) references ward (w_code)
)
As a note. Oracle also accepts null and default null for this purpose, so these are also acceptable:
p_phone number(30) null,
p_phone number(30) default null,
The problem with your code was the date(15). date doesn't take a length argument.
By the way, you should be storing phone numbers and zip codes using strings and not numbers. They can have leading zeros.
Related
this is my first hands-on experience with Sql and I'm trying to construct One-To-Many relationship, here is the SQL code:
create table car (
id SERIAL PRIMARY KEY,
make VARCHAR(100) NOT NULL,
model VARCHAR(100) NOT NULL,
price NUMERIC(19, 2) NOT NULL
);
create table person (
id BIGSERIAL NOT NULL PRIMARY KEY,
first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50) NOT NULL,
gender VARCHAR(7) NOT NULL,
email VARCHAR(100),
date_of_birth DATE NOT NULL,
country_of_birth VARCHAR(50) NOT NULL,
cars_owning INT[] REFERENCES car(id)
);
and I get this error:
Key columns "cars_owning" and "id" are of incompatible types: integer[] and integer.
Here is the model a person can have many cars but each car have only one owner
typically (as a good general rule of thumb) the many refers to the one. not the other way around as you have tried.
So, alter the schema as:
create table car (
id SERIAL PRIMARY KEY,
make VARCHAR(100) NOT NULL,
model VARCHAR(100) NOT NULL,
price NUMERIC(19, 2) NOT NULL,
owner_id BIGINT FOREIGN KEY REFERENCES person(id)
);
create table person (
id BIGSERIAL NOT NULL PRIMARY KEY,
first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50) NOT NULL,
gender VARCHAR(7) NOT NULL,
email VARCHAR(100),
date_of_birth DATE NOT NULL,
country_of_birth VARCHAR(50) NOT NULL
);
If you need to get the list of cars owned by a person, use this select statement
SELECT person.id, ARRAY_AGG(car.id) owns_car_ids
FROM person
LEFT JOIN car ON person.id = car.owner_id
GROUP BY 1
The ArtistID column in Piece table refers to the ArtistID in the Artist table. Likewise, the LocationID column in Piece refers to LocationID in the GeographicLocation table. However, both foreign key references throw a "not the same data type as referencing column" error. What am I doing wrong?
CREATE TABLE dbo.Artist
(
ArtistID SMALLINT PRIMARY KEY IDENTITY,
LastName VARCHAR(50) NOT NULL,
FirstName VARCHAR(40) NOT NULL,
Nationality VARCHAR(10) NULL,
BirthYear SMALLINT NOT NULL CHECK(BirthYear <= 1980),
DeathYear SMALLINT NULL,
Sex CHAR(1) NOT NULL CHECK(Sex = 'F' OR Sex = 'M')
)
CREATE TABLE dbo.Piece
(
PieceID SMALLINT PRIMARY KEY IDENTITY(1, 5),
ArtistID SMALLINT NOT NULL
FOREIGN KEY REFERENCES Artist(ArtistID),
LocationID SMALLINT NOT NULL
FOREIGN KEY REFERENCES GeographicLocation(LocationID),
CommonName VARCHAR(100) NULL,
YearProduced TINYINT NULL,
Period VARCHAR(50) NULL,
Medium VARCHAR(35) NOT NULL,
Frame VARCHAR(35) NULL,
AppraisedValue MONEY NOT NULL,
AppraiserID SMALLINT NOT NULL
FOREIGN KEY REFERENCES Appraiser(AppraiserID)
)
CREATE TABLE dbo.GeographicLocation
(
LocationID SMALLINT PRIMARY KEY IDENTITY,
Country VARCHAR(25) NOT NULL,
City VARCHAR(50) NOT NULL
)
I think you missed a table here, which is AppraiserID column in Piece table refers to the AppraiserID in the Appraisertable
So, when I execute your SQL I am getting below error:
Foreign key 'FK__Piece__Appraiser__322C6448' references invalid table 'Appraiser'.
First Create a table called Appraiser, then create Foreign key references for those column.
Below SQL I am able to create all tables and Foreign key references:
CREATE TABLE dbo.Artist
(ArtistID SMALLINT PRIMARY KEY IDENTITY,
LastName VARCHAR(50) NOT NULL,
FirstName VARCHAR(40) NOT NULL,
Nationality VARCHAR(10) NULL,
BirthYear SMALLINT NOT NULL CHECK(BirthYear <= 1980),
DeathYear SMALLINT NULL,
Gender CHAR(1) NOT NULL CHECK(Gender = 'F' OR Gender = 'M'))
CREATE TABLE dbo.GeographicLocation
(LocationID SMALLINT PRIMARY KEY IDENTITY,
Country VARCHAR(25) NOT NULL,
City VARCHAR(50) NOT NULL)
CREATE TABLE dbo.Appraiser
(AppraiserID SMALLINT PRIMARY KEY IDENTITY(1, 5),
AppraisedValue MONEY NOT NULL,
AppraisedName VARCHAR(100) NULL)
CREATE TABLE dbo.Piece
(PieceID SMALLINT PRIMARY KEY IDENTITY(1, 5),
ArtistID SMALLINT NOT NULL,
LocationID SMALLINT NOT NULL,
CommonName VARCHAR(100) NULL,
YearProduced TINYINT NULL,
Period VARCHAR(50) NULL,
Medium VARCHAR(35) NOT NULL,
Frame VARCHAR(35) NULL,
AppraisedValue MONEY NOT NULL,
AppraiserID SMALLINT NOT NULL)
ALTER TABLE dbo.Piece WITH CHECK ADD CONSTRAINT FK_Piece_ArtistID FOREIGN KEY(ArtistID)
REFERENCES dbo.Artist (ArtistID)
GO
ALTER TABLE dbo.Piece CHECK CONSTRAINT FK_Piece_ArtistID
GO
ALTER TABLE dbo.Piece WITH CHECK ADD CONSTRAINT FK_Piece_AppraiserID FOREIGN KEY(AppraiserID)
REFERENCES dbo.Appraiser (AppraiserID)
GO
ALTER TABLE dbo.Piece CHECK CONSTRAINT FK_Piece_AppraiserID
GO
ALTER TABLE dbo.Piece WITH CHECK ADD CONSTRAINT FK_Piece_LocationID FOREIGN KEY(LocationID)
REFERENCES dbo.GeographicLocation (LocationID)
GO
ALTER TABLE dbo.Piece CHECK CONSTRAINT FK_Piece_LocationID
GO
I need to get the percentage increase revenue since last year, per country.
create table Customer
(
customer_mail_address varchar(255) not null,
lastname varchar(50) not null,
firstname varchar(50) not null,
payment_method varchar(10) not null,
payment_card_number varchar(30) not null,
contract_type varchar(20) not null,
subscription_start date not null,
subscription_end date ,
user_name varchar(30) not null,
password varchar(50) not null,
country_name varchar(50) not null,
gender char(1) ,
birth_date date ,
constraint pk_Customer primary key(customer_mail_address),
constraint fk_Customer1 foreign key(country_name) references Country(country_name) ON UPDATE CASCADE,
constraint fk_Customer2 foreign key(contract_type) references Contract(contract_type) ON UPDATE CASCADE,
constraint fk_Customer3 foreign key(payment_method) references Payment(payment_method) ON UPDATE CASCADE,
constraint chk_Customer1 check(subscription_start < subscription_end),
constraint uc_Customer unique(user_name),
constraint chk_Customer2 check(len([password]) >= 8 AND [password] like '%[0-9]%'),
constraint chk_Customer3 check(birth_date < subscription_start),
constraint chk_Customer4 check(user_name NOT LIKE '%[^A-Z0-9]%')
)
create table Watchhistory
(
movie_id integer not null,
customer_mail_address varchar(255)not null,
watch_date date not null,
price numeric(5,2)not null,
invoiced bit not null,
constraint pk_Watchhistory primary key(movie_id, customer_mail_address, watch_date),
constraint fk_Watchhistory1 foreign key(movie_id) references Movie(movie_id),
constraint fk_Watchhistory2 foreign key(customer_mail_address) references Customer(customer_mail_address) ON UPDATE CASCADE ON DELETE CASCADE
)
These two tables are what I use to calculate this. I tried a lot of stuff but nothing really did the trick. This is what I have now to calculate the revenue for each year per country but not the percentage increase per country.
CREATE VIEW OmzetStijgingDalingPerLand AS
SELECT DATEPART(yy,watch_date) as [jaar], country_name, SUM(price) AS [omzet]
FROM Watchhistory w
INNER JOIN Customer c ON w.customer_mail_address = c.customer_mail_address
GROUP BY DATEPART(yy,watch_date), country_name
As it is described in article mentioned before, LAG function is the key
SELECT jaar,
country_name,
omzet,
omzet / LAG(omzet, 1) OVER(PARTITION BY country_name ORDER BY jaar) AS increase_percent
FROM OmzetStijgingDalingPerLand
This is my task list:
Design a star or snowflake schema for a data warehouse that will help answer various business questions regarding sales.
Create a database in SQL Server (this is the data warehouse server) based on the star/snowflake schema you designed.
Load data from the source system i.e. the OLTP database shown earlier to the star/snowflake schema database.
The data from most of the tables in the OLTP database have been prepared in a form of SQL statements. Unfortunately, due to company's policy, you are not allowed to load data from the Products and Customer table 'directly'.
The Customer data has been prepared in CSV format
The Product data can only be retrieved from cloud database in JSON format http://bi.edisonsiow.com/ay1516s2/ca1/getProducts.php
You are required to find the most efficient way, which might include coding, to load data from the sources to your SQL Server.
So far i have done this :
CREATE TABLE Customers (
customerNumber Int NOT NULL,
customerName Varchar(50) NOT NULL,
contactLastName Varchar(50) NOT NULL,
contactFirstName Varchar(50) NOT NULL,
phone Varchar (50) NOT NULL,
addressLine1 Varchar (50) NOT NULL,
addressLine2 Varchar (50) NOT NULL,
city Varchar (50) NOT NULL,
state Varchar (50) NULL,
postalCode Varchar (15) NOT NULL,
country Varchar(50) NOT NULL,
salesRepEmployeeNumber Int NOT NULL,
creditLimit Double NOT NULL,
PRIMARY KEY (customerNumber));
CREATE TABLE Offices (
officeCode Varchar(10) NOT NULL,
city Varchar(50) NOT NULL,
phone Varchar(50) NOT NULL,
addressLine1 Varchar(50) NOT NULL,
addressLine2 Varchar(50) NOT NULL,
state Varchar(50) NULL,
country Varchar(50) NOT NULL,
postalCode Varchar(15) NOT NULL,
territory Varchar(10) NOT NULL,
PRIMARY KEY (officeCode));
CREATE TABLE payments (
customerNumber Int NOT NULL,
checkNumber Varchar(50) NOT NULL,
paymentDate Datetime NOT NULL,
amount DOUBLE NOT NULL,
PRIMARY KEY (customerNumber, checkNumber));
CREATE TABLE OrderDetails (
orderNumber Int NOT NULL,
productCode Varchar(15) NOT NULL,
quantityOrdered Int NOT NULL,
priceEach DOUBLE NOT NULL,
orderLineNumber SMALLINT NOT NULL,
PRIMARY KEY (orderNumber, productCode));
CREATE TABLE ProductLines (
productLine Varchar (50) NOT NULL,
textDescription TEXT NOT NULL,
htmlDescription TEXT NOT NULL,
image BLOB NOT NULL,
PRIMARY KEY (productLine));
CREATE TABLE Orders (
orderNumber Int NOT NULL,
orderDate DateTime NOT NULL,
requiredDate DateTime NOT NULL,
shippedDate DateTime NOT NULL,
status Varchar(15) Not null,
comments TEXT NOT NULL,
customerNumber INT NOT NULL,
Primary key(orderNumber));
ALTER TABLE Orders ADD FOREIGN KEY(customerNumber) REFERENCES Customer(customerNumber);
CREATE TABLE Employees (
employeeNumber Int Not null,
lastName Varchar(50) Not null,
firstName Varchar(50) Not null,
extension Varchar(10) NOt null,
email Varchar(100) Not null,
officeCode Varchar(10) Not Null,
reportsTo Int Not null,
jobTitle Varchar(50) Not null,
Primary key(employeeNumber));
CREATE TABLE Products (
productCode Varchar(15) Not Null,
productName Varchar(70) Not Null,
productLine Varchar(50) Not null,
productScale Varchar(10) Not null,
productVendor Varchar(50) Not null,
productDescription TEXT Not null,
quantityinStock Int Not null,
Buy Price Double Not null,
MSRP Double Not null,
Primary key (productCode))
9:28PM
CREATE TABLE payments (
customerNumber Int NOT NULL,
checkNumber Varchar(50) NOT NULL,
paymentDate Datetime NOT NULL,
amount Float NOT NULL,
PRIMARY KEY (customerNumber, checkNumber));
CREATE TABLE Customers (
customerNumber Int NOT NULL,
customerName Varchar(50) NOT NULL,
contactLastName Varchar(50) NOT NULL,
contactFirstName Varchar(50) NOT NULL,
phone Varchar (50) NOT NULL,
addressLine1 Varchar (50) NOT NULL,
addressLine2 Varchar (50) NOT NULL,
city Varchar (50) NOT NULL,
state Varchar (50) NULL,
postalCode Varchar (15) NOT NULL,
country Varchar(50) NOT NULL,
salesRepEmployeeNumber Int NOT NULL,
creditLimit Float NOT NULL,
PRIMARY KEY (customerNumber));
ALTER TABLE Payments ADD FOREIGN KEY(customerNumber) REFERENCES Customers(customerNumber); -- here
CREATE TABLE Offices (
officeCode Varchar(10) NOT NULL,
city Varchar(50) NOT NULL,
phone Varchar(50) NOT NULL,
addressLine1 Varchar(50) NOT NULL,
addressLine2 Varchar(50) NOT NULL,
state Varchar(50) NULL,
country Varchar(50) NOT NULL,
postalCode Varchar(15) NOT NULL,
territory Varchar(10) NOT NULL,
PRIMARY KEY (officeCode));
CREATE TABLE OrderDetails (
orderNumber Int NOT NULL,
productCode Varchar(15) NOT NULL,
quantityOrdered Int NOT NULL,
priceEach Float NOT NULL,
orderLineNumber SMALLINT NOT NULL,
PRIMARY KEY (orderNumber, productCode));
CREATE TABLE ProductLines (
productLine Varchar (50) NOT NULL,
textDescription TEXT NOT NULL,
htmlDescription TEXT NOT NULL,
image Float NOT NULL,
PRIMARY KEY (productLine));
CREATE TABLE Orders (
orderNumber Int NOT NULL,
orderDate DateTime NOT NULL,
requiredDate DateTime NOT NULL,
shippedDate DateTime NOT NULL,
status Varchar(15) Not null,
comments TEXT NOT NULL,
customerNumber INT NOT NULL,
Primary key(orderNumber));
ALTER TABLE OrderDetails ADD FOREIGN KEY(orderNumber) REFERENCES Orders(orderNumber); -- here
CREATE TABLE Employees (
employeeNumber Int Not null,
lastName Varchar(50) Not null,
firstName Varchar(50) Not null,
extension Varchar(10) NOt null,
email Varchar(100) Not null,
officeCode Varchar(10) Not Null,
reportsTo Int Not null,
jobTitle Varchar(50) Not null,
Primary key(employeeNumber));
CREATE TABLE Products (
productCode Varchar(15) Not Null,
productName Varchar(70) Not Null,
productLine Varchar(50) Not null,
productScale Varchar(10) Not null,
productVendor Varchar(50) Not null,
productDescription TEXT Not null,
quantityinStock Int Not null,
BuyPrice Float Not null,
MSRP Float Not null,
Primary key (productCode))
ALTER TABLE OrderDetails ADD FOREIGN KEY(productCode) REFERENCES Products(productCode);
I dont know how to load from source system?
In SQL Server Management Studio, exp[and the server-name, and under databases, find your database.
Right-click it, select Tasks, and then Import Data.
Use the import/export wizard to assist you in importing data from your source data.
I am new to SQL and I am trying to create a table with a constraint but I have not used the constrant before and I am not actually certain what this constraint does uc_ID on PId, LastName?
I want to create a constraint that will only allow alpha numeric values in a column?
Code:
CREATE TABLE Persons
(
PId int identity(1,1) NOT NULL,
LastName varchar(25) NOT NULL,
FirstName varchar(25) NOT NULL,
Address1 varchar(25) NOT NULL,
City varchar(25) NOT NULL
CONSTRAINT uc_ID UNIQUE (PId,LastName)
)
CREATE TABLE E
(
PId int identity(1,1) NOT NULL,
LastName varchar (25) NOT NULL,
FirstName varchar (25) NOT NULL,
Address1 varchar (25) NOT NULL,
City varchar (25) NOT NULL
CONSTRAINT OnlyAlphanumeric CHECK ([FirstName] NOT LIKE '%[^A-Z0-9]%')
)
Another Example (is not):
CREATE TABLE EEE
(
PId int identity(1,1) NOT NULL,
FirstName varchar (50) NOT NULL,
CONSTRAINT CHECK ([FirstName] LIKE '%[A-Za-z]%')
)
Means that the combination of Pid + LastName must be unique.
Since Pid is an identity, in normal circumstances it cannot be duplicated, so that constraint seems somehow redudant.
Try:
ALTER TABLE TableName ADD CONSTRAINT Only_Characters_And_Numbers CHECK ColumnName NOT LIKE '%[^A-Z0-9 ]%'
If you want a constraint that allows only alphanumeric characters in a column you can use this (for example for FirstName:
ALTER TABLE [Persons] ADD CONSTRAINT OnlyAlphanumeric CHECK ([FirstName] NOT LIKE '%[^A-Z0-9 ]%')
Disclaimer: taken from here (and tested).
If you want the constraint to be added when the table is created:
CREATE TABLE Persons
(
PId int identity(1,1) NOT NULL,
LastName varchar(25) NOT NULL,
FirstName varchar(25) NOT NULL,
Address1 varchar(25) NOT NULL,
City varchar(25) NOT NULL
CONSTRAINT OnlyAlphanumeric CHECK ([FirstName] NOT LIKE '%[^A-Z0-9 ]%')
)
Note that constraint names are unique per database.
Alternatively, you can create an AFTER INSERT and AFTER UPDATE trigger to make this validation, but a constraint works just fine in this case.