CHAR
CHAR is a fixed-length character data type in SQL. It is used to store strings of a specified length. The stored strings in CHAR type columns are right-padded with spaces to match the defined length. Unlike variable-length character types, CHAR always uses the same amount of storage space per entry, regardless of the actual string length.
Example
Output
column_test |
---|
abc |
Explanation
In this example, a table named ‘test’ is created with a column ‘column_test’ which has the CHAR data type of length 5. The CHAR data type is a fixed length string data type, meaning that it will always use the same amount of storage space regardless of the length of data inserted. If the data inserted (‘abc’) is shorter than the declared length (5), the remaining space will be filled with blank spaces. When retrieved with a SELECT statement, ‘abc’ is displayed.
Example
Output
Explanation
In this example, the CREATE TABLE
query is used to create a new table, Books
, with two columns: Title
and AuthorName
. The CHAR
data type is used to define these columns where CHAR(50)
specifies a fixed length character of 50 characters for Title
and CHAR(30)
for AuthorName
.
Next, the INSERT INTO
statement is used to insert a new row into the Books
table, setting ‘The Great Gatsby’ as the Title
and ‘F. Scott Fitzgerald’ as the AuthorName
. The output ‘INSERT 0 1’ shows that one row was successfully inserted into the table.
Example
Output
Explanation
The CHAR data type is a fixed-length data type in SQL Server. When a value is stored in a column of CHAR type, it is right-padded with spaces to the defined length. In this example, CHAR(10)
is used to declare a variable @Sample. The value ‘Hello’ is stored in it, which only has 5 characters. When selected, the output is ‘Hello’ followed by 5 spaces, making up the total length 10.
Example
Output
Explanation
The CHAR
data type is used to declare a fixed-length character string. The string value ‘SQL’ is inserted into the example_column
of the example_char
table, which has a fixed length of 10. Despite the value being only three characters long, the string will occupy 10 characters of space, as dictated by the CHAR(10)
declaration.
Example
Output
Explanation
In this example, a new table named Books
is created. It has two columns, ID
of integer type and Path
of CHAR(255)
type. Then, a row is inserted into the table with ID as 1 and a path to a hypothetical book location. The CHAR(255)
type indicates that the Path
column can store a sequence of 255 characters.