How to create a column with the datatype float which only stores up to 3 decimals in PostgreSQL? - sql

I want to create a table in my PostgreSQL:
CREATE TABLE my_table(
id INT GENERATED ALWAYS AS IDENTITY NOT NULL PRIMARY KEY,
description TEXT,
score FLOAT NOT NULL
);
How do I limit the number of decimals stored in the "score" column to a maximum of 3 decimals?

You would use numeric. However, you need a precision as well, which limits the maximum value:
CREATE TABLE my_table(
id INT GENERATED ALWAYS AS IDENTITY NOT NULL PRIMARY KEY,
description TEXT,
score NUMERIC(10, 3) NOT NULL
);
This will store numbers up to 9,999,999.999.

Related

SQL Table with mixed data type field Best Practice

everyone,
I would like an advice on best practice for creating realtional database structure with field having mixed data type.
I have 'datasets' (some business objects) and I would like to have list of parameters, associated with each dataset. And those parameters can have different types - strings, integers, float and json values.
What would be the best structure for the parameters table? Should I have single column with string type?
CREATE TABLE param_desc (
id serial PRIMARY KEY,
name varchar NOT NULL,
param_type int -- varchar, int, real, json
);
CREATE TABLE param_value (
id serial PRIMARY KEY,
dataset_id int NOT NULL,
param int NOT NULL REFERENCES param_desc (id),
value varchar NOT NULL,
CONSTRAINT _param_object_id_param_name_id_time_from_key UNIQUE (dataset_id, param)
);
The problem with such approach is that I can't easily cast value for some additional conditions. For example, I want to get all datasets with some specific integer parameter, having int value more than 10. But if I write where clause, the casting will return error, as other non-integer parameters can't be casted.
SELECT dataset_id FROM vw_param_current WHERE name = 'priority' AND value::int > 5
Or should I have 4 separate columns, with 3 of them being NULL for every row?
Or should I have 4 different tables?

Format number of decimals based on another column PostgreSQL

I have a Table in my Database that contains values that are of type float8. I want to change these values to only contain decimal places configured in another table without changing the type.
CREATE TABLE config (
id uuid NOT NULL,
decimals int4 NOT NULL DEFAULT 2,
CONSTRAINT config PRIMARY KEY (id)
);
CREATE TABLE event (
value float8 NOT NULL,
config_id uuid NOT NULL,
id uuid NOT NULL,
CONSTRAINT event_pkey PRIMARY KEY (id),
CONSTRAINT config_id FOREIGN KEY (config_id) REFERENCES config(id)
);
My Tables would look like this:
event
config
id
config_id
value
id
decimals
0
1
18.891827465774448
0
2
1
0
-1.4444289712231306
1
5
I've tried doing it this way
ALTER TABLE event
ALTER COLUMN value TYPE decimal(16, (SELECT config.decimals
FROM config, event
WHERE config.id = event.config_id));
that returns
ERROR: type modifiers must be simple constants or identifiers
After the Alter Table they should look like this:
event
config
id
config_id
value
id
decimals
0
1
18.89182
0
2
1
0
-1.44
1
5
You can't change the data type per row. Instead, format the numbers in the query. Use to_char to format the value and repeat to build the format
select
to_char(event.value, '999999999D' || repeat('9', config.decimals)
from event
left join config on config.id = event.config_id
Alternatively, leave this formatting up to the application layer.

String or binary data would be truncated in table 'Record_Company.dbo.bands', column 'name'. Truncated value: 'I'

Below this is what I'm writing. On the last step it is crashing. Thank you for help. I tried what I found for example:
SET ANSI_WARNINGS OFF
INSERT INTO bands (name)
VALUES ('Iron Maiden');
SET ANSI_WARNINGS ON
GO
But it did not work.
CREATE TABLE bands (
id INT NOT NULL IDENTITY,
name NVARCHAR NOT NULL,
PRIMARY KEY (id) -
)
CREATE TABLE Albums (
id INT NOT NULL IDENTITY,
name NVARCHAR NOT NULL,
release_year INT,
band_id INT NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (band_id) REFERENCES bands(id),
INSERT INTO bands (name)
VALUES ('Iron Maiden');
String or binary data would be truncated in table 'Record_Company.dbo.bands', column 'name'. Truncated value: 'I'.
https://www.sqlservertutorial.net/sql-server-basics/sql-server-nvarchar/
NVARCHAR(n)
Code language: SQL (Structured Query Language) (sql)
In this syntax, n defines the string length that ranges from 1 to 4,000. If you don’t specify the string length, its default value is 1.
(emphasis mine)
So your NVARCHAR is interpreted as NVARCHAR(1) which means it can hold a string of only 1 character. Your string "Iron Maiden" is truncated to the first character, "I".

How to create an areas table using the following specification using sql?

How to create a table with the following specification ? Can anyone help me out please. Especially with the min and max constraint.
Table name : areas
Name Type Size Validation
id int 10 Primary Key
name varchar 40 Not Null, Min 3 Max 40
do_id int 10 Foreign Key (division_offices)
pincode int 10 not null min 6 max 6
ANSI SQL answer:
create table areas
(id int Primary Key,
name varchar(40) Not Null check(length(name) >= 3),
do_id int references division_offices,
pincode int not null check(pincode between 100000 and 999999)
)

Create a column with an if condition in SQL server

i am not sure if i could use conditional statement while creating new columns.
Code:
create table Employees(
Emp_ID int primary key identity (1,1),
Hours_worked int,
Rate int default '')
/*Now here in default value i want to set different rates depending upon hours worked. like if hour worked is greater than 8 then rate is 300, if hours worked is less than 8 hour the rate is 200.) How to write this as a Default value in sql server 2008.
My second question is:
Why i get error if i write like this,
create table tbl_1(
col_1 varchar(max) unique
)
The error is
Column 'col_1' in table 'tbl_1' is of a type that is invalid for use as a key column in an index.
Msg 1750, Level 16, State 0, Line 1
Regards
Waqar
you can use COMPUTED Column, http://msdn.microsoft.com/en-us/library/ms191250.aspx
create table Employees(
Emp_ID int primary key identity (1,1),
Hours_worked int,
Rate as (case when Hours_worked > 8 then 300 else 200 end) persisted )
The default value cannot refer to any other column names. So the "default" value of Rate won't know the value of Hours_worked. You could handle it with a trigger or whatever is doing the actual inserting could contain this logic.
http://msdn.microsoft.com/en-us/library/ms173565(v=sql.100).aspx
You cannot but a UNIQUE constraint on a VARCHAR(MAX) field.