SQL Variables and Data Types
SQL Variables and Data Types Interview with follow-up questions
1. What are the different data types available in SQL?
SQL supports a range of data types. The exact set varies by database system, but the standard categories are:
Numeric:
INT/INTEGER— whole numbers (4 bytes, range ±2.1 billion)BIGINT— larger whole numbers (8 bytes)SMALLINT— smaller whole numbers (2 bytes)DECIMAL(p,s)/NUMERIC(p,s)— exact fixed-point numbers; use for moneyFLOAT/REAL/DOUBLE PRECISION— approximate floating-point; avoid for financial data due to rounding errors
Character/String:
CHAR(n)— fixed-length string, always padded to n charactersVARCHAR(n)— variable-length string, up to n charactersTEXT— variable-length string with no practical length limit (PostgreSQL, MySQL)
Date and Time:
DATE— date only (YYYY-MM-DD)TIME— time only (HH:MM:SS)TIMESTAMP/DATETIME— date + timeTIMESTAMP WITH TIME ZONE(TIMESTAMPTZin PostgreSQL) — timezone-aware
Boolean:
BOOLEAN/BOOL— true/false (SQL Server usesBIT)
Binary:
BYTEA(PostgreSQL) /BLOB(MySQL) — raw binary data
Semi-structured (modern databases):
JSON/JSONB(PostgreSQL) — native JSON; JSONB is stored binary and indexableARRAY(PostgreSQL) — array of any typeXML— XML data type
Interview tip: Use DECIMAL not FLOAT for money. Know that CHAR pads with spaces, which can affect comparisons.
Follow-up 1
What is the difference between CHAR and VARCHAR data types in SQL?
The main difference between CHAR and VARCHAR data types in SQL is that CHAR is a fixed-length character string, while VARCHAR is a variable-length character string. This means that a CHAR column will always occupy the same amount of storage space, regardless of the actual length of the data stored in it, while a VARCHAR column will only occupy the necessary amount of storage space based on the length of the data stored in it.
Follow-up 2
Can you explain the use of the DATE data type in SQL?
The DATE data type in SQL is used to store date values. It allows you to store dates in the format 'YYYY-MM-DD'. The DATE data type is commonly used to represent birth dates, transaction dates, and other types of dates in a database.
Follow-up 3
What is the use of the DECIMAL data type in SQL?
The DECIMAL data type in SQL is used to store fixed-point numbers with a specified precision and scale. It allows you to store numbers with a specific number of digits before and after the decimal point. The precision represents the total number of digits that can be stored, while the scale represents the number of digits that can be stored after the decimal point.
Follow-up 4
How does the BOOLEAN data type work in SQL?
The BOOLEAN data type in SQL is used to store boolean values, which can be either true or false. In SQL, the boolean values are typically represented as 1 for true and 0 for false. The BOOLEAN data type is commonly used to represent logical conditions or flags in a database.
Follow-up 5
What is the difference between INT and BIGINT data types?
The main difference between INT and BIGINT data types in SQL is the range of values they can store. INT is a 32-bit signed integer data type, which means it can store values from -2,147,483,648 to 2,147,483,647. BIGINT is a 64-bit signed integer data type, which means it can store values from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. BIGINT can store larger numbers than INT, but it also requires more storage space.
2. How do you declare a variable in SQL?
Variable declaration syntax varies significantly between database systems. This is a common area where interviewers expect you to be specific about the platform.
SQL Server / T-SQL:
DECLARE @count INT;
DECLARE @name VARCHAR(100) = 'Alice'; -- declare and assign
SET @count = 10;
-- or
SELECT @count = COUNT(*) FROM employees;
PostgreSQL (PL/pgSQL — inside a function or DO block):
DO $$
DECLARE
v_count INTEGER;
v_name TEXT := 'Alice';
BEGIN
SELECT COUNT(*) INTO v_count FROM employees;
RAISE NOTICE 'Count: %', v_count;
END;
$$;
MySQL (inside a stored procedure or block):
DECLARE v_count INT DEFAULT 0;
DECLARE v_name VARCHAR(100) DEFAULT 'Alice';
SET v_count = 10;
-- or
SELECT COUNT(*) INTO v_count FROM employees;
Oracle (PL/SQL):
DECLARE
v_count NUMBER;
v_name VARCHAR2(100) := 'Alice';
BEGIN
SELECT COUNT(*) INTO v_count FROM employees;
END;
Key points:
- Standard SQL does not define variable syntax for standalone scripts — it is procedural-language-specific
- Variables are scoped to the block/procedure they are declared in
- SQL Server uses
@prefix; PostgreSQL/MySQL/Oracle do not (they usev_convention by habit)
Follow-up 1
How do you assign a value to a variable in SQL?
To assign a value to a variable in SQL, you can use the SET statement. Here is the syntax:
SET @variable_name = value;
For example, to assign the value 10 to a variable named @count, you would use:
SET @count = 10;
You can also assign a value to a variable directly in a SELECT statement or as a result of a query.
Follow-up 2
Can you give an example of declaring a variable in SQL?
Sure! Here is an example of declaring a variable named @name of type VARCHAR(50):
DECLARE @name VARCHAR(50);
You can replace VARCHAR(50) with the desired data type and size for your variable.
Follow-up 3
What is the scope of a variable in SQL?
The scope of a variable in SQL is the range of the code where the variable can be referenced. In SQL, variables have a local scope, which means they are only accessible within the block of code where they are declared. This block of code can be a stored procedure, a function, or a batch of SQL statements.
Follow-up 4
Can you change the data type of a variable after it has been declared in SQL?
No, you cannot change the data type of a variable after it has been declared in SQL. Once a variable is declared with a specific data type, it cannot be altered. If you need to change the data type, you will need to declare a new variable with the desired data type and assign the value from the old variable to the new one.
Follow-up 5
What happens if you try to use a variable that has not been declared?
If you try to use a variable that has not been declared in SQL, you will get an error. The error message will indicate that the variable is not declared. It is important to always declare variables before using them to avoid such errors.
3. What is the difference between a local and a global variable in SQL?
The local/global variable distinction applies primarily to SQL Server (T-SQL) — it is less relevant in PostgreSQL or MySQL where variable scope is always tied to the block or procedure.
In SQL Server:
Local variables are declared with a single @ and are scoped to the batch, stored procedure, or function in which they are declared. They are not accessible outside that scope.
DECLARE @local_count INT = 0;
SET @local_count = 10;
-- @local_count exists only in this batch/procedure
Global variables use double @@ and are system-supplied read-only values — they are not user-defined variables. They expose server state and metadata.
SELECT @@VERSION; -- SQL Server version
SELECT @@ROWCOUNT; -- rows affected by the last statement
SELECT @@IDENTITY; -- last identity value inserted (scope-insensitive)
SELECT @@SERVERNAME; -- server name
Important nuance: In SQL Server, you cannot create your own @@ variables. @@ROWCOUNT, @@ERROR, @@IDENTITY etc. are built-in system functions disguised as variables.
PostgreSQL/MySQL: Variables are always local to the PL/pgSQL block or stored procedure. PostgreSQL has session-level settings (SET / SHOW) and user-defined configuration parameters, but these are different from variables.
Interview tip: If asked this question, clarify which database the interviewer has in mind, since "global variable" means something very different (or doesn't exist) depending on the platform.
Follow-up 1
Can you give an example of a local variable in SQL?
Sure! Here's an example of a local variable in SQL:
CREATE PROCEDURE calculate_average()
BEGIN
DECLARE @total INT;
SET @total = 0;
SELECT @total = @total + column_name FROM table_name;
SELECT @total / COUNT(*) AS average FROM table_name;
END;
In this example, the variable @total is a local variable that is declared within the scope of the calculate_average stored procedure. It is used to calculate the average of a column in a table.
Follow-up 2
Can you give an example of a global variable in SQL?
Certainly! Here's an example of a global variable in SQL:
DECLARE @global_variable INT;
SET @global_variable = 10;
CREATE PROCEDURE use_global_variable()
BEGIN
SELECT @global_variable;
END;
In this example, the variable @global_variable is a global variable that is declared outside of any specific scope. It can be accessed from within the use_global_variable stored procedure or any other part of the SQL environment.
Follow-up 3
What is the scope of a local variable in SQL?
The scope of a local variable in SQL is limited to the specific scope in which it is declared. For example, if a local variable is declared within a stored procedure, it can only be accessed within that stored procedure. Once the stored procedure finishes executing, the local variable goes out of scope and cannot be accessed anymore.
Follow-up 4
What is the scope of a global variable in SQL?
The scope of a global variable in SQL is not limited to any specific scope. It can be accessed from anywhere within the SQL environment, including stored procedures, functions, and other parts of the SQL code. The global variable remains in scope until it is explicitly dropped or the SQL environment is closed.
Follow-up 5
Can a local variable be accessed outside its scope?
No, a local variable in SQL cannot be accessed outside its scope. Once the scope in which the local variable is declared ends, the variable goes out of scope and cannot be accessed anymore. Attempting to access a local variable outside its scope will result in an error.
4. What is the use of NULL in SQL?
NULL in SQL represents the absence of a known value — it is not zero, not an empty string, and not false. It means the value is unknown or not applicable.
Key behaviors that interviewers test:
NULL is not equal to anything, including itself:
SELECT NULL = NULL; -- returns NULL, not TRUE
SELECT NULL != NULL; -- returns NULL, not FALSE
You must use IS NULL or IS NOT NULL:
SELECT * FROM employees WHERE manager_id IS NULL; -- correct
SELECT * FROM employees WHERE manager_id = NULL; -- returns no rows (wrong)
NULL in arithmetic produces NULL:
SELECT 10 + NULL; -- NULL
SELECT salary * 1.1 FROM employees; -- NULL if salary IS NULL
NULL in aggregate functions: Aggregate functions (COUNT, SUM, AVG, etc.) ignore NULLs — except COUNT(*).
SELECT AVG(commission) FROM employees; -- NULL rows excluded from average
SELECT COUNT(*) FROM employees; -- counts all rows including NULLs
SELECT COUNT(commission) FROM employees; -- counts only non-NULL commission rows
Handling NULLs:
COALESCE(a, b, c)— returns the first non-NULL valueNULLIF(a, b)— returns NULL if a equals b, otherwise returns aIS DISTINCT FROM(PostgreSQL) — NULL-safe equality operator
Interview gotcha: Three-valued logic — SQL comparisons with NULL return UNKNOWN (not TRUE or FALSE), which is why NULL rows are excluded from WHERE filters.
Follow-up 1
What is the difference between NULL and 0 in SQL?
The main difference between NULL and 0 in SQL is that NULL represents the absence of a value or an unknown value, while 0 is a specific value that represents the number zero. NULL is not equal to 0 and they have different meanings in SQL.
Follow-up 2
How do you check if a variable is NULL in SQL?
To check if a variable is NULL in SQL, you can use the IS NULL operator. The IS NULL operator returns true if the value is NULL and false otherwise. Here's an example:
SELECT * FROM table_name WHERE column_name IS NULL;
Follow-up 3
What happens if you try to perform an operation with a NULL value in SQL?
When you perform an operation with a NULL value in SQL, the result will also be NULL. This is because NULL represents the absence of a value, so any operation involving NULL will also result in NULL. For example, if you add NULL to a number, the result will be NULL.
Follow-up 4
Can you give an example of a situation where you would use NULL in SQL?
Sure! One example of a situation where you would use NULL in SQL is when you have a column that is optional and may not have a value for every row. For example, in a table of customers, you may have an optional 'middle_name' column. If a customer does not have a middle name, you can store NULL in that column to indicate the absence of a value.
Follow-up 5
What is the use of the IS NULL and IS NOT NULL operators in SQL?
The IS NULL and IS NOT NULL operators in SQL are used to check if a value is NULL or not. The IS NULL operator returns true if the value is NULL and false otherwise. The IS NOT NULL operator returns true if the value is not NULL and false otherwise. These operators are useful for filtering and querying data based on the presence or absence of a value. Here's an example:
SELECT * FROM table_name WHERE column_name IS NULL;
SELECT * FROM table_name WHERE column_name IS NOT NULL;
5. What is the use of the CAST function in SQL?
The CAST function explicitly converts a value from one data type to another. It is part of the SQL standard and works across all major databases.
Syntax:
CAST(expression AS target_type)
Common examples:
Convert string to integer:
SELECT CAST('42' AS INT);
Convert integer to string:
SELECT CAST(employee_id AS VARCHAR(10)) FROM employees;
Convert to date:
SELECT CAST('2026-01-15' AS DATE);
Truncate decimal precision:
SELECT CAST(3.99 AS INT); -- returns 3 (truncates, does not round)
CAST vs CONVERT:
CASTis ANSI SQL standard — works in all databasesCONVERTis SQL Server and MySQL specific; offers additional formatting options (e.g., date format styles in SQL Server)- PostgreSQL also supports the
::shorthand:'42'::INT,NOW()::DATE
CAST vs TRY_CAST (SQL Server):
CASTthrows an error if conversion failsTRY_CASTreturns NULL on failure — safer for untrusted input
Common use cases:
- Concatenating a number into a string:
'Employee #' || CAST(id AS VARCHAR) - Ensuring consistent type comparison when joining columns of different types
- Formatting output for reporting
Interview note: Implicit type coercion can happen silently in many databases, sometimes causing unexpected results — explicit CAST is clearer and safer.
Follow-up 1
Can you give an example of using the CAST function in SQL?
Sure! Here's an example of using the CAST function in SQL:
SELECT CAST('123' AS INT) AS ConvertedValue;
In this example, the CAST function is used to convert the string '123' to an integer data type. The result of the query will be the value 123.
Follow-up 2
What happens if you try to cast a variable to a data type that is not compatible with its current value?
If you try to cast a variable to a data type that is not compatible with its current value, an error will occur. The specific error message will depend on the database system you are using, but it will generally indicate that the conversion is not possible due to a data type mismatch.
Follow-up 3
What is the difference between CAST and CONVERT in SQL?
In SQL, both the CAST and CONVERT functions are used to convert values from one data type to another. The main difference between the two is that the CAST function is part of the SQL standard and is supported by all database systems, while the CONVERT function is specific to certain database systems.
Another difference is that the CONVERT function allows you to specify additional formatting options, such as date and time formats, while the CAST function only performs a basic conversion between data types.
Follow-up 4
Can you cast a variable to a custom data type in SQL?
No, you cannot cast a variable to a custom data type in SQL. The CAST function can only be used to convert values between the built-in data types provided by the database system. If you need to convert a variable to a custom data type, you would need to use other methods, such as creating a user-defined function or stored procedure.
Follow-up 5
What is the performance impact of using the CAST function in SQL?
The performance impact of using the CAST function in SQL can vary depending on the specific database system and the size of the data being converted. In general, the CAST function is a relatively lightweight operation and should not have a significant impact on performance. However, if you are performing a large number of conversions or working with large data sets, the performance impact may become more noticeable. It is always a good idea to test the performance of your queries and consider alternative approaches if necessary.
Live mock interview
Mock interview: SQL Variables and Data Types
- Read your scene and goals
- Talk it out; goals tick off live
- Get a score and stronger lines
Your voice and your AI key never touch our servers; the key stays in this browser and is sent only to Google. Only your round scores are saved to track progress.