Most Frequently asked sqlite Interview Questions and Answers
Question: How do you perform a SELECT query in SQLite?
Answer:
Performing a SELECT
query in SQLite allows you to retrieve data from one or more tables. The SELECT
statement in SQLite follows a basic structure, and you can use various clauses to filter, sort, and format your results.
Here’s a breakdown of how to perform a SELECT
query in SQLite, along with some common usage examples.
Basic SELECT Query
The simplest form of a SELECT
query retrieves all columns from a table:
SELECT * FROM table_name;
SELECT *
: Selects all columns in the table.FROM table_name
: Specifies the table from which to retrieve the data.
Example:
SELECT * FROM users;
This will retrieve all rows and columns from the users
table.
Selecting Specific Columns
You can select specific columns by specifying their names instead of using *
(asterisk).
SELECT column1, column2 FROM table_name;
Example:
SELECT name, age FROM users;
This will retrieve only the name
and age
columns from the users
table.
Filtering Results Using WHERE Clause
You can filter rows using the WHERE
clause to only return records that meet certain conditions.
SELECT * FROM table_name WHERE condition;
Example:
SELECT * FROM users WHERE age > 25;
This will retrieve all rows from the users
table where the age
column is greater than 25.
Using Logical Operators in WHERE Clause
SQLite allows the use of logical operators (AND
, OR
, NOT
) to combine multiple conditions.
SELECT * FROM table_name WHERE condition1 AND condition2;
Example:
SELECT * FROM users WHERE age > 25 AND name = 'Alice';
This will retrieve all rows where the age
is greater than 25 and the name
is ‘Alice’.
Sorting Results Using ORDER BY Clause
You can sort the result set using the ORDER BY
clause. By default, results are sorted in ascending order (ASC
). To sort in descending order, use DESC
.
SELECT * FROM table_name ORDER BY column_name [ASC|DESC];
Example:
SELECT * FROM users ORDER BY age DESC;
This will retrieve all rows from the users
table, sorted by the age
column in descending order.
Limiting the Number of Results
You can limit the number of rows returned using the LIMIT
clause.
SELECT * FROM table_name LIMIT number_of_rows;
Example:
SELECT * FROM users LIMIT 5;
This will retrieve the first 5 rows from the users
table.
Combining WHERE, ORDER BY, and LIMIT
You can combine the WHERE
, ORDER BY
, and LIMIT
clauses to filter, sort, and limit the results all at once.
SELECT column1, column2 FROM table_name WHERE condition ORDER BY column_name [ASC|DESC] LIMIT number_of_rows;
Example:
SELECT name, age FROM users WHERE age > 25 ORDER BY name ASC LIMIT 3;
This will retrieve the first 3 rows where the age
is greater than 25, ordered by name
in ascending order.
Using Aggregate Functions
SQLite supports several aggregate functions such as COUNT()
, SUM()
, AVG()
, MIN()
, and MAX()
.
Example - Counting Rows:
SELECT COUNT(*) FROM users;
This will return the number of rows in the users
table.
Example - Summing a Column:
SELECT SUM(age) FROM users;
This will return the sum of all age
values in the users
table.
Using GROUP BY
You can group rows that have the same values in specified columns using the GROUP BY
clause.
SELECT column1, COUNT(*) FROM table_name GROUP BY column1;
Example:
SELECT age, COUNT(*) FROM users GROUP BY age;
This will count how many users have the same age.
Using JOINs to Combine Data from Multiple Tables
SQLite supports INNER JOIN, LEFT JOIN, RIGHT JOIN, and FULL JOIN to combine data from multiple tables.
Example - INNER JOIN:
SELECT users.name, orders.order_date
FROM users
INNER JOIN orders ON users.id = orders.user_id;
This will join the users
table with the orders
table based on the id
of users
and the user_id
of orders
, returning the name
and order_date
of each user’s orders.
Using DISTINCT to Remove Duplicates
If you want to return only unique results, you can use the DISTINCT
keyword.
SELECT DISTINCT column1 FROM table_name;
Example:
SELECT DISTINCT age FROM users;
This will return a list of unique ages from the users
table.
Example with Multiple Clauses
SELECT name, age FROM users
WHERE age > 30
ORDER BY age DESC
LIMIT 5;
This query retrieves the name
and age
of the first 5 users with an age greater than 30, sorted by age
in descending order.
Conclusion:
Performing SELECT
queries in SQLite is simple and versatile. Here’s a quick summary of some key features:
- Basic SELECT: Retrieve data from one or more columns.
- Filtering: Use
WHERE
to filter results. - Sorting: Use
ORDER BY
to sort results. - Limiting: Use
LIMIT
to restrict the number of rows. - Aggregates: Use functions like
COUNT()
,SUM()
,AVG()
, etc. - Grouping: Use
GROUP BY
to group results. - Joins: Combine data from multiple tables with
JOIN
. - Distinct: Use
DISTINCT
to return unique rows.
These capabilities allow you to efficiently query SQLite databases for your application’s needs.
Question: What is the purpose of PRAGMA in SQLite?
Answer:
In SQLite, PRAGMA
is a special command used to modify the behavior of the database engine or to retrieve specific information about the database environment. It allows you to control various aspects of the SQLite database engine at runtime, such as configuration settings, performance optimizations, and database status.
PRAGMA
commands are unique to SQLite and are used primarily for:
- Changing Database Settings: You can adjust the behavior of the database, such as enabling or disabling foreign key constraints.
- Retrieving Information:
PRAGMA
can be used to query SQLite’s internal state, such as the schema or database settings. - Optimizing Performance: You can control settings that affect the performance of SQLite, such as cache size, synchronous mode, or locking behavior.
Common PRAGMA Commands in SQLite
1. PRAGMA foreign_keys
The PRAGMA foreign_keys
command is used to enable or disable foreign key constraint enforcement. By default, foreign key constraints are disabled in SQLite for backward compatibility reasons.
-
Enable Foreign Key Constraints:
PRAGMA foreign_keys = ON;
-
Disable Foreign Key Constraints:
PRAGMA foreign_keys = OFF;
-
Check Foreign Key Status:
PRAGMA foreign_keys;
Enabling foreign key support requires calling PRAGMA foreign_keys = ON;
every time a new connection is made to the database.
2. PRAGMA journal_mode
The journal_mode
command determines the journaling mode used by SQLite, which controls how the database handles transactions.
-
Default Journal Mode (DELETE):
PRAGMA journal_mode = DELETE;
-
WAL (Write-Ahead Logging) Mode:
PRAGMA journal_mode = WAL;
In WAL mode, writes are first written to a separate log file and later committed to the database, improving concurrent read and write performance.
-
Check Current Journal Mode:
PRAGMA journal_mode;
3. PRAGMA cache_size
The cache_size
command is used to set the number of pages in the cache. Increasing the cache size can improve the performance of database queries by reducing the need for disk I/O.
-
Set Cache Size (number of pages):
PRAGMA cache_size = 1000;
-
Check Current Cache Size:
PRAGMA cache_size;
Each page typically has a size of 1024 bytes, so setting cache_size
to 1000 would allocate 1,000,000 bytes of cache.
4. PRAGMA synchronous
The synchronous
command controls the level of synchronization used when writing data to the database. It determines how often SQLite will flush data to disk during transactions.
-
Full Sync (safest, slower):
PRAGMA synchronous = FULL;
-
Normal Sync (default):
PRAGMA synchronous = NORMAL;
-
Off Sync (fastest, least safe):
PRAGMA synchronous = OFF;
Using OFF
can speed up writes but increases the risk of data corruption if there is a power failure or crash during a write operation.
5. PRAGMA temp_store
The temp_store
command specifies where temporary files used by SQLite (like those created during sorting and indexing) should be stored.
-
Store Temporary Files in Memory:
PRAGMA temp_store = MEMORY;
-
Store Temporary Files on Disk:
PRAGMA temp_store = FILE;
-
Check Current Temp Store:
PRAGMA temp_store;
6. PRAGMA user_version
The user_version
command allows you to store and retrieve an arbitrary version number in the database. This is often used for managing schema versioning.
-
Set User Version:
PRAGMA user_version = 1;
-
Get User Version:
PRAGMA user_version;
7. PRAGMA integrity_check
The integrity_check
command is used to check the integrity of the database. It scans for any corruption or issues within the database schema.
-
Run Integrity Check:
PRAGMA integrity_check;
-
Output: If the database is intact, the result will be
ok
; otherwise, it will report any issues.
8. PRAGMA table_info
The table_info
command retrieves information about the columns in a table, such as column names, types, and whether they allow NULL
.
-
Get Table Information:
PRAGMA table_info(table_name);
For example, to get the columns in the users
table:
PRAGMA table_info(users);
9. PRAGMA foreign_key_list
The foreign_key_list
command returns the list of foreign key constraints on a table.
-
Get Foreign Key List:
PRAGMA foreign_key_list(table_name);
For example:
PRAGMA foreign_key_list(users);
This will show the foreign key constraints applied to the users
table.
Other Useful PRAGMA Commands
- PRAGMA compile_options: Lists all compile-time options used to build SQLite.
- PRAGMA locking_mode: Controls the locking mode of the database, which can affect how concurrent transactions are handled.
- PRAGMA page_size: Defines the size of each database page (default is typically 1024 bytes).
- PRAGMA optimize: Optimizes the database schema and performs certain internal optimizations.
Conclusion:
PRAGMA
commands in SQLite provide a powerful way to configure and query various aspects of the database engine. They enable you to optimize performance, enable or disable features, retrieve database settings, and perform maintenance tasks. Some of the most common uses include enabling foreign key constraints, managing transaction modes, optimizing performance settings (like cache size and journal modes), and checking database integrity.
By utilizing PRAGMA
, developers can fine-tune SQLite’s behavior to meet the specific requirements of their applications.
Question: How do you update data in an SQLite database?
Answer:
To update data in an SQLite database, you use the UPDATE
SQL statement. This command allows you to modify existing records in a table based on specific conditions, typically set using the WHERE
clause. If you don’t use a WHERE
clause, the update will affect all rows in the table, so it’s important to always specify the condition unless you intend to modify every record.
Basic Syntax of UPDATE Statement:
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
table_name
: The name of the table where you want to update the data.column1
,column2
: The columns that you want to update.value1
,value2
: The new values to be assigned to those columns.WHERE condition
: A condition that determines which rows should be updated. If omitted, all rows will be updated.
Examples:
1. Basic Update Example:
To update a single column (name
) in the users
table where the id
is 1:
UPDATE users
SET name = 'John Doe'
WHERE id = 1;
This query will change the name
of the user with id = 1
to ‘John Doe’.
2. Updating Multiple Columns:
You can update multiple columns at once by separating them with commas.
UPDATE users
SET name = 'Jane Doe', age = 30
WHERE id = 2;
This will update both the name
and age
of the user with id = 2
.
3. Updating All Records (No WHERE clause):
If you omit the WHERE
clause, all rows in the table will be updated:
UPDATE users
SET age = 25;
This will set the age
of every user in the users
table to 25.
4. Conditional Update with Multiple Conditions:
You can use logical operators like AND
, OR
, and NOT
to specify multiple conditions in the WHERE
clause.
UPDATE users
SET age = 35
WHERE name = 'John Doe' AND city = 'New York';
This will update the age
to 35 for users whose name
is ‘John Doe’ and who live in ‘New York’.
5. Using Subqueries for Update:
You can use a subquery to update data based on values from another table or query.
UPDATE users
SET age = (SELECT MAX(age) FROM users WHERE city = 'New York')
WHERE city = 'Los Angeles';
This will set the age
of all users in ‘Los Angeles’ to the maximum age of users from ‘New York’.
6. Using Parameterized Queries (with SQLite in Code):
When working with SQLite in a programming language (like Python, Java, etc.), it’s best practice to use parameterized queries to prevent SQL injection attacks.
In Python, using the sqlite3
library:
import sqlite3
# Connect to the SQLite database
conn = sqlite3.connect('example.db')
cursor = conn.cursor()
# Update query with placeholders for parameters
cursor.execute("UPDATE users SET name = ? WHERE id = ?", ('Alice', 1))
# Commit the transaction
conn.commit()
# Close the connection
conn.close()
This uses placeholders (?
) for the parameters, which are safely inserted into the query when executed, preventing SQL injection.
Important Notes:
-
Use the WHERE Clause: Always use the
WHERE
clause unless you want to update all rows in the table. Updating all records without specifying a condition can result in unintended changes. -
Transactions: For complex updates or when updating multiple rows, it’s a good practice to use transactions to ensure data consistency.
BEGIN TRANSACTION; UPDATE users SET age = 30 WHERE city = 'New York'; UPDATE users SET age = 40 WHERE city = 'Los Angeles'; COMMIT;
This ensures that all updates are applied as a single unit, and in case of an error, changes can be rolled back.
-
Data Types: Make sure the values you’re updating match the expected data types for each column. For example, don’t try to update a
TEXT
column with a number or aDATE
column with text that doesn’t represent a valid date.
Conclusion:
The UPDATE
statement in SQLite is used to modify existing data in a table. You can update one or more columns, apply conditions with the WHERE
clause, and even use subqueries for more complex updates. Always be cautious when updating data, especially when omitting the WHERE
clause, as it can modify all rows in the table. Additionally, using parameterized queries when working with databases in your application code is a good practice to ensure security.
Question: How do you delete data from an SQLite table?
Answer:
To delete data from an SQLite table, you use the DELETE
SQL statement. This command allows you to remove one or more rows from a table based on a specified condition. If you omit the WHERE
clause, all rows in the table will be deleted, so it’s important to always specify the condition unless you intend to delete every record.
Basic Syntax of DELETE Statement:
DELETE FROM table_name
WHERE condition;
table_name
: The name of the table from which you want to delete data.condition
: A condition that determines which rows should be deleted. If omitted, all rows will be deleted.
Examples:
1. Basic Delete Example:
To delete a row where the id
is 1 from the users
table:
DELETE FROM users
WHERE id = 1;
This query will delete the user with id = 1
from the users
table.
2. Deleting Multiple Rows:
You can delete multiple rows based on a condition using logical operators in the WHERE
clause.
DELETE FROM users
WHERE city = 'New York';
This will delete all users who live in ‘New York’.
3. Delete All Records (No WHERE clause):
If you want to delete all records in a table, you can omit the WHERE
clause. Be cautious when using this, as it will remove every row in the table.
DELETE FROM users;
This will remove all users from the users
table but keep the table structure intact (i.e., the table will remain empty).
4. Deleting Rows Based on Multiple Conditions:
You can use logical operators like AND
, OR
, and NOT
to specify more complex conditions.
DELETE FROM users
WHERE city = 'Los Angeles' AND age > 30;
This will delete all users who live in ‘Los Angeles’ and are older than 30.
5. Using Subqueries in DELETE:
You can also use a subquery in the DELETE
statement to remove rows based on the result of another query.
DELETE FROM users
WHERE id IN (SELECT id FROM users WHERE city = 'Chicago' AND age < 25);
This will delete all users who are under 25 years old and live in ‘Chicago’.
Important Notes:
-
Use the WHERE Clause: As with the
UPDATE
statement, always use theWHERE
clause to specify which rows to delete. If you omit theWHERE
clause, all rows in the table will be deleted. -
Transactions: If you are deleting multiple rows or performing complex delete operations, it’s a good practice to use transactions to ensure that the changes are applied atomically. In case of an error, you can roll back the changes.
BEGIN TRANSACTION; DELETE FROM users WHERE city = 'New York'; DELETE FROM users WHERE age < 25; COMMIT;
This ensures that either all deletions are applied successfully or none if an error occurs.
-
Referential Integrity: If your table has foreign key constraints, deleting a row may violate referential integrity. In such cases, SQLite can either reject the delete operation or cascade the delete (remove related rows in other tables). You can control this behavior by enabling foreign key support in SQLite (
PRAGMA foreign_keys = ON;
) and specifying the appropriate actions (e.g.,ON DELETE CASCADE
) when defining the foreign key relationships. -
SQLite
TRUNCATE
vsDELETE
: SQLite does not support theTRUNCATE
statement, which is used in other databases to quickly remove all rows from a table. In SQLite, you would useDELETE FROM table_name
to achieve the same effect, but be aware thatDELETE
is slower thanTRUNCATE
in larger datasets because it involves transaction logging.
Conclusion:
The DELETE
statement in SQLite is used to remove data from a table. By specifying a WHERE
clause, you can delete specific rows, while omitting it will remove all rows in the table. As with other database operations, it’s important to use caution when deleting data and to ensure that you are not inadvertently removing more records than intended. For complex delete operations, you can use transactions to maintain data integrity.
Read More
If you can’t get enough from this article, Aihirely has plenty more related information, such as sqlite interview questions, sqlite interview experiences, and details about various sqlite job positions. Click here to check it out.