In SQL, data types are used to specify the type of data that a column in a table can hold. Some common SQL datatypes include:
- INT
- FLOAT
- CHAR
- VARCHAR
- DATE
- DATETIME
- BOOLEAN
The specific data types available in SQL depend on the particular SQL database management system (DBMS) you are using. Some DBMS have additional data types that are not part of the SQL standard.
Examples:
INT: Used to store whole numbers, such as the primary key of a table or the number of units in inventory.
CREATE TABLE products (
id INT PRIMARY KEY,
name VARCHAR(50),
quantity INT,
price FLOAT
);
In the above example we CREATE a table called “products” in a SQL database, with four columns: “id”, “name”, “quantity”, and “price”. The “id” column is defined as an INT data type and is set as the primary key, which means that it must be unique and cannot be null. The “name” column is defined as a VARCHAR(50) data type, which means that it can store variable-length character strings up to 50 characters in length. The “quantity” column is defined as an INT data type, which means that it can store whole numbers. The “price” column is defined as a FLOAT data type, which means that it can store decimal numbers.
Once the table is created, you can then use SQL statements such as INSERT, SELECT, UPDATE, and DELETE to add, retrieve, modify, and remove data from the table.
FLOAT: used to store decimal numbers such as currency values or precise measurements.
CREATE TABLE orders (
id INT PRIMARY KEY,
product_id INT,
quantity INT,
price FLOAT,
total_amount FLOAT
);
CHAR: used to store fixed-length character strings, such as a middle initial or a two-letter country code.
CREATE TABLE customers (
id INT PRIMARY KEY,
first_name VARCHAR(50),
last_name VARCHAR(50),
email VARCHAR(50)
);
VARCHAR: used to store variable-length character strings, such as a product name or customer address.
CREATE TABLE products (
id INT PRIMARY KEY,
name VARCHAR(50),
description VARCHAR(50),
price FLOAT
);
DATE: used to store date values, such as the date of a customer’s order.
CREATE TABLE orders (
id INT PRIMARY KEY,
customer_id INT,
order_date DATE,
total_amount FLOAT
);
DATETIME: used to store date and time values, such as the timestamp of a user’s last login.
CREATE TABLE users (
id INT PRIMARY KEY,
username VARCHAR(50),
password VARCHAR(50),
last_login DATETIME
);
BOOLEAN: used to store true/false values, such as whether a product is in stock or not.
CREATE TABLE products (
id INT PRIMARY KEY,
name VARCHAR(50),
in_stock BOOLEAN,
price FLOAT
);