Consider a table messages with three columns: fixed_char of type char(5), var_char of type varchar(5), and text_col of type text. The row inserted is ('hi', 'hi', 'hi'). What will be the result of the query that selects the length of each column's value?
CREATE TABLE messages (fixed_char char(5), var_char varchar(5), text_col text); INSERT INTO messages VALUES ('hi', 'hi', 'hi'); SELECT length(fixed_char) AS len_fixed, length(var_char) AS len_var, length(text_col) AS len_text FROM messages;
Remember that char(n) pads the string with spaces to the fixed length n.
The char(5) type pads the string 'hi' with 3 spaces, so its length is 5. The varchar(5) and text types store the string as is, so their lengths are 2.
Which statement correctly describes the difference between char(n) and varchar(n) in PostgreSQL?
Think about how the database treats the length of stored strings for each type.
char(n) pads strings with spaces to always have length n. varchar(n) stores strings as they are, up to length n, without padding.
Given a table users with a column username varchar(3), which INSERT statement will cause an error?
CREATE TABLE users (username varchar(3));
Check the length of the string compared to the column's maximum length.
The varchar(3) column allows strings up to length 3. The string 'abcd' has length 4, which exceeds the limit and causes an error.
You need to store user comments that can be very long, sometimes thousands of characters. Which character type is best to use in PostgreSQL for this column?
Consider flexibility and performance for very long strings.
text type can store strings of any length efficiently without a fixed limit, making it ideal for very long text data.
Given a table products with a column code char(4), the query SELECT code FROM products WHERE code = 'AB' returns no rows, but SELECT code FROM products WHERE code LIKE 'AB%' returns rows. Why?
Think about how fixed-length char stores strings and how comparisons work.
char(4) pads stored strings with spaces to length 4. The string 'AB' is stored as 'AB '. The equality comparison with 'AB' fails because 'AB' is length 2 without spaces, but LIKE 'AB%' matches the prefix 'AB'.