Introduction to PostgreSQL real Data Type
The real
data type in PostgreSQL is a floating-point type that can store single-precision floating-point numbers (32 bits).
Syntax
The syntax for defining a real
data type is as follows:
column_name real
Use Cases
The real
data type is commonly used for storing numeric values with decimal parts, such as temperature, velocity, price, etc. It is widely used in fields like science, engineering, finance, etc.
Compared to the double precision
data type, the real
data type uses less storage space but has slightly lower precision. If you need higher precision, you can use the double precision
data type.
Examples
Here are two examples of using the real
data type:
Example 1
In this example, we will create a table named temperature
with a real
column named value
to store temperature values.
CREATE TABLE temperature (
id SERIAL PRIMARY KEY,
value REAL
);
INSERT INTO temperature (value) VALUES (24.5);
INSERT INTO temperature (value) VALUES (26.8);
Now, we can query the temperature
table and calculate the average value of all temperature values:
SELECT AVG(value) FROM temperature;
The result is:
avg
--------
25.65
(1 row)
Example 2
In this example, we will create a table named product
with a real
column named price
to store product prices.
CREATE TABLE product (
id SERIAL PRIMARY KEY,
name VARCHAR(50),
price REAL
);
INSERT INTO product (name, price) VALUES ('Product A', 19.99);
INSERT INTO product (name, price) VALUES ('Product B', 29.99);
Now, we can query the product
table and calculate the sum of all product prices:
SELECT SUM(price) FROM product;
The result is:
sum
--------
49.98
(1 row)
Conclusion
The real
data type is a useful floating-point type in PostgreSQL, especially for storing numeric values with decimal parts. Although it has slightly lower precision compared to the double precision
data type, it uses less storage space and can be more storage-efficient in certain cases.