Random values are not getting inserted in SQLite Table

72 Views Asked by At

I have made a database in SQLite, and a Table. Schema is like this:

CREATE TABLE Students (
    StudentID INTEGER PRIMARY KEY,
    FirstName TEXT NOT NULL,
    LastName TEXT NOT NULL,
    Gender TEXT CHECK (Gender IN ('Male', 'Female', 'Other')),
    Age INTEGER,
    RegistrationDate DATE
);

I have tried to run some queries to insert 1000 row data manually but age and data are giving weird values. This is the query:

WITH RECURSIVE
  cnt(x) AS (
     SELECT 1
     UNION ALL
     SELECT x+1 FROM cnt
     WHERE x<1000
  )
INSERT INTO Students (FirstName, LastName, Gender, Age, RegistrationDate)
SELECT
    'FirstName' || x,
    'LastName' || x,
    CASE WHEN x % 3 = 0 THEN 'Male' WHEN x % 3 = 1 THEN 'Female' ELSE 'Other' END,
    CAST(18 + ROUND(RANDOM() * 10) AS INTEGER), -- Age between 18 and 28
    DATE('now', '-' || ROUND(RANDOM() * 365, 0) || ' days') -- Random registration date in the last year
FROM cnt;

and this is the result of the values when i select * from Students;


1|FirstName1|LastName1|Female|-9223372036854775808|
2|FirstName2|LastName2|Other|9223372036854775807|
3|FirstName3|LastName3|Male|-9223372036854775808|
4|FirstName4|LastName4|Female|-9223372036854775808|
5|FirstName5|LastName5|Other|9223372036854775807|
6|FirstName6|LastName6|Male|-9223372036854775808|
7|FirstName7|LastName7|Female|-9223372036854775808|
8|FirstName8|LastName8|Other|-9223372036854775808|

2

There are 2 best solutions below

0
On

Read the documentation:

The random() function returns a pseudo-random integer between -9223372036854775808 and +9223372036854775807.

So, the solution is to use modulo:

ABS(RANDOM()) % 11 + 18, -- Age between 18 and 28

Similarly for the date:

DATE('now', '-' || (ABS(RANDOM()) % 366) || ' days') -- Random registration date in the last year
0
On

I have updated the logic by using modulus(%). Here is the sample code:

WITH RECURSIVE
  cnt(x) AS (
     SELECT 1
     UNION ALL
     SELECT x+1 FROM cnt
     WHERE x<1000
  )
INSERT INTO Students (FirstName, LastName, Gender, Age, RegistrationDate)
SELECT
    'FirstName' || x,
    'LastName' || x,
    CASE WHEN x % 3 = 0 THEN 'Male' WHEN x % 3 = 1 THEN 'Female' ELSE 'Other' END,
    18 + ABS(CAST(RANDOM() % 11 AS INTEGER)), -- Age between 18 and 28
    DATE('now', '-' || (ABS(RANDOM()) % 365) || ' days') -- Random registration date in the last year
FROM cnt;

Here is sample output:

enter image description here

Here is the dbfiddle