To start with a very simple query: we would like to know how many movies are in the Video Library. In the 4D language, the code would be:
C_LONGINT($AllMovies)
$AllMovies:=0
ALL RECORDS([MOVIES])
$AllMovies:=Records in selection([MOVIES])
ALERT("The Video Library contains "+String($AllMovies)+" movies")
- As you can see, you can receive the result of the query in a variable (in our case $AllMovies) that is enclosed between "<<" and ">>".
Another way to reference any type of valid 4D expression (variable, field, array, “expression…”) is to place a colon ":" in front of it:
C_LONGINT($AllMovies)
$AllMovies:=0
Begin SQL
SELECT COUNT(*)
FROM MOVIES
INTO :$AllMovies
End SQL
ALERT("The Video Library contains "+String($AllMovies)+" movies")
Special attention should be paid to inter-process variables, where the notation is a little bit different: you must place an inter-process variable between "[" and "]":
C_LONGINT($AllMovies)
<>AllMovies:=0
Begin SQL
SELECT COUNT(*)
FROM MOVIES
INTO <<[<>$AllMovies]>>
End SQL
ALERT("The Video Library contains "+String(<>AllMovies)+" movies")
- The second way to interact with the SQL engine is using integrated generic SQL (ODBC compatible) commands. Thus the simple query above becomes:
C_LONGINT($AllMovies)
$AllMovies:=0
SQL LOGIN(SQL_INTERNAL;"";"")
SQL EXECUTE("SELECT COUNT(*) FROM MOVIES";$AllMovies)
SQL LOAD RECORD(SQL all records)
SQL LOGOUT
ALERT("The Video Library contains "+String($AllMovies)+" movies")
For more information concerning generic SQL commands, please refer to SQL section of the 4D Language Reference manual.
- The third way to interact with the new SQL engine is using the 4D QUERY BY SQL command. In this situation, the simple query above becomes:
C_LONGINT($AllMovies)
$AllMovies:=0
QUERY BY SQL([MOVIES];"ID <> 0")
$AllMovies:=Records in selection([MOVIES])
ALERT("The Video Library contains "+String($AllMovies)+" movies")
In fact, the QUERY BY SQL command can be used to execute a simple SELECT query that can be written as follows:
SELECT *
FROM myTable
WHERE <SQL_Formula>
myTable is the name of the table passed in the first parameter and SQL_Formula is the query string passed as the second parameter:
QUERY BY SQL(myTable;SQL_Formula)
In our case there is no WHERE clause, so we forced one: "ID <> 0". The equivalent in SQL for the whole query would be:
SELECT *
FROM MOVIES
WHERE ID <> 0
To test all the above examples, launch the "4D SQL Code Samples" database and go to the main dialog box. On the left side of the dialog, you can choose the query mode:

Then press the SQL query results in variables button.