1. Home
SQL

SQL Tutorial: Learn Structured Query Language Basics

Learn all SQL tutorial concepts in detail and master your career today.

  • 59
  • 9 Hours
right-top-arrow

Tutorial Playlist

46 Lessons
4

A Comprehensive Guide to SQL Data Types

Updated on 10/06/202474 Views

Introduction

Structured Query Language

Source: Freepik 

SQL (Structured Query Language) is a powerful language for managing and manipulating relational databases. One fundamental aspect of collaborating with SQL is comprehending the available information types. Data kinds define the sort of data that can be saved in database columns, and choosing the proper information kind is important for guaranteeing data honesty, enhancing storage, and enabling reliable querying.

SQL Data Types

SQL supports a wide range of data types to accommodate different kinds of data. These data types can be broadly categorized into three main groups: numeric data types, character data types, and date and time data types.

Numeric Data Types: Numeric data types store numeric values in SQL databases. They include integers, floating-point numbers, and fixed-point numbers. The most commonly used numeric data types are:

  • INT: This is used to store whole numbers without decimal points. It typically has a range of -2,147,483,648 to 2,147,483,647.
  • BIGINT: Used to store large whole numbers without decimal points. It has a wider range than INT, typically -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.
  • DECIMAL: This is used to store fixed-point numbers with a specified precision and scale. It allows for storing exact numeric values with a fixed number of digits before and after the decimal point.
  • FLOAT and DOUBLE: Used to store approximate numeric values with floating-point precision. FLOAT typically has a precision of 7 digits, while DOUBLE has a precision of 15 digits.

Character Data Types: Character data types are used to store character strings, such as text, names, and descriptions. The most commonly used character data types are:

  • CHAR: Used to store fixed-length character strings. The maximum length of a CHAR column must be specified when creating the table. If the stored value is shorter than the specified length, it is padded with spaces.
  • VARCHAR: Used to store variable-length character strings. Unlike CHAR, VARCHAR does not pad the stored value with spaces. The maximum length of a VARCHAR column must be specified when creating the table.
  • TEXT: Used to store large amounts of character data. It holds a maximum of 65,535 characters and is typically used for storing lengthy text, such as articles or descriptions.

Date and Time Data Types: Date and time data types are used to store temporal values, such as dates, times, and timestamps. The most commonly used date and time data types are:

  • DATE: Used to store date values without a time component. It follows the format 'YYYY-MM-DD.'
  • TIME: This is used to store time values without a date component. It follows the format 'HH:MM:SS.'
  • DATETIME: Used to store both date and time values. It follows the format 'YYYY-MM-DD HH:MM:SS.'
  • TIMESTAMP: This is similar to DATETIME but with a smaller storage size. It is typically used for tracking changes or recording timestamps.

In addition to these main categories, SQL provides other specialized data types, such as BOOLEAN for storing logical values (TRUE or FALSE), BLOB for storing binary data, and JSON for storing JSON documents.

Understanding the properties and usage of each data type is essential for designing efficient and reliable databases. Choosing the appropriate data type based on the nature of the data, the range and precision requirements, and the storage considerations helps ensure data integrity and optimizes database performance.

Let's dive into each category and explore the specific data types available.

Numeric Data Types In SQL

Numeric data types in SQL store numeric values in SQL databases. Here are the commonly used numeric data types:

INT

The INT data type is used to store integer values. Its range is -2,147,483,648 to 2,147,483,647. The storage size of INT is typically 4 bytes.

Example:

CREATE TABLE employees (

  id INT,

  age INT,

  salary INT

);

BIGINT

The BIGINT data type is used to store large integer values. Its range is -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. The storage size of BIGINT is typically 8 bytes.

Example:

CREATE TABLE population (

  country VARCHAR(50),

  population BIGINT

);

DECIMAL

The DECIMAL data type is used to store fixed-point numbers. It allows you to specify the precision (total number of digits) and scale (number of digits after the decimal point).

Example:

CREATE TABLE products (

  id INT,

  name VARCHAR(100),

  price DECIMAL(10,2)

);

FLOAT and DOUBLE

The FLOAT and DOUBLE data types are used to store floating-point numbers. FLOAT typically has a precision of 7 digits, while DOUBLE has a precision of 15 digits.

Example:

CREATE TABLE measurements (

  id INT,

  temperature FLOAT,

  humidity DOUBLE

);

Other Numeric Data Types

Other numeric data types include SMALLINT (2 bytes), TINYINT (1 byte), and REAL (4 bytes). These data types have different ranges and storage sizes to accommodate various numeric requirements.

Character Data Types In SQL

Character data types are used to store character strings in SQL databases. Here are the commonly used character data types:

CHAR

The CHAR data type is used to store fixed-length character strings. The maximum length of a CHAR column must be specified when creating the table. If the stored value is shorter than the specified length, it is padded with spaces.

Example:

CREATE TABLE users (

  id INT,

  username CHAR(10),

  password CHAR(20)

);

VARCHAR

The VARCHAR data type is used to store variable-length character strings. Unlike CHAR, VARCHAR does not pad the stored value with spaces. The maximum length of a VARCHAR column must be specified when creating the table.

Example:

CREATE TABLE articles (

  id INT,

  title VARCHAR(100),

  content VARCHAR(1000)

);

TEXT

The TEXT data type is used to store large amounts of character data. It holds a maximum of 65,535 characters. TEXT is typically used for storing lengthy text, such as articles or descriptions.

Example:

CREATE TABLE blog_posts (

  id INT,

  title VARCHAR(100),

  content TEXT

);

Date And Time Data Types In SQL

Date and time data types are used to store temporal values in SQL databases. Here are the commonly used date and time data types:

DATE

The DATE data type is used to store date values without a time component. It follows the format 'YYYY-MM-DD.'

Example:

CREATE TABLE orders (

  id INT,

  customer_id INT,

  order_date DATE

);

TIME

The TIME data type is used to store time values without a date component. It follows the format 'HH:MM:SS.'

Example:

CREATE TABLE schedules (

  id INT,

  event_name VARCHAR(100),

  start_time TIME,

  end_time TIME

);

DATETIME

The DATETIME data type is used to store both date and time values. It follows the format 'YYYY-MM-DD HH:MM:SS.'

Example:

CREATE TABLE appointments (

  id INT,

  patient_id INT,

  appointment_datetime DATETIME

);

TIMESTAMP

The TIMESTAMP data type is similar to DATETIME but with a smaller storage size. It is typically used for tracking changes or recording timestamps.

Example:

CREATE TABLE audit_log (

  id INT,

  user_id INT,

  action VARCHAR(100),

  timestamp TIMESTAMP

);

Other SQL Data Types

In addition to the numeric, character, and date/time data types, SQL offers a few other data types for specific purposes:

BOOLEAN

The BOOLEAN data type in SQL is used to store logical values, either TRUE or FALSE. It occupies 1 byte of storage.

Example:

CREATE TABLE settings (

  id INT,

  user_id INT,

  notification_enabled BOOLEAN

);

BLOB

The BLOB (Binary Large Object) data type is used to store large binary objects, such as images, documents, or multimedia files.

Example:

CREATE TABLE files (

  id INT,

  name VARCHAR(100),

  data BLOB

);

JSON

The JSON data type in SQL is used to store JSON (JavaScript Object Notation) documents. It allows for storing and querying structured data in a flexible format.

Example:

CREATE TABLE products (

  id INT,

  name VARCHAR(100),

  details JSON

);

SQL Data Types: Advantages And Disadvantages

SQL has its own set of advantages and disadvantages, like any other tool. Let’s explore the advantages and disadvantages that make SQL a necessary tool for database management: 

Advantages Of SQL Data Types

  1. Data Integrity: SQL data types enforce data integrity by ensuring that only valid and appropriate data is stored in the database columns. By specifying the correct data type for each column, you can prevent storing incompatible or incorrect data.
  2. Efficient Storage: Choosing the appropriate data type allows for efficient storage of data. For example, using an INT data type for storing whole numbers is more efficient than using a VARCHAR data type. Efficient storage optimization leads to better database performance and reduced storage costs.
  3. Improved Query Performance: When data types are properly defined, the database optimizer can make informed decisions about query execution plans. It can leverage the data type information to perform type-specific optimizations, such as using indexes effectively or applying appropriate operators, resulting in faster query performance.
  4. Data Consistency: SQL data types promote data consistency across the database. By enforcing a consistent data type for a particular column, you ensure that all the values stored in that column adhere to the same format and constraints. This consistency facilitates accurate data retrieval, comparison, and manipulation.

Disadvantages Of SQL Data Types

  1. Limited Flexibility: SQL data types have predefined formats and constraints, which can sometimes limit the flexibility of storing certain types of data. For example, if you have a column that needs to store complex or unstructured data, such as JSON or XML, you may need to use specialized data types or resort to storing the data as text and parsing it in the application layer.
  2. Data Type Mismatches: When integrating data from different sources or systems, data type mismatches can occur. If the data types of the source and target columns are incompatible, it can lead to data loss or incorrect data representation. Careful data type mapping and conversion techniques need to be employed to handle such scenarios.
  3. Storage Overhead: Some data types, particularly those with fixed lengths like CHAR, can result in storage overhead if the actual data stored is consistently shorter than the defined length. This can lead to wasted storage space and increased database size. Careful consideration should be given to choosing the appropriate data type and length based on the expected data values.

Data Type Conversion And Casting

In SQL, data type conversion and casting play a crucial role in transforming data from one type to another. It allows you to perform operations on data that may have different data types or to ensure compatibility between columns during comparisons or assignments. SQL provides several functions and operators to facilitate data type conversion and casting.

One of the most commonly used conversion functions is CAST. The CAST function allows you to explicitly convert a value from one data type to another. The syntax for using CAST is as follows:

CAST(Value AS Datatype)

Here, value represents the data or expression you want to convert, and datatype specifies the target data type you want to convert to. For example, if you have a string value that represents an integer, you can use CAST to convert it to the INT data type:

SELECT CAST('42' AS INT);

This query will return the integer value 42.

Another useful conversion function is CONVERT. It is similar to CAST but provides additional flexibility by allowing you to specify an optional style parameter. The syntax for CONVERT is as follows:

CONVERT(Datatype, Value, Style)

The datatype and value parameters serve the same purpose as in the CAST function. The style parameter is optional and allows you to specify the format or style of the conversion. For example, you can use CONVERT to convert a date string to the DATE data type with a specific format:

SELECT CONVERT(DATE, '2023-06-15', 120);

In this example, the style parameter 120 represents the format 'YYYY-MM-DD'.

SQL also provides the PARSE function, which is used to convert a string to a date/time or numeric value. The syntax for PARSE is as follows:

PARSE(String AS Datatype)

The string parameter represents the string value you want to parse, and the datatype specifies the target data type. PARSE is particularly useful when you have string values that represent dates or numbers in a specific format. For example:

SELECT PARSE('2023-06-15' AS DATE);

This query will parse the string '2023-06-15' and convert it to the DATE data type.

It's important to note that not all data types can be directly converted to each other. When performing data type conversion or casting, you need to ensure compatibility between the source and target data types. Attempting to convert incompatible data types may result in errors or unexpected behavior.

For example, converting a string value that doesn't represent a valid number to an INT data type will raise an error. Similarly, converting a date string with an unsupported format to the DATE data type will also result in an error.

To handle potential errors and data loss during data type conversion, you can use error-handling techniques such as TRY_CAST or TRY_CONVERT. These functions attempt the conversion and return NULL if the conversion fails, instead of raising an error.

SELECT TRY_CAST('abc' AS INT);

In this case, since 'abc' cannot be converted to an integer, TRY_CAST will return NULL instead of raising an error.

Data type conversion and casting are essential techniques in SQL when working with data from different sources or when performing operations that require compatible data types. By using functions like CAST, CONVERT, and PARSE, you can transform data to the desired data type and ensure smooth data processing and analysis.

However, it's crucial to exercise caution and thoroughly test your conversion logic to handle any potential errors or data loss. Proper error handling and data validation can help maintain data integrity and prevent the unexpected issues in your SQL queries and operations.

Conclusion

Understanding SQL data types is essential for effective database design and management. By choosing the appropriate data types for your database columns, you can ensure data integrity, optimize storage, and enable efficient querying. This comprehensive guide has covered the various SQL data types, including numeric, character, date/time, and specialized types like BOOLEAN and JSON.

Remember to consider the nature of your data, the range and precision requirements, and the storage efficiency when selecting data types. Additionally, familiarize yourself with data type conversion functions to handle scenarios where data needs to be transformed from one type to another. By mastering SQL data types, you'll be well-equipped to design robust and efficient databases that meet your application's requirements.

Ready to take your SQL skills to the next level? Check out our comprehensive SQL courses and tutorials at Upgrad. Whether you're a beginner or an experienced developer, Upgrad offers a wide range of resources to help you master SQL and enhance your database management capabilities. Start your learning journey today!

Frequently Asked Question

Q1: What are the data types in SQL?

SQL supports various data types, including numeric (INT, DECIMAL, FLOAT), character (CHAR, VARCHAR, TEXT), date and time (DATE, TIME, DATETIME), and specialized types like BOOLEAN and JSON.

Q2: What are the different date types in SQL?

The commonly used date and time data types in SQL are DATE (stores date without time), TIME (stores time without date), DATETIME (stores both date and time), and TIMESTAMP (similar to DATETIME but with smaller storage size).

Q3: What is the data type in SQL with an example?

An example of a data type in SQL is VARCHAR, which is used to store variable-length character strings. For instance, defining a column as "name VARCHAR(50)" allows storing names up to 50 characters long.

Q4: What is the data type of dual table?

The DUAL table is a dummy table in SQL that contains a single row with a single column. The data type of the column in the DUAL table is not specifically defined and can vary depending on the database system.

Q5: What is the primary key in SQL?

A primary key in SQL is a column or a combination of columns that uniquely identifies each row in a table. It enforces data integrity, prevents duplicate rows, and is often used as a reference for establishing relationships between tables.

Q6: What are SQL operators?

SQL operators are symbols or keywords used to perform operations on data in SQL statements. They include arithmetic operators (+, -, *, /), comparison operators (=, <>, <, >, <=, >=), logical operators (AND, OR, NOT), and special operators like BETWEEN, IN, and LIKE.

Q7: What are the two types of data?

In the context of databases, the two main types of data are structured data and unstructured data. Structured data has a predefined format and fits well into tables with rows and columns, while unstructured data, such as text, images, or videos, does not have a fixed format.

Q8: What is the AC file data type?

The term "AC file data type" is not a standard or commonly used term in SQL. It might be a specific data type used in a particular database system or application. Can you please provide more context or information about where you encountered this term?

Rohan Vats

Rohan Vats

Software Engineering Manager @ upGrad. Passionate about building large scale web apps with delightful experiences. In pursuit of transforming eng… Read More

Get Free Career Counselling
form image
+91
*
By clicking, I accept theT&Cand
Privacy Policy
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
right-top-arrowleft-top-arrow

upGrad Learner Support

Talk to our experts. We’re available 24/7.

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...