Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I am looking for a neat way to combine consecutive number ranges in a single select statement. Say my table has these records: ``` first_number last_number 0 9 10 19 20 29 40 49 50 59 70 79 ``` Then output shall be as follows: ``` first_number last_number 0 29 40 59 70 79 ``` This is what I've com...
Please try: ``` with T1 as ( select row_number() over (order by first_number) RNum, first_number, last_number From yourtable ) ,T (RNUM, first_number, last_number, CNT) as ( select T1.*, 1 CNT from T1 where RNum=1 union all SELECT b.RNUM, b.first_number, b.last_number, (case when b.firs...
Here is another approach, which will give you desired output. ``` select min(first_number) as first_number , max(last_number) as last_number from ( select first_number , last_number , sum(grp) over(order by first_number) as grp from ( select first_number ...
How to combine consecutive number ranges
[ "", "sql", "oracle", "" ]
I have this query: ``` INSERT INTO emailevents (shopid, userid, emailid, campaignid, variationid, type, createdon) VALUES ($1, (SELECT id FROM users WHERE mongoid=$2), (SELECT id FROM emails WHERE mongoid=$3), (SELECT id FROM campaigns WHERE mongoid=$4) AS cid, (SELECT id FROM campaignvariations W...
Try to change to `select` instead of `values` as below ``` INSERT INTO emailevents (shopid, userid, emailid, campaignid, variationid, type, createdon) select $1, (SELECT id FROM users WHERE mongoid=$2), (SELECT id FROM emails WHERE mongoid=$3), (SELECT id FROM campaigns WH...
One fix is to change the `values` to a `select`: ``` INSERT INTO emailevents (shopid, userid, emailid, campaignid, variationid, type, createdon) select $1, (SELECT id FROM users WHERE mongoid=$2), (SELECT id FROM emails WHERE mongoid=$3), (SELECT id FROM campaig...
Syntax error for insert query alias in Postgres
[ "", "mysql", "sql", "postgresql", "" ]
**I have this query:** ``` SELECT id,id1,title FROM tablename LEFT JOIN tablename AS parent ON tablename .id1 = parent.id WHERE parent.id is NULL ``` What I try to achieve is that only rows are shown from which no parent exist. **Table layout and content** ``` id id1(parent) title 1 ...
This ``` SELECT child.id,child.id1,child.name FROM table AS child --alias names, as column names would be ambiguous LEFT JOIN table AS parent ON table.id1 = parent.id WHERE parent.id is NULL -- only no parent! ``` Shows the *orphans*. To get all non-orphans ``` SELECT child.id,child.id1,child.name FROM tabl...
Your query looks correct, except you need table aliases for the columns in the `select`: ``` SELECT table.id, table.id1, table.name FROM table LEFT JOIN table AS parent ON table.id1 = parent.id WHERE parent.id is NULL ; ``` The problem is that both `table` and `parent` have the same columns. The engine do...
Mysql only select row with existing parent
[ "", "mysql", "sql", "subquery", "left-join", "" ]
**Background** * Framework: Codeignighter/PyroCMS I have a DB that stores a list of products, I have a `duplicate function` in my application that first looks for the common product name so it can add a '`suffix`' value to the duplicated product. **Code in my Products model class** ``` $product = $this->get($id); ...
Let's do some testing about this. Here is what you are doing ``` $count = $this->db->like('name', $product->name)->get('products')->num_rows(); ``` And i suspect `$product->name` contains this. Harry's Book As we know this is coming from the database table as you are using. Where you are using the upper query ment...
Other answers didn't work for me, this does though: ``` $count = $this->db->query("SELECT * FROM `default_firesale_products` WHERE `title` LIKE '".addslashes($product['title'])."'")->num_rows(); ``` Whenever CI Active Record mangles your queries you can always just put a raw query in instead and have full control.
Active record query failed - Escape quote from query
[ "", "sql", "codeigniter", "activerecord", "pyrocms", "" ]
I wish to replace all occurrences of `?` with a single empty space within a table for all columns. Example: ``` This is a?string ``` would become ``` This is a string ``` Currently I have found out how to do it for one column only ``` UPDATE tableName SET columnName = REPLACE(columnName,'"','\'') ``` Is there...
Try before you buy: ``` SELECT Replace(columnName1, '?', ' ') , Replace(columnName2, '?', ' ') , Replace(columnName3, '?', ' ') FROM your_table ``` Then update if you're happy with the results ``` UPDATE your_table SET columnName1 = Replace(columnName1, '?', ' ') , columnName2 = Replace(columnNam...
You cannot do it for all columns automatically, you'll need to list the columns individually, but you can still do it with one statement: ``` UPDATE tableName SET columnName1 = REPLACE(columnName1,'"','\''), columnName2 = REPLACE(columnName2,'"','\''), columnName3 = REPLACE(columnName3,'"','\''), ...
String replace within SQL statement
[ "", "mysql", "sql", "" ]
I'm having a problem getting the rows I need from my database. The question is simple: I have a table with customer data in it. Now I want to do a mailing (via post) to all my customers, but I only want to send it to every address once. So if any customers live on the same address (street, number, postal code, city) I...
``` SELECT title , last_name , first_name , address_line_1 , address_line_2 , etc FROM ( SELECT title , last_name , first_name , address_line_1 , address_line_2 , etc , Row_Number() OVER (PARTITION BY addres...
Here's how I would do something like this in Oracle: ``` --Create testing table CREATE TABLE UniqueValTest ( fname NVARCHAR2(100), lname NVARCHAR2(100), address NVARCHAR2(100), city NVARCHAR2(50), state NVARCHAR2(2), zip NVARCHAR2(5), age NUMBER, recid NUMBER ); --Create sample data INSERT INTO Uniq...
SQL select rows with unique values
[ "", "sql", "" ]
SO, **The problem** I have an issue with rows multiplication. In SQL, there is a `SUM()` function which calculates sum for some field for set of rows. I want to get multiplication, i.e. for table ``` +------+ | data | +------+ | 2 | | -1 | | 3 | +------+ ``` that will be `2*(-1)*3 = -6` as a result. I'm usi...
If you need this type of calculations often, I suggest you store the signs and the logarithms in separate columns. The signs can be stored as `1` (for positives), `-1` (for negatives) and `0` (for zero.) The logarithm can be assigned for zero as `0` (or any other value) but it should not be used in calculations. The...
I guess this would work... ``` SELECT IF(MOD(COUNT(data < 0),2)=1 , EXP(SUM(LOG(data)))*-1 , EXP(SUM(LOG(data)))) x FROM my_table; ```
Get rows product (multiplication)
[ "", "mysql", "sql", "" ]
I have following tables: **Mall:** ``` +-----------+----------------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-----------+----------------------+------+-----+---------+----------------+ | MallID | smallint(5) unsigned | NO | PRI ...
Your queries do what you expect. I would write the second using ANSI standard `join` syntax and encourage you to use abbreviations as table aliases: ``` select Name from Mall m where 0 = (select count(*) from Customer c join Store s on Mall.MallID = Store.MallID ...
They're correct, but there are better (IMHO) ways to write them: ``` SELECT m.* FROM Mall m JOIN (SELECT MallID, SUM(Revenue) totalRev FROM Store GROUP BY MallID HAVING totalRev > 100000) s ON s.MallID = m.MallID SELECT m.Name FROM Mall m LEFT JOIN (SELECT DISTINCT s.MallID FROM Customer ...
Are these queries correct?
[ "", "mysql", "sql", "foreign-keys", "subquery", "" ]
I have written a program where i can do a Request for an identification card. There are different types of identification cards ( Red, Blue, Green ) While the request, the program should generate identification numbers. The numbers (Range of the numbers) depends on which card are requested. ``` Red Card: 1 - 50000 ...
Edit #1: I updated trigger (`IF UPDATE`), stored procedure and last two examples. ``` CREATE TABLE dbo.CustomSequence ( CustomSequenceID INT IDENTITY(1,1) PRIMARY KEY, SequenceName NVARCHAR(128) NOT NULL, -- or SYSNAME UNIQUE(SequenceName), RangeStart INT NOT NULL, RangeEnd INT NOT NULL, ...
You can use instead of insert trigger for this ``` create table Cards_Types (Color nvarchar(128) primary key, Start int); create table Cards (ID int primary key, Color nvarchar(128)); insert into Cards_Types select 'RED', 0 union all select 'BLUE', 50000 union all select 'GREEN', 100000; create trigger utr_Cards_Ins...
Create Sequence in MS SQL Server 2008
[ "", "sql", "sql-server", "sql-server-2008", "" ]
i have a problem with mysql 5.6 version. Sorry if my english sucks, and sorry if the format is not the right one, im in a hurry. Mysql throws me this error "#1241 - Operand should contain 1 column(s)" from this query: ``` SELECT DISTINCT (P.`P_nombre`, P.`P_raza`) FROM `Perros` AS P, `Adiestramientos` as ...
You're using `A` identifier for the same table twice - in both inner and outer query. Change one into different, e.g. `A2`: ``` SELECT DISTINCT P.`P_nombre`, P.`P_raza` FROM `Perros` AS P, `Adiestramientos` as A WHERE P.`P_codigo` = A.`P_codigo` AND A.`A_nroLegajo` = '1500' AND P.`P_codigo` NOT IN( ...
The [error](http://dev.mysql.com/doc/refman/5.0/en/subquery-errors.html) which you get means that:- MySQL does not support statements of the following form: ``` SELECT * FROM t1 WHERE s1 IN (SELECT s2 FROM t2 ORDER BY s1 LIMIT 1) ``` In your case you have to change the indentifier A as it is used twice. Try this:- ...
#1241 - Operand should contain 1 column(s) IN
[ "", "mysql", "sql", "distinct", "mysql-error-1241", "" ]
The SQL below fails and gives me an error: ``` Incorrect syntax near '-'. ``` The variable valu1 is a GUID that has "-" characters in it. I am using it as a varchar ``` Declare @valu1 as varchar(1000) Declare @valu2 as varchar(200) Declare @sqlStr as nvarchar(2000) Select @valu1 = GUID, @val...
``` SET @sqlStr =N'Insert Into dbo.table1 Select newid() as ChangeID, GETDATE() as DateModified, a.col1 as col1, c.col2 as col2, ...
Please try putting more quotes around the variables: ``` ''' + @valu1 + ''' as valu1 ```
Dynamic tsql error
[ "", "sql", "sql-server", "t-sql", "" ]
I am new to Oracle Sql and facing an issue : I want to create a temporary table inside procedure . LIKE: ``` CREATE PROCEDURE P AS BEGIN CREATE TEMPORARY TABLE A(ID int); END P; ``` BUT THIS IS GIVING ME AN ERROR How Can I Create a temporary table inside procedure. I have seen other answers on stackover...
You could use Dynamic SQL with [EXECUTE IMMEDIATE](http://docs.oracle.com/cd/B28359_01/appdev.111/b28370/executeimmediate_statement.htm): ``` CREATE OR REPLACE PROCEDURE p AS BEGIN EXECUTE IMMEDIATE 'CREATE TEMPORARY TABLE A(id NUMBER)...etc'; END p; ``` Edit: Obviously you'll have to ensure your syntax is correct...
Why do you want to create a temporary table in a stored procedure in the first place? It is relatively common to create temporary tables in other databases (SQL Server and MySQL, for example). It is very, very rare to do the same thing in Oracle. In almost every case where you are tempted to create a temporary table i...
Oracle Sql : Procedure which can create temporary tables inside it
[ "", "sql", "oracle", "stored-procedures", "" ]
I have a table my\_table that has columns state, month, ID, and sales. My goal is to merge different rows that have the same state, month, ID into one row while summing the sales column of these selected rows into the merged row. For example: ``` state month ID sales ------------------------------- FL ...
You need to use `GROUP_CONCAT` for that: ``` SELECT GROUP_CONCAT(DISTINCT State) AS State , Month, ID, SUM(Sales) FROM Table1 GROUP BY Month, ID; ``` ### See [this SQLFiddle](http://sqlfiddle.com/#!2/a90ef/6) --- ### Update (For SQL Server) For SQL Server you can use `STUFF()` for that: ``` SELECT state = ...
Please try this: ``` SELECT B.STATE, A.ID, SUM(A.SALES) AS SALES FROM MYTABLE A INNER JOIN (SELECT DISTINCT CASE WHEN A.state = B.STATE THEN A.STATE ELSE A.STATE+','+B.STATE END AS STATE, ID FROM MYTABLE A INNER JOIN MYTABLE B ON A.ID = B.ID) B ON A.STATE = B.STATE GROUP BY B.state, A.month, A.ID ``` ...
Aggregate with row merge
[ "", "mysql", "sql", "" ]
This query works fine for each and every test case if you choose the person's last name: ``` SELECT P.Patient_ID, P.Person_FirstName, P.Person_LastName , H.Height , W.Weight , CASE when H.Height is not null then W.Weight / (H.Height * H.Height) else null END as BMI FROM VIEW_Bill...
Change it to this: ``` SELECT P.Patient_ID, P.Person_FirstName, P.Person_LastName , H.Height , W.Weight , CASE when H.Height != 0 then W.Weight / (H.Height * H.Height) else null END as BMI FROM VIEW_BillPatient P LEFT JOIN H on P.Patient_ID = H.Patient_ID LEFT JOIN W on P...
You could use `nullif(expr1,expr2)`. > Returns a null value if the two specified expressions are equal. In this case, `BMI` will be `null` if `height` is `0` or `null` or if `weight` is `null` ``` SELECT P.Patient_ID, P.Person_FirstName, P.Person_LastName , H.Height , W.Weight , W.Weight / nullif(H.Heigh...
Divide by zero with SQL
[ "", "sql", "sql-server", "" ]
This is just purely for eye candy while working with SQLite in the terminal, but is there a way to format column width with headers so that each header is resized appropriately (and independently of the other columns)? In other words, here's the output with ``` .width auto ``` for a simple table ``` Id Name...
The `sqlite3` tool has no such function. You would have to compute the column widths by hand (`SELECT max(length(col1)) ...`).
For "human readable" output, you can use `column` mode, and turn `header` output on. That will get you something similar to the `sqlplus` output in your examples: ``` sqlite> select * from foo; 234|kshitiz|dba.se sqlite> .mode column sqlite> select * from foo; 234 kshitiz dba.se sqlite> .headers on sqlit...
SQLite3 Terminal Output Formatting .width
[ "", "sql", "sqlite", "terminal", "formatting", "" ]
I have 2 procedures: `A` and `B`. `A` calls `B` and `B` calls `A`. I need to block calling if the procedure is already called from another one. How to check that?
MySQL [user-defined variables](http://dev.mysql.com/doc/refman/5.6/en/user-variables.html) are global to your session. So you could set a variable to TRUE in procedure A and then check it in procedure B. Procedure A: ``` BEGIN IF NOT @called = 1 THEN SET @called := 1; CALL B(); SET @called := NULL; E...
as variant you may check some value from table IsExecFromA. And Check this in proc B. If IsExecFromA = true then not exec again proc A etc. u?
How to break recursive calls between procedures on MySQL?
[ "", "mysql", "sql", "" ]
I'm trying to pull all records that have the engineer and has an overall score of 16 or higher. value\_money, quality\_service, friendliness, response\_time are all fields in the same table. I'm trying to add all these and perform a WHERE. This is what I've got so far ``` SELECT *, value_money+quality_service+frien...
Alias cannot be used in `WHERE`. Do either ``` SELECT *, value_money+quality_service+friendliness+response_time AS overall FROM feedback WHERE engineer LIKE '%Chris Gauden%' AND value_money+quality_service+friendliness+response_time < 16 ORDER BY date DESC LIMIT 0, 15 ``` or ``` SELECT * FROM ( SELECT *, value_mone...
You cannot use alias in there WHERE clause. You have to use full `value_money+quality_service+friendliness+response_time` combination.
Where multi column adds up over 16
[ "", "mysql", "sql", "" ]
I''ll explain what I need to do on example. First of all, we have a simple table like this one, named *table*: ``` id | name ===+===== 1 | foo 1 | bar 1 | foobar 2 | foo 2 | bar 2 | foobar ``` Now the query: ``` SELECT t.* FROM table t GROUP BY t.id ``` Will get us result similar to this one: ``` id | name =...
Using MySQL you can use [GROUP\_CONCAT(expr)](http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat) > This function returns a string result with the concatenated non-NULL > values from a group. It returns NULL if there are no non-NULL values. > The full syntax is as follows: ``` GROUP_...
For SQL Server (**before** 2017) use [`FOR XML`](https://learn.microsoft.com/en-us/sql/relational-databases/xml/for-xml-sql-server) clause and [`STUFF()`](https://learn.microsoft.com/en-us/sql/t-sql/functions/stuff-transact-sql) function for that: ``` SELECT distinct id, name = STUFF((SELECT ' , ' + name ...
GROUP BY but get all values from other column
[ "", "sql", "group-by", "" ]
What would be an effective way to add an integer column when a certain value in the rows are the same? For instance, say I have a table with scores of two different players. ``` id | score | player_id 1 5 1 2 6 1 3 9 2 4 3 2 ``` How can I add the player's score based o...
I think you want `GROUP BY` ``` SELECT player_id, SUM(score) totalScore FROM tablename GROUP BY player_id ``` * [SQLFiddle Demo](http://sqlfiddle.com/#!2/1d899/2) OUTPUT ``` ╔═══════════╦════════════╗ ║ PLAYER_ID ║ TOTALSCORE ║ ╠═══════════╬════════════╣ ║ 1 ║ 11 ║ ║ 2 ║ 12 ║ ╚══════...
You may try like this:- ``` SELECT player_id, SUM(score) as Sums FROM tablename GROUP BY player_id ```
Effective way to add Integers based on table values
[ "", "mysql", "sql", "" ]
I have two tables in SQL Server 2008 - ``` Sales.SalesOrderHeader --> CustomerID(FK, int, not null), OrderDate (datetime, not null), etc... Sales.Individual --> CustomerID(PK, FK, int, not null), ContactID (FK, int, not null), etc... ``` I have to find the the customers (ie CustomerID and the Corresponding ContactID)...
In JOINs RDBMS can create an execution plan which makes it faster as compared to sub query. In many cases you will find that JOINS are comparatively faster than subquery. However when they are functionaly equivalent, they will perform the same. Subquery loads all the data for processing [MSDN](http://msdn.microsoft.co...
Join is generally preferred to the multi-level nesting with subqueries. In general joins are faster as SQL server Engine can better optimize this type of query.
Which is better - subqueries only or joins?
[ "", "sql", "sql-server", "join", "subquery", "" ]
I'm having a difficult time understanding "on delete cascade" If I had the following example: create table X (id int primary key, name char(10)); create table Y (bid int primary key, aid references A(id) on delete cascade); X contains one row (111, 'Mike') Y contains two rows (1000, 111), (2000, 111)\*\* I if remo...
It would be deleted and nothing else would happen. Cascading deletes only go from the referenced table to the referencing table. So a delete on table X will cascade a delete down to table y, while a delete on table y has no impact on table x.
Nothing will happen, only if you delete a row from table X the rows in table Y referencing it will be deleted.
"On Delete Cascade" if deleting a row from the child table
[ "", "mysql", "sql", "foreign-keys", "sqlcommand", "cascading-deletes", "" ]
I want to make sure that an email is sent exactly once, so I'm using the following statement in Oracle SQL: ``` update mytable set mail_sent = 't' where id = ? and mail_sent = 'f' ``` and examining the number of rows modified. If no rows were modified, then another process did the same thing first and will send the m...
There's a set of Tom Kyte's excellent articles about what happens during a concurrent update, which are worth reading: * <http://tkyte.blogspot.ru/2005/08/something-different-part-i-of-iii.html> * <http://tkyte.blogspot.ru/2005/08/part-ii-seeing-restart.html> * <http://tkyte.blogspot.ru/2005/09/part-iii-why-is-restart...
One safe way to do this is to select the row for update, which takes an exclusive lock on the row, send the email, then update the record to 't' and commit. The locking of the record is a deliberate design aim of this method. Until the email is confirmed to be sent you do not want to indicate that you have sent it, ot...
Are update statements safe from race conditions?
[ "", "sql", "oracle", "" ]
I have this query and I want to remove results that are = 0. ``` declare @Teacher as nvarchar(50) ='Professor David' select 'Science Class' as 'Study Type', (select Count(Distinct StudentID) from Table_class_SClass where Grade = 'Passed' and Teacher= @Teacher) as 'Number of Passing Students' union select 'Science L...
You can take your existing query and make it a subquery. Then, you can use a `where` clause to do the filtering: ``` select t.* from (select 'Science Class' as [Study Type], (select Count(Distinct StudentID) from Table_class_SClass where Grade = 'Passed' and Teacher= @Teacher) as [Number of Passing Stud...
You can try adding this line at the end of each query `group by teacher having count(Distinct StudentID) > 0` This will return only records which has count more than 1 ``` select 'Science Class' as [Study Type], (select Count(Distinct StudentID) from Table_class_SClass where Grade = 'Passed' and Teacher= ...
How To Remove Results from multiple selection statements that are equal to 0
[ "", "sql", "count", "distinct", "" ]
I am trying to add a group by SC\_FRAMES.GROUPPRODUCTTYPE to this statement: ``` SELECT SC_JOBS.CREATIONDATE, (SELECT SUM(SC_JOBS.GROSSEXCLVAT) FROM SC_JOBS WHERE SC_FRAMES.GROUPPRODUCTTYPE = 'ABC' AND SC_FRAMES.JOBID = SC_JOBS.JOBSID AND SC_JOBS.INVOICEDATE < '1990-01-01') AS Product1, (SELECT SUM(SC_JOBS....
I think you want a query like this: ``` SELECT f.GROUPPRODUCTTYPE, MIN(j.CREATIONDATE), SUM(case when j.INVOICEDATE < '1990-01-01' then j.GROSSEXCLVAT else 0 end) as Product1 FROM SC_JOBS INNER j JOIN SC_FRAMES f ON f.JOBID = j.JOBSID WHERE j.CREATIONDATE BETWEEN :StartDate AND :EndD...
Try this: ``` SELECT SC_JOBS.CREATIONDATE, (SELECT SUM(SC_JOBS.GROSSEXCLVAT) FROM SC_JOBS WHERE SC_FRAMES.GROUPPRODUCTTYPE = 'ATI' AND SC_FRAMES.JOBID = SC_JOBS.JOBSID AND SC_JOBS.INVOICEDATE < '1990-01-01') AS Product 1, (SELECT SUM(SC_JOBS.GROSSEXCLVAT) FROM SC_JOBS WHERE SC_FRAMES.GROUPPRODUCTTYPE = 'ATI' ...
how to group by with a sql that has multiple subqueries
[ "", "mysql", "sql", "fastreport", "" ]
I'm using cakePHP to create a todo-application. CakePHP creates queries for you etc. That's why there must be no typo. The error: ``` Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Projecttask.projecttasks_name' in 'field list' ``` The query: ``` SQL Query: SELECT `Itemrequirement`.`itemreq_id`, `Pr...
You are using `projecttasks` twice ``` LEFT JOIN `gtd`.`projecttasks` AS `ProjecttaskParent` ... LEFT JOIN `gtd`.`projecttasks` AS `ProjecttaskChild` ... ``` but with aliases `ProjecttaskParent` and `ProjecttaskChild`, so you must use an alias instead of the table name ``` `ProjecttaskParent`.`projecttasks_name` ``...
You are selecting from database name ProjectTask and you use an alias (ProjectTaskParent and ProjectTaskChild) Your query should be: ``` SELECT `Itemrequirement`.`itemreq_id`, `ProjecttaskParent`.`projecttasks_name` FROM `gtd`.`itemrequirements` AS `Itemrequirement` LEFT JOIN `gtd`.`projecttasks` AS `ProjecttaskParen...
Column not found: 1054 Unknown column - NO TYPOS NOR WRONG ' ` "
[ "", "mysql", "sql", "database", "cakephp", "" ]
I have a table like this: ``` ------------------------------- EMP ID|Country |Emp Level | ------|-----------|-----------| 102 |UK |Staff | 103 |US |Admin Staff| 104 |CA |Staff | 105 |NL |Admin Staff| 106 |MN |Intern | 107 |IN |Staff | 1...
``` SELECT Country, EmpLevel, COUNT(*) AS Count FROM my_table WHERE Country IN ('UK', 'US', 'CA') GROUP BY Country, EmpLevel UNION SELECT 'Global', EmpLevel, COUNT(*) AS Count FROM my_table WHERE Country NOT IN ('UK', 'US', 'CA') GROUP BY EmpLevel ``` See it on [sqlfiddle](http://sqlfiddle.com/#!2/...
Have you tried this? ``` select country as cou, emp_level as emp, count(*) from your_table where country in ('UK', 'US', 'CA') group by cou, emp order by cou, emp union select 'global', emp_level as emp, count(*) from your_table where country not in ('UK', 'US', 'CA') group by emp order by emp ```
Group countries together and count
[ "", "mysql", "sql", "sql-server", "database", "" ]
I am curious about what is making my query slow and a question came into my mind. Which one is faster and more efficient? `LEFT()` or `SUBSTRING()`?
SQL Server is a database. You dod not ask questions of which string processing function is 'faster'. You ask the questions 'which can use an index?' and 'do I have the required index?'. Is all about data access, because disks are sloooooow, not about shifting CPU registers. So, **Which can use an index?** (which one i...
There is no difference at all between `left` and `substring` because `left` is translated to `substring` in the execution plan. For example: ``` select substring(col, 1, 2), left(col, 3) from YourTable ``` will look like this in the execution plan ``` <DefinedValue> <ColumnReference Column="Expr1004" /> ...
Performance of SUBSTRING vs LEFT in SQL Server
[ "", "sql", "sql-server", "" ]
I am trying to figure out the SQL to do a running total for a daily quota system. The system works like this... Each day a user gets a quota of 2 "consumable things". If they use them all up, the next day they get another 2. If they somehow over use them (use more than 2), the next day they still get 2 (they can't hav...
Try creating custom aggregate function like: ``` CREATE FUNCTION quota_calc_func(numeric, numeric, numeric) -- carry over, daily usage and daily quota RETURNS numeric AS $$ SELECT GREATEST(0, $1 + $3 - $2); $$ LANGUAGE SQL STRICT IMMUTABLE; CREATE AGGREGATE quota_calc( numeric, numeric ) -- daily usage and daily q...
> they can't have a negative balance That triggered my memory :-) I had a similar problem >10 years ago on a Teradata system. The logic could be easily implemented using recursion, for each row do: > add 2 "new" and substract x "used" quota, if this is less than zero > use zero instead. I can't remember how i foun...
Running total... with a twist
[ "", "sql", "postgresql", "" ]
I was wondering, what is the difference between these two scripts? ``` SELECT * FROM ##TEMP ``` and this ``` SELECT * FROM #TEMP ```
`##TEMP` is global temporary table, `#TEMP` is local. **Local temporary tables** are visible only to their creators during the same connection to an instance of SQL Server as when the tables were first created or referenced. Local temporary tables are deleted after the user disconnects from the instance of SQL Server....
The first one (##TEMP) is global - anyone can access it's content and also you can from different sessions (think of tabs in SQL Server Management Studio). The other is only visible by you.
MS SQL Temporary table
[ "", "sql", "sql-server", "t-sql", "temp-tables", "global-temp-tables", "" ]
I have a table that records users answers for a number of questions: **tableA** ``` user_id | question_id | date answered | correct? ------------------------------------------------- 66 345 timestamp 1 34 654 timestamp 0 34 654 timestamp ...
To add last twenty questions answered, you need pick last twenty rows and then count the correct answers, but `GROUP BY` and `LIMIT` don't go so well together and you can't attach the last twenty rows unless you are checking for only one category at a time. MySQL doesn't allow you to join a table when one of the subque...
Hei, Friend look this: > Foo.c SELECT, COUNT (\*) AS pct \* t.factor FROM foo JOIN (SELECT > 100/COUNT (\*) FROM foo AS factor) AS t GROUP BY foo.c; Ooops! So it was enough to make a JOIN to get the number of total users, and apply some math test. Returning to my situation practical-metaphorical, we have: ``` SELECT...
Query on timestamps to select only recent rows for each group
[ "", "mysql", "sql", "" ]
I have a table Hobby, whose snippet is as follows: ``` Name Activity Hours John Hiking .5 Sam Cycling .5 Sam Swimming 1 Sam Hiking .5 John Running 1 Sam Sailing 1 ``` For every person X in (X, Y), I would like to find the sum of hours of activities where X and Y d...
I find this to be a tricky question. My original approach was going to use a `full outer join`. But then I realized that if there is no match on the activity in one name, then I'm not going to have the name either. So, the following query works by getting a list of all pairs of names. This is an ordered list, so a giv...
your from clause reads ``` FROM Hobby a, Hobby b ``` Putting a comma in the from clause means "CROSS JOIN" which means each row in the first table are correlated with every row in the second table. Given your where clause I would think this gives some pretty big numbers. your query needs to be a bit different: ``` ...
SQL sum values from the same table
[ "", "sql", "oracle", "" ]
I need to filter all dates which greater than, say 01 january 2011. ``` select * from table_name where date > '01/01/2011'; ``` the problem is that `date` field store `int` values, here is an example: ``` 1339011098 1336717439 1339010538 ``` How to convert the `date` field on the sql query (from the `int` format to...
You can use [`UNIX_TIMESTAMP()`](http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_unix-timestamp) ``` select * from table_name where date > unix_timestamp('2011-01-01') ``` Or conversely use [`FROM_UNIXTIME()`](http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_...
You're going the wrong direction. Rather than converting potentially millions of records for the compare, try converting your target date, which you only need to do once. Those look like unix timestamps, so the resulting query should look like this: ``` SELECT * FROM `Table_name` WHERE date > unix_timestamp('01/01/20...
convert date from numeric value to date valid format
[ "", "mysql", "sql", "date", "" ]
## Background Info I have a database with two tables: `Phones`, and `Carriers` Phones -> Carriers `Phones` (Primary key: `Phones.ID`; Foreign Key: `Phones.CarrierID`) is linked to `Carriers` (Primary key: `Carriers.ID`; Foreign Key: `Carriers.RegionID`). The data types for both `Phones.CarrierID` and `Carriers.ID`...
You have a Many-to-Many relationship. Typically this is implemented by adding a table in between the two data tables: ``` Phones -> PhoneCarriers -> Carriers ``` `PhoneCarrier` will look something like: ``` PhoneCarrierID PhoneID (FK) CarrierID (FK) ``` You won't have a foreign key directly from `Phone` to `Carrier...
You need to use a PhoneCarriers table: ``` PhoneCarriers ------------- PhoneCarrierID <-- Unimportant PK PhoneID <-- FK to Phones Table CarrierID <-- FK to Carrier Table. ``` This is where your multiple entries exist.
Link one record to multiple records in separate table
[ "", "sql", "sql-server", "database", "" ]
In one of my database tables, I want to know if there is atleast one record corresponding to a condition. The query i wrote is Count(\*) from table where (condition) And in my program, i can check whether the result is a non-zero value. It works fine. How can we optimize this? I dont want to wait till it finds the to...
``` SELECT TOP 1 1 AS found FROM tablename WHERE ... ``` Then check if the query returns a single row or not. In this case engine will immediately return you result as soon as it finds the first row (assuming you don't add `ORDER BY`)
SQL has `exists` which can be used for this. This will return 1 if the query returns a result, and 0 otherwise. ``` Select Case When Exists (<query>) Then 1 Else 0 End as X ```
SQL: How to find if there is at least one record matching a condition
[ "", "sql", "optimization", "count", "" ]
I have a list of tables (i.e. productsA, productsB, productsN, ...) each product in these tables may have a comment (stored in the comments table), if I hed to select top 10 ordered comments wich of these is the best solution to be adopted (in terms of performances and speed)? using UNION: <http://www.sqlfiddle.com/#...
The second query would most probably use an index scan on `comment_date` with nested loops over product tables, i. e. at most 10 logical seeks plus whatever it takes to read 10 records from `comments` This first query would most probably use an index scan and sort over each of the queries, then a `MERGE UNION` of thei...
I'd suggest you need neither `UNION` or `CASE` and can just `JOIN` multiple times to comments: ``` SELECT TOP 10 comment_product , COALESCE(a.product_name,b.product_name,c.product_name) AS product_name , comment_date FROM comments z LEFT JOIN productsA a ON z.product_id = a.id_pro...
which one have I to choose between "union" and "case"?
[ "", "sql", "sql-server", "select", "case", "union", "" ]
My query is ``` SELECT CASE WHEN clnt_ntnlty =0 THEN 'Aboriginal' WHEN clnt_ntnlty =1 THEN 'Torres Strait Islander' WHEN clnt_ntnlty =2 THEN 'Both Aboring & Torres Strait' WHEN clnt_ntnlty =3 THEN 'Neither Aboring OR Torres Strait' ELSE 'Not Provided' END AS Identy, ISNULL(COUNT(clnt_ntnlty), 0) AS Counts FROM dbo.cl...
Please try: ``` SELECT DISTINCT Identy, COUNT(clnt_ntnlty) OVER (PARTITION BY Identy) Counts FROM ( SELECT 0 Val, 'Aboriginal' Identy UNION SELECT 1 Val, 'Torres Strait Islander' Identy UNION SELECT 2 Val, 'Both Aboring & Torres Strait' Identy UNION SELECT 3 Val, 'Neither Abor...
You can have a subquery which has four values you want and do a `LEFT JOIN` on it. ``` SELECT a.Identy, COALESCE(b.Counts, 0) Counts FROM ( SELECT 'Aboriginal' Identy UNION ALL SELECT 'Torres Strait Islander' Identy UNION ALL SELECT 'Both Aboring ...
How to get zeros for no values in sql
[ "", "sql", "sql-server-2005", "" ]
I have two table account and balance ``` /---------------------\ | cid | name | mobile | |---------------------| | 1 | ABC | 12345 | |---------------------| | 2 | XYZ | 98475 | \---------------------/ /----------------------------\ | date | cid | balance | |----------------------------| | 2013-09-19 | ...
You need to use two sub-queries like this: ``` SELECT a.cid, a.name, a.mobile, b.date, b.balance FROM account a JOIN ( SELECT b1.* FROM balance b1 JOIN ( SELECT cid, MAX(Date) As maxDate FROM balance GROUP BY cid ) b2 ON b1.cid = b2.cid AND b1.date = b2.maxDate ) b ON a.cid =...
``` SELECT a.cid, a.name, a.mobile, MAX(b.date), b.balance FROM account AS a INNER JOIN balance AS b WHERE a.cid=b.cid GROUP BY cid; ``` Sorry I din't notice the balance column in 3rd table. ``` SELECT a.cid, a.name, a.mobile, b.date, b.balance FROM account AS a INNER JOIN ( SELECT c.date, c.cid, c.balance F...
MySQL join two table with the maximum value on another field
[ "", "mysql", "sql", "view", "max", "" ]
I have database called schoolDB and 2 database tables, `student` and `education` **Create student table:** ``` USE [schoolDB] GO /****** Object: Table [dbo].[tblStudent] Script Date: 09/22/2013 17:30:11 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO SET ANSI_PADDING ON GO CREATE TABLE [dbo].[tblStu...
A simple answer. 1. I select all rows of interest (i.e. 'Secondary School' or by coursename). 2. I count the number of rows per student. 3. I filter to keep the students that have at least 2 rows. 4. I use an expression in the `ORDER BY` to make sure secondary school shows up first. What your question left unclear is...
This will give you a list of students and a count of college courses (per college), by joining the institution table with itself. ``` SELECT STUDENTNUMBER, SCHOOL_NAME, COLLEGE_NAME, count(*) as COLLEGE_COURSES FROM ( SELECT school.STUDENTNUMBER, school.INSTITUTIONNAME AS SCHOOL_NAME, college...
Displaying results based on record count using SQL
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I wondered if there is any table or view which is storing last updates, scripts run by SQL plus or transaction or any changes run by the system? If you look at the SQL Developer they have SQL history. I need something very similar to that but contain or information with time and date and maybe number of execution etc.
Changed Data Capture (CDC) allows Oracle Data Integrator to track changes in source data caused by other applications. When running integration interfaces, thanks to CDC, Oracle Data Integrator can avoid processing unchanged data in the flow. <http://docs.oracle.com/cd/E21764_01/integrate.1111/e12643/data_capture.htm>...
There are several data dictionary views that contain information about SQL statements, transactions etc: * V$SQL * V$SESSION * V$TRANSACTION ... see [Asktom on V$SQL views](http://asktom.oracle.com/pls/asktom/f?p=100:11:0%3a%3a%3a%3ap11_question_id:385254862843) and [Oracle documentation on V$SQL](http://docs.oracl...
Is there any log file or view stores data about user last transaction with database?
[ "", "sql", "oracle", "oracle11g", "oracle-sqldeveloper", "" ]
I have every column set to `NOT NULL` but for some reason I am still able to add a `NULL` value in each column. Here is my table info (create syntax): ``` CREATE TABLE `addresses` ( `id` int(11) NOT NULL AUTO_INCREMENT, `address` varchar(100) NOT NULL, `city` varchar(100) NOT NULL, `state` varchar(4) N...
You are inserting empty strings, and empty string are not `NULL`, to check for `NULL` error do: ``` INSERT INTO `addresses` (`street`, `city`, `state`, `zip`) VALUES (NULL, NULL, NULL, NULL); ``` and you will see error. The `NOT NULL` checks only for values that are not `NULL`. To prevent empty string either you hav...
try below ``` INSERT INTO `addresses` (`street`, `city`, `state`, `zip`) VALUES (NULL, NULL, NULL, NULL); ``` above will not work ``` INSERT INTO `addresses` (`street`, `city`, `state`, `zip`) VALUES ('', '', '', ''); ``` above insert empty string The empty string specifically means that the value was set to be em...
MySQL column set to NOT NULL but still allowing NULL values
[ "", "mysql", "sql", "" ]
I have two columns, column1 and 2 with 10 records each for example: Column1 (A, A, A, B, B, B, B, C, C, D) and Column2 (1, 1, 2, 3, 3, 2, 1, 4, 4, 1) I need to create third column, column3 with these two columns such that, column3= (A\_1\_1\_2, B\_3\_3\_2\_1, C\_4\_4, D\_1) Please help me how to do this, I am using ...
Here you go. You need to retain the 3rd column and only output on the last observation of each Col1 group: ``` data test; input Col1 $ Col2; datalines; A 1 A 1 A 2 B 3 B 3 B 2 B 1 C 4 C 4 D 1 ;; run; data test_out; set test; by Col1; format Col3 $64.; retain Col3; if first.Col1 then Col3 = strip(Col1); Col3 = ca...
I used the work found in [this previous question](https://stackoverflow.com/questions/194852/concatenate-many-rows-into-a-single-text-string) for most of my answer. ``` CREATE TABLE MyTable (COLUMN1 char(1) NULL, COLUMN2 char(1) NULL); INSERT INTO MyTable VALUES ('A', '1'), ('A', '1'), ('A', '2'), ('B', '3'), ('B', ...
concatinating two column records to get the aggregated third column
[ "", "sql", "sas", "" ]
I have a simple stored procedure that is dynamically obtaining values from a cursor. The issue is that at various points some of the bound values can be NULL. I'd like to be able to use these bound values in another query later, for example: ``` select * from table where column = value; ``` The issue is that the `val...
One straightforward solution is: ``` where ((value is null and column is null) or (value is not null and column = value)) ``` You might like to make sure that indexes on column are actually on (column,0) so that null values are included (and the optimiser knows that they are included).
If you want `NULL` values to compare as equals: ``` select * from table where (column = value or column is null and value is null); ```
Convert "column = null" to "column is null"?
[ "", "sql", "oracle", "syntax", "null", "oracle10g", "" ]
What I need is a date for the next given day (Monday, Tuesday, Wed...) following today's date. The user is allowed to select what day following they want and that is stored as an int in a table. "Call me next Tuesday (3)" ``` Sunday = 1 Monday = 2 Tuesday = 3 ... ``` So my table looks like this. ``` UserID, NextDay...
1) Your solution uses a non-deterministic function: `datepart(dw...)` . Because of this aspect, changing `DATEFIRST` setting will gives different results. For example, you should try: ``` SET DATEFIRST 7; your solution; ``` and then ``` SET DATEFIRST 1; your solution; ``` 2) Following solution is independent of `DA...
A calendar table is an alternative to using a bunch of date functions and date arithmetic. A minimal calendar table for this particular problem might look something like this. ``` 2013-09-20 Fri 2012-09-21 Sat 2012-09-22 Sun 2012-09-23 Mon 2012-09-24 Tue ... ``` So a query to get the next Monday might look like ...
SQL: get next relative day of week. (Next Monday, Tuesday, Wed.....)
[ "", "sql", "date", "" ]
Using a Rails 3 Active Record model (postgres db) I want to take a user search input of something like this: ``` "some string, some other string, final string" ``` From there I want to split strings on the commas and build an SQL query that looks something like this ``` SELECT * FROM items WHERE item_name SIMILAR TO...
I would skip SIMILAR TO and go straight to [POSIX regexes](http://www.postgresql.org/docs/current/interactive/functions-matching.html#FUNCTIONS-POSIX-REGEXP), I'm pretty sure SIMILAR TO will be translated to a regex internally so why bother? Also, `~` will let you use [`ANY`](http://www.postgresql.org/docs/current/inte...
Try this way, ``` string = 'some string, some other string, final string' patterns = search_string.split(", ").map{|str| "%#{str}%" } items = Item.where('item_name like any(array[?])', patterns) ```
Rails: How can I take comma separated values and build an SQL query?
[ "", "sql", "ruby-on-rails", "ruby", "postgresql", "" ]
Currently what I am trying to achieve is to create a graph within LINQPad from a SQL Datasource. I believe it is possible to do, however I am not 100% sure on how exactly to do it. Does anyone have any ideas on a method to do this? (Even if it includes using NuGet packages, I don't mind)
**Edit:** charting is now a built-in feature in LINQPad. See [this answer](https://stackoverflow.com/a/51048641/46223). Yes, you can use any NuGet charting library, or the built-in Windows Forms library in `System.Windows.Forms.DataVisualization.Charting`. Simply call Dump on the chart control after creating it, such ...
Linqpad 5.31 comes with internal Chart extension. ``` var customers = new[] { new { Name = "John", TotalOrders = 100 }, new { Name = "Mary", TotalOrders = 130 }, new { Name = "Sara", TotalOrders = 140 }, new { Name = "Paul", TotalOrders = 125 }, }; customers.Chart (c => c.Name, c => c.TotalOrders).Dum...
Create Graphs in LINQPad
[ "", "sql", "linq", "graph", "linqpad", "graph-visualization", "" ]
I need to combine two result sets and I feel I am so close but just don't see how to wrap this all up: Here's one query with a small result set, (give me inactives) ``` SELECT MAX(set_date) AS most_recent_inactive, key_value, statusid FROM status_history WHERE base_table = 'userinfo' AND statusid = 10 AND set_date ...
This is assuming that your inactive status\_id is always less than your active status\_id. This may not work if there are other possible status\_id values. ``` select max(most_recent_active), max(most_recent_inactive), key_value, min(status_id) from (select null as most_recent_active, max(set_date) as most_recent_inac...
You can use a CASE statement to split out which are inactive and which are active. The default, if the case is not fulfilled is NULL so you'll get what you want. ``` select max(case when statusid = 10 then set_date end) as most_recent_inactive , max(case when statusid = 11 then set_date end) as most_recent_active...
How do I combine multiple queries?
[ "", "sql", "oracle", "" ]
I have a query with a joined subquery. If the subquery returns null, I want it to be ignored and I want to the rest of the query to work normally. Currently I have something like: ``` SELECT a, b, c, d FROM tblOne JOIN tblTwo ON tblOne.a = tblTwo.a --this works fine JOIN (SELECT a FROM tblThree) ON tblThree.a...
Use a `LEFT OUTER JOIN` instead of an `INNER JOIN`. This will return all rows for the rest of the query, even if `tblThree` returns no matching rows. In this case the columns for `tblThree` will all be `NULL`. Using your query (although I have added the required alias for the derived table): ``` SELECT a, b, c, d FRO...
Try changing your third join to a LEFT JOIN. ``` LEFT JOIN (SELECT a, e, f FROM tblThree) ON tblThree.a = tblOne.a ``` Then if a is null you will still get the original rows prior to the attempted join. Another option would be to add ``` WHERE a IS NOT NULL ``` to your subquery to only return rows where a h...
sql conditional subquery - ignore subquery if it returns null?
[ "", "sql", "sql-server", "" ]
I'm new to triggers and I can't seem to find an answer to this question. I need to insert calculated rows in a table and have no access to the application source code. I thought a work around might be to create a trigger on the table to calculate the values based on the inserted values then insert them into the table,...
You need to change the logic of your trigger. Right now, you are assuming that there is only one row inserted or updated, but that's not how it works. `INSERTED` is a pseudo table that contains all rows inserted or updated. So, try this instead: ``` ALTER TRIGGER [dbo].[SelfCalFieldsTrigger] ON [dbo].[dynTable] FOR IN...
Try it like this, it should fix both problems: ``` ALTER TRIGGER [dbo].[SelfCalFieldsTrigger] ON [dbo].[dynTable] FOR INSERT, UPDATE AS BEGIN UPDATE [dbo].dynTable SET INVESTOR_DISC_PREM_PERCENT = Coalesce(INVESTOR_DISC_PREM_DOLLAR, 0)/ Coalesce(INVESTOR_PRIN_BAL_PURCHASED, 0)*100, ...
SQL After update trigger seems to prevent insert from working
[ "", "sql", "sql-server", "triggers", "" ]
I was asked this question in an interview, this the table ``` Roll | Sub | Marks 1 A 20 1 B 21 2 A 15 2 B 19 3 A 21 3 B 22 ``` now i have to find the roll and marks 2nd highest marks obtained by the student so i answered this : ``` declare @trytable table...
Below query gives the roll numbers who obtained 2nd highest marks summing the two subject marks. ``` SELECT TOP 1 Roll, Marks FROM ( SELECT DISTINCT TOP 2 Roll, SUM(Marks) over (Partition by Roll) Marks FROM YourTable ORDER BY marks DESC ) temp ORDER BY Marks ``` OR ``` SELECT DIS...
If I understand you correctly, you just want to get the total score for the second highest student, and student is identified by roll? If so: ``` select roll, sum(Marks) from Student group by roll order by total limit 1,1; ``` Not 100% sure about the 1,1 - what you are saying is, I only want 1 row, and not the first.
How to get the 2nd highest from a table where it need to be added first in sql server in a single query?
[ "", "sql", "sql-server", "" ]
I'm trying to create a query that'll update `table_1` where column `id_owner` has more than `5 rows` with the same `owner id`, it needs to set column "`active`" to `3` on all rows those users have. I've tried several different methods and turned up empty with each. Any ideas?
Use this `UPDATE` query with `JOIN` to achieve this: ``` UPDATE table1 t1 JOIN ( SELECT id_owner FROM table1 GROUP BY id_owner HAVING COUNT(*) > 5 ) t2 ON t1.id_owner = t2.id_owner SET t1.active = 3; ``` ### See [this sample SQLFiddle](http://sqlfiddle.com/#!9/f9a5b7b/1)
You may try this:- ``` update table_1 set active = 3 where owner_id in ( select * from ( select owner_id from table_1 group by owner_id having count(*) > 5 ) a ) ```
Update if count is greater than 5 in MySQL
[ "", "mysql", "sql", "sql-update", "" ]
I have as following Data ``` Id , TagNo , Revision 100 , 20001 , A 101 , 20001 , B 102 , 20001 , C 103 , 20002 , B 104 , 20002 , A 105 , 20003 , B ``` I want if I pass B for revision i have following Records ``` 101 , 20001 , B 103 , 20002 , B 105 , 20003 , B ``` if i pass A for Revision i should have the following...
``` with cte as ( select Id, TagNo, Revision, row_number() over(partition by TagNo order by Revision desc) as rn from Table1 where Revision <= @Revision ) select Id, TagNo, Revision from cte where rn = 1 ``` **`sql fiddle demo`**
Are you just looking for ``` select * from mytable where Revision = 'A' ``` or ``` select * from mytable where Revision = 'B' ``` or ``` select * from mytable where Revision = 'C' ```
TSQL making doesn't work
[ "", "sql", "sql-server", "t-sql", "" ]
I am joining 2 tables like : ``` RIGHT JOIN Sheet.dbo.tbl_M_Tam TD ON TD.Name = EU.Name ``` The problem is that sometimes EU.Name is like 'name1' and TD is 'name1 KO' in this case the join won't work. So I want to make it work by adding the string 'KO' in EU.Name when it is a one word string. Is there is a simp...
If this is just for the one specific string ('KO') then this should work. ``` RIGHT JOIN Sheet.dbo.tbl_M_Tam TD ON TD.Name = CASE WHEN EU.Name LIKE '% %' THEN EU.Name ELSE EU.Name + ' KO' END ```
``` RIGHT JOIN Sheet.dbo.tbl_M_Tam TD ON TD.Name LIKE EU.Name +'%' ``` But be warned that this is not the most efficient way of doing a `JOIN` on many rows in a system with high ussage. If you want to be efficient try to clean up your data in some way so that you can do a straight col1 equals col2 join.
how to count how many words when using a join?
[ "", "sql", "sql-server", "join", "" ]
Given the table `users` below: ``` +----+---------+--------+ | id | name | office | +----+---------+--------+ | 1 | David | 1 | | 2 | Roz | 1 | | 3 | Patrick | 2 | | 4 | Chris | 3 | | 5 | Agnes | 3 | | 6 | Freya | 3 | +----+---------+--------+ ``` I want to select th...
``` SELECT a.office, MAX( CASE WHEN b.ID IS NULL THEN NULL ELSE a.Name END) Name FROM Tablename a LEFT JOIN ( SELECT office, MIN(id) ID FROM Tablename GROUP BY office HAVING COUNT(*) > 1 )...
I came up with another solution that I'm jotting for posterity. ``` -- Office id... SET @office_id = 1; -- Find the latest user SELECT `id` INTO @latest_user_id FROM `users` WHERE `office` = @office_id ORDER BY `id` DESC LIMIT 1; -- Find the first user that isn't the first SELECT `id` INTO @latest_user_id ...
Select first row but only if there's more than one match?
[ "", "mysql", "sql", "" ]
I have read **Database system concepts**, 6th edition, *Silberschatz*. I'm going to implement the university database system shown in chapter 2 on OS X on MySQL. But I have a trouble with creating the table `course`. the table `department` looks like ``` mysql> select * from department -> ; +------------+---------...
The syntax of `FOREIGN KEY` for `CREATE TABLE` is structured as follows: ``` FOREIGN KEY (index_col_name) REFERENCES table_name (index_col_name,...) ``` So your MySQL DDL should be: ``` create table course ( course_id varchar(7), title varchar(50), dept_name varchar(20), cred...
When you get this vague error message, you can find out the more specific error by running ``` SHOW ENGINE INNODB STATUS; ``` The most common reasons are that when creating a foreign key, both the referenced field and the foreign key field need to match: * **Engine** should be the same *e.g. InnoDB* * **Datatype** s...
MySQL : ERROR 1215 (HY000): Cannot add foreign key constraint
[ "", "mysql", "sql", "database", "" ]
Been puzzling over this for a while now. Basically here's my statement. ``` SELECT CandidateID, Town, Candidates.SalaryMin, CandidateExperience, CandidateExperience.divTagExp, PrimarySector, Candidates.SalaryMin, CandidateSalary.divTagSal, CASE WHEN following.RecID =1 THEN 'block' ELSE 'none' END AS divFollow FROM...
``` SELECT *, CASE WHEN candidateId IN ( SELECT followId FROM following ) THEN 'block' ELSE 'none' END AS divFollow FROM Candidates ```
``` select Candidates.*, ISNULL(Following.divFollow, 'none') as divFollow from Candidates left join (select distinct followID from Following) as Following on CandidateID = followID ``` Further inner joins can be made to get data from Following table. Left outer join ensures that all entries in the former table (l...
MySQL - Something wrong with my join
[ "", "mysql", "sql", "" ]
is it possible to add such a thing as last second of the day into date? Let's say that I have dates with different times and I need every date set to time 23:59:59... Is it possible? Thanks
``` update the_table set the_date_column = to_date(to_char(the_date_column, 'yyyy-mm-dd')||' 23:59:59', 'yyyy-mm-dd hh24:mi:ss'); ```
In case the [solution proposed by @a\_horse\_with\_no\_name](https://stackoverflow.com/a/18916694/1667004) proves to be slow, it should be possible to do it this way: +1 day -1 second is the logic I'd follow to get that result, without string concatenation: ``` SELECT trunc(SYSDATE) + 1 - (INTERVAL '1' SECOND) FROM D...
How to add last second into date?
[ "", "sql", "oracle", "" ]
How to use SQL to convert the first table to second table in oracle? For the first table, it has three columns called Time, TotalUsers and Department. For the Department column, it only has two types of values, one is \* another is null. I need to make TotalUsers with \* intoTotalUsersStar, and make TotalUsers with nu...
It's very simple - ``` CREATE TABLE second AS SELECT date , CASE department WHEN NULL THEN totalUsers ELSE NULL END AS TotalUsersNull , CASE department WHEN '*' THEN totalUsers ELSE NULL END AS TotalUsersStar FROM first; ``` For more information [click he...
This is just a query. ``` SELECT Date_, CASE WHEN Department IS NULL THEN TotalUsers END TotalUsersNull, CASE WHEN Department = '*' THEN TotalUsers END TotalUsersStar FROM First; ``` Please note that I'm using field name `Date_` since Oracle does not like much when data types used as names. To c...
how to use sql using sql in oracle
[ "", "sql", "oracle", "" ]
I am trying to add foreign key on my other table but this gave me error `#1072 - Key column 'role_id' doesn't exist in table` I have created a table named `role` then I created like this ``` create table role ( role_id varchar(15) primary key (role_id) ) ``` then when I try to alter table on my `user` table ``...
You have to have the column you reference in `add foreign key (`**role\_id**`)` inside your user table. Otherwise you get that error. You would have to have inside your user table something like: ``` create table user( ... role_id varchar(15) ... ) ``` Or if you don't have it, you have to do: ``` ALTER TABLE ...
You need to add `role_id` inside your new table also then set it to foreign key. ``` alter table user roll_id varchar(15), add foreign key (role_id) references role(role_id) ``` Edit: I don't know the proper syntax since I am new to DBMS but I had a similar error so just declare `role_id` again in the new table and i...
#1072 - Key column 'role_id' doesn't exist in table
[ "", "mysql", "sql", "" ]
How I will properly do this: Customer ``` CusID, CusLname, CusFname, CusMname, CusAddress, CusEmailAdd ``` Order ``` OrderID, Order, CusID ``` SQL ``` Select Count(OrderID), o.CusID, CusLname, CusFname, CusMname, CusAddress, CusEmailAdd From Customer c Inner join Order o On c.CusID = o.CusID Group By o.CusID...
A little bit different version (from that Gordon Linoff suggests): ``` select cnt, c.CusID, CusLname, CusFname, CusMname, CusAddress, CusEmailAdd from Customer c join ( select count(OrderID) cnt, CusID from Order o group by CusID ) o on c.CusID = o.CusID order by c.CusID //...
Just include them in the `group by` clause: ``` Select Count(OrderID), o.CusID, CusLname, CusFname, CusMname, CusAddress, CusEmailAdd From Customer c Inner join Order o On c.CusID = o.CusID Group By o.CusID, CusLname, CusFname, CusMname, CusAddress, CusEmailAdd; ```
Column is invalid in select
[ "", "sql", "t-sql", "sql-server-2008-r2", "" ]
I'm having some trouble translating an MS Access query to SQL: ``` SELECT id, col1, col2, col3 FROM table1 LEFT OUTER JOIN table2 ON table1.id = table2.id LEFT OUTER JOIN table3 ON table1.id = table3.id ``` so far so good, but here's the (CASE) part where I get stuck: ``` CASE WHEN table3.col3 IS NULL THEN table2....
Try this: ``` CASE WHEN table3.col3 IS NULL THEN table2.col3 ELSE table3.col3 END as col4 ``` The `as col4` should go at the end of the CASE the statement. Also note that you're missing the `END` too. Another probably more simple option would be: ``` IIf([table3.col3] Is Null,[table2.col3],[table3.col3]) ``` Just ...
That looks like it might belong in the select statement: ``` SELECT id, col1, col2, col3, (CASE WHEN table3.col3 IS NULL THEN table2.col3 AS col4 ELSE table3.col3 as col4 END) FROM table1 LEFT OUTER JOIN table2 ON table1.id = table2.id LEFT OUTER JOIN table3 ON table1.id = table3.id ```
where to place CASE WHEN column IS NULL in this query
[ "", "sql", "ms-access", "null", "case", "" ]
I've got 2 date columns in my table `(start_date, end_date)`. I've tried `Datediff(day, start_date, end_date)`, but I was prompt with: > **invalid column name** --- **How can I calculate the date difference between these 2 columns?**
select DATEDIFF (day,start\_date,end\_date) from yourtablename;
Should be `Datediff(day, start_date, end_date)`. There is no 's' at the end of the `day` * <http://technet.microsoft.com/en-us/library/ms189794.aspx>
Datediff between 2 columns in same table
[ "", "sql", "sql-server-2008", "t-sql", "datediff", "" ]
I have a large mySQL database and I want to remove every record that is empty, not null in a certain column. What is the best way to do write a SQL query for this? Currently I have tried: ``` DELETE FROM Businesses WHERE WEBADDRESS IS NULL ``` But it did not delete anything. There are 44,000 records and almost 80% ...
``` DELETE FROM myTable WHERE myColumn IS NULL ``` Link to MySQL page for DELETE syntax: <http://dev.mysql.com/doc/refman/5.7/en/delete.html> IF the column is not `NULL` but just blank you would need to do something like: ``` DELETE FROM myTable WHERE myColumn = '' ``` Based on the information you also provided in ...
``` delete from your_table where certain_column is null ```
mySQL Query Remove Null Records in Column
[ "", "mysql", "sql", "" ]
I have the tables Fruits: ``` |ID|FruitName| |1 |Banana | |2 |Orange | |3 |Apple | ``` And I also have the table Sales: ``` |ID|Month|Sold| |1 |Jan |20 | |1 |Feb |10 | |1 |Mar |30 | |2 |Apr |15 | |2 |Jan |25 | |3 |Jul |25 | |3 |Jun |18 | ``` Now I want to Display this ``` 1|Banana|Mar|30| 2|Or...
You need to join the `fruit` table with `sales` once to get the month and then again to `sales` table to get the `maxSold` count using which you can filter out the unneeded records on which the `sold` count is not equal to the `maxSold`. ``` SELECT f.id, f.name, s.month, maxSold FROM fruit f LEFT JOIN sales s ON f.id...
Try this: ``` SELECT f.id ,f.fruitname ,s.month ,s.sold FROM fruits f LEFT JOIN (SELECT a.* FROM Sales a LEFT JOIN Sales b ON a.Id = b.IdAND a.Sold < b.sold WHERE b.Sold IS NULL) AS s ON s.id = f.id ``` The inner left join between sales tables are getting the max values, then outer left join is ...
How to join two tables showing max() of other table
[ "", "mysql", "sql", "" ]
Why is this throwing an error on the equal sign? ``` select IIF((SUBSTRING('A1234', 1, 1) = 'A'), TRUE, FALSE) as IsAustraliaUser ``` Error: > Msg 102, Level 15, State 1, Line 1 > Incorrect syntax near '='.
[`IIF`](http://technet.microsoft.com/en-us/library/hh213574.aspx) is a SQL Server 2012 feature, you'll need to use [`CASE`](http://technet.microsoft.com/en-us/library/ms181765.aspx) ``` SELECT CASE SUBSTRING('A1234', 1, 1) WHEN 'A' THEN 'TRUE' ELSE 'FALSE' END ```
You should replace IIF with CASE, also TRUE and FALSE don't exists in SQL Server, you can use VARCHAR or BIT ``` select CASE WHEN SUBSTRING('A1234', 1, 1) = 'A' THEN 'TRUE' ELSE 'FALSE' END as IsAustraliaUser ```
What's wrong this T-SQL statement?
[ "", "sql", "sql-server", "t-sql", "" ]
I have a problem involving a SUM, LEFT OUTER JOIN and GROUP BY commands, but can't figure out where my error is. I have two tables, one for customer transactions and one for customer claims. A customer can have multiple transactions and multiple claims, but in both tables the rows are unique. Customers can also have n...
So the first step to see what is happening is to remove the SUMs and just select the transaction amount and claim amount. That way you can see what data is being returned. You'll see that the join on A/2007 will have the transaction amount twice, since it's joining each row to the claims table. One solution is to use ...
The query will be counting the transaction amount twice for 2007 due to the fact you have two claims, so the transaction amount will be counted twice. i.e. the returned data being used is: ``` Customer | Transaction Year | Transaction Amount | Claim Amount -------------------------------------------------------------...
Duplication involving SUM, LEFT JOIN and GROUP BY
[ "", "mysql", "sql", "" ]
If I have a column in a table of type `TIMESTAMP` and has as default: CURRENT\_TIMESTAMP does this column get updated to the current timestamp if I update the value of *any* other column in the the same row? It seems that it does not but I am not sure if this is what should happen. I can not understand what this me...
Give the command `SHOW CREATE TABLE whatever` Then look at the [table definition](https://dev.mysql.com/doc/refman/8.0/en/timestamp-initialization.html). It probably has a line like this ``` logtime TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, ``` in it. `DEFAULT CURRENT_TIMESTAMP` mean...
I think you have to define the timestamp column like this ``` CREATE TABLE t1 ( ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ); ``` See [here](http://dev.mysql.com/doc/refman/5.0/en/timestamp-initialization.html)
When is a timestamp (auto) updated?
[ "", "mysql", "sql", "timestamp", "" ]
I'm looking for a SQL function that can get query string in the sense, URL is stored on a variable. Actually, I need to create a trigger that will update the column containing url and encode the particular query string of the url, so to encode that particular query string, first I need to extract the query string valu...
Please try below query which returns querystring value with querystring name as parameter: ``` declare @url nvarchar(max) = 'mypage.php?name=This is test&address=Test Address&phone=+9779854125896' declare @param nvarchar(max)='phone' SELECT (CASE WHEN CHARINDEX('&', v)>0 THEN SUBSTRING(v, 0, CHARINDEX('&', v)) ...
You need to create a CLR function that uses Regex. Read [SQL Server: Regular Expressions](http://msdn.microsoft.com/en-us/magazine/cc163473.aspx) for more information.
Get and remove query string with SQL
[ "", "sql", "sql-server", "database", "t-sql", "get", "" ]
I have tables(columns) `A(a)` and `B(b, a)`. Field `a` is primary in `A`, `b` is primary in `B`. `A` represents a set of classes, `B` represents a set of elements, each of them is part of one class. The task is to retrieve all the classes (`A.a`) is first column and elements of those classes in second column. If some c...
*(Note: this was first posted as a comment.)* If `B.a` can have NULLs and some rows do have NULLs in that column, the second query's second part will return nothing. That is because `x NOT IN (list)` essentially translates to ``` x <> value1 AND x <> value2 AND ... ``` and when at least one of the values is NULL, t...
Union will treat all null values as a single null value and that may not be what you are expecting. There are two ways around this: ``` 1. Use UNION ALL 2. Use non distinct "type Fields"... SELECT Type="Type1", Amount FROM Table UNION SELECT Type="Ty...
SQL left join and manual null addition
[ "", "sql", "" ]
I have a Postgres table with a string column carrying numeric values. I need to convert these strings to numbers for math, but I need both `NULL` values as well as empty strings to be interpreted as `0`. I can [convert empty strings into null values](https://stackoverflow.com/a/14035890/405017): ``` # select nullif('...
The types of values need to be consistent; coalescing the empty string to a 0 means that you cannot then compare it to `null` in the `nullif`. So either of these works: ``` # create table tests (orig varchar); CREATE TABLE # insert into tests (orig) values ('1'), (''), (NULL), ('0'); INSERT 0 4 # select orig, cast(...
You could also use ``` cast( case when coalesce(orig, '') = '' then '0' else orig end as float ) ``` You could also unwrap that a bit since you're being fairly verbose anyway: ``` cast( case when orig is null then '0' when orig = '' then '0' else orig end ...
Cast string to number, interpreting null or empty string as 0
[ "", "sql", "postgresql", "syntax", "" ]
I have a contact number field which stores number as countrycode + ' ' + phonenumber.. Now i want to strip leading zeroes from phone number I tried using ``` UPDATE [dbo].[User] SET PhoneNumber = REPLACE(LTRIM(REPLACE([PhoneNumber], '0', ' ')), ' ', '0') ``` but this replaces the space in between with '0' Any sugge...
Try converting the value to `int` or `numeric` Eg: ``` select '91 004563' as Input, CONVERT(INT, SUBSTRING('91 004563',CHARINDEX(' ','91 004563')+1,100)) as Output ``` This gives the result ``` Input Output --------- ------ 91 004563 4563 ```
Try this: `SUBSTRING(PhoneNumber, PATINDEX('%[^0 ]%', PhoneNumber + ' '), LEN(PhoneNumber))`
strip leading zeroes in sql in string after space
[ "", "sql", "sql-server", "" ]
I'd like to insert the results of this query to the table I created below. ``` IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[Entity]') AND type in (N'U')) DROP TABLE [Entity] Go Create Table Entity ([EntCode] [nvarchar](8) NOT NULL, [Name] [nvarchar](80) NOT NULL, [CompanyRegistration] [...
``` insert into ResourceTaskFact.dbo.Entity (e.EntCode, e.Name, e.Active, e.AccessLevel, ss.SiteURN, ss.CompanyURN, ss.SiteName, ss.SiteDesc, ss.SiteURL) Select e.EntCode, e.Name, e.Active, e.AccessLevel, ss.SiteURN, ss.CompanyURN, ss.Si...
You need to explicitly set `CompanyRegistration` to `NULL` in your `SELECT` statement: ``` insert into ResourceTaskFact.dbo.Entity Select e.EntCode, e.Name, NULL AS CompanyRegistration, -- Put column name in to demonstrate why you're selecting NULL here e.Active , e.AccessLevel, ss.SiteURN, ...
How do Insert into a table when one the column in the empty table is NULL
[ "", "sql", "sql-server", "" ]
I'm having trouble with the performance of my rails application. This might be the effect of a poor database structure. And the page is frequently viewed by users, considering that the record is 5k+. ``` Current System: Model: person has_many payment Controller: @total_payments = 0 person.each do |p| @total_payme...
Assuming `persons` is an Activerecord relation ``` persons.joins(:payments).sum(:value) ``` If `persons` is an array already (less preferred) ``` Payment.where(:person_id => persons.map(&:id)).sum(:value) ``` If total payment is the only attribute need from associated payments in this view. Then the fastest method ...
You could try doing something like Payment.select('value') as a base query so that you are only doing one query and mapping over that instead.
Best way to Query Records
[ "", "mysql", "sql", "ruby-on-rails", "ruby-on-rails-3", "" ]
following is my Query to generate the Pivoted result: ``` SELECT '# of Corrective Actions open and overdue' as [Corrective Actions breakdown], [405], [2865], [3142], [405]+[2865]+[3142] as [Total] FROM (Select il.Locationid , ca.CorrectiveActionsid, il.locOrder, ca.isDeleted caDeleted, i.isDeleted iDeleted, i.Company...
looks like your query doesn't return any row, you can fix it like this (I've not fixed other parts of query, just want to show you a workaround): ``` select A.[Corrective Actions breakdown], coalesce([405], 0) as [405], coalesce([2865], 0) as [2865], coalesce([3142], 0) as [3142], coalesce([405], 0...
I would expect the `count()` to return 0. If it doesn't, you can try using `coalesce()`: ``` coalesce([405], 0) as [405] ```
SQL Pivot table for Blank data
[ "", "sql", "sql-server", "sql-server-2008", "pivot", "" ]
How to know the Column position in a table in MS-SQL. Eg: if a table consists of 3 columns namely column1, column2 and column3. I should write a query so that i can get the position of column3 as **3**
try : ``` SELECT ORDINAL_POSITION FROM information_schema.columns WHERE table_name = 'YourTableName' AND COLUMN_NAME = 'YourColumnName' ```
You will get all these from information\_schema. ``` select ordinal_position from information_schema.columns where schema_name = 'databasename' and table_name = 'tablename' and column_name = 'column name' ```
Position of a column in a table
[ "", "sql", "sql-server", "t-sql", "" ]
I have a table like table name : emailvalue ``` -------------------------------------- | email | value | ----------------------------------- | ab@gmail.com | A | -------------------------------------- | ab@gmail.com | B | -------------------------------------- ...
Use it: ``` DELETE t1 FROM emailvalue t1 LEFT JOIN ( SELECT email, value FROM emailvalue GROUP BY email ) t2 on t2.email = t1.email AND t2.value = t1.value WHERE t2.value is null; ```
``` delete t from your_table t left join ( select email, min(value) as minv from your_table group by email ) x on x.email = t.email and x.minv = t.value where x.minv is null ```
Want to delete multiple row but not first row for same property in mysql?
[ "", "mysql", "sql", "" ]
I have 2 Tables: User and UserFriends User userID, Guid UserFriends ActiveID, Guid - PassiveID, Guid So you can be in my friendlist but I dont need to be in yours. For an online list of all users, at first I get all user and Iterate them with a foreach to do things I have to do here. ``` List<DAL.User> onlineList =...
Are working with a relational database (e.g. Oracle, MySql, MsSql, etc.) ? If so, let the database do what it does best: write a single query the returns the appropriate results from the database. **UPDATE 1** So for example, a MS SQL query might look something like: ``` SELECT u.userId, u.refreshPing FROM userFrie...
Create a query to return all of your friends before entering the `foreach` then just check each online user against that collection
How to avoid a sql query in a forearch
[ "", "asp.net", "sql", "" ]
I'm trying to put some data together for a High Charts Bar chart using ASP.NET. Basically, i have three users who i need to track when they have logged into the system. the variants to be used are: 1) Today 2) This Week 3) Last Week 4) Last Month So, i've created individual tsql scripts for today and and last week, b...
``` Select Distinct UserId , ( Select Count(*) as CountToday from hitsTable h2 Where h2.UserId = h1.UserId And Convert(date,hitDate) = Convert(date,GETDATE()) ) As CountToday , ( Select count(*) as CountLatWeek from hitsTable h2 Where h2.UserId = h1.UserId And hitDate Between DATEADD(dd, -(DAT...
Try this query ``` select id, sum(case when Convert(date,hitDate) = Convert(date,GETDATE()) then 1 else 0 end) as as CountToday, sum(hitDate between (DATEADD(week, DATEDIFF (week,0,GETDATE()),-1)) AND getDate() then 1 else 0 end) as CountLatWeek, ...... -- Add more condition from hitsTable g...
Multiple Selects into one select
[ "", "sql", "select", "" ]
I have inherited a large database project with thousands of views. Many of the views are invalid. They reference columns that no longer exist. Some of the views are very complex and reference many columns. Is there an easy way to track down all the incorrect columns references?
This answer finds the underlying columns that were originally defined in the views by looking at `sys.views`, `sys.columns` and `sys.depends` (to get the underlying column if the column has been aliased). It then compares this with the data held in `INFORMATION_Schema.VIEW_COLUMN_USAGE` which appears to have the curren...
**UPDATED TO RETRIEVE ERROR DETAILS** So this answer gets you what you want but it isn't the greatest code. A cursor is used (yes I know :)) to execute a `SELECT` from each view in a TRY block to find ones that fail. Note I wrap each statement with a `SELECT * INTO #temp FROM view X WHERE 1 = 0` this is to stop the `...
Is there a way to find all invalid columns that are referenced in a view using SQL Server 2012?
[ "", "sql", "sql-server", "view", "" ]
I have this table: ``` idFilmAward Name -------------------------------- 1 Academy Awards 2 Saturn Award .. ... ``` Lets say I also have this table: ``` ############### ###First Way### ############### idAward Name idFilmAward -------------------------------------...
Strictly speaking, [Database Normalization](http://en.wikipedia.org/wiki/Database_normalization) says that you should always use second way. You should avoid repeating the same data in different rows in a "perfect" relational database design. In this way, if you want to change the name of the award from "Best Director...
It is not a problem of how many times it repeats. The database has to be normalized (third normal form at least). So "if it repeats even once" or better "could repeat" in your case use a separate table. (This is not a notion) One of the isolated cases when you do not want a normalized database is when using performanc...
When I need to create new table and connect it using foreign key to other table?
[ "", "mysql", "sql", "" ]
I've been trying make a SQL LIKE statement for a search button to display data to, but it doesn't work . I've tried searching about it and even copy-pasted some of the working codes but still no.. I'm really new to this so please excuse my fail coding. (vb.net 2008 + ms access 2003) here's my code : ``` item = txtsea...
There are some things wrong in your code: First, where do you set the connection string? ``` Dim con = new OleDbConnection(.....connection string here ....) ``` The connection string is essential to open the database, without it you cannot call the Open method on the connection. This site contains a lot of connecti...
I was looking for the same, but here is the correct way: ``` cmd = New OleDbCommand("SELECT * FROM moviedb WHERE Title Like '%" & item & "%' ", con) ``` You have to remove the `=` sign
SELECT * from table like from text box. (vb.net 2008 + ms access 2003)
[ "", "sql", "vb.net", "ms-access-2003", "" ]
I'm having a data column named **test\_duration bigint(12)**. I'm storing time in seconds into the database. Now when I fetch record from the table I want the time converted into HH:MM:SS format. How should I achieve this? Thanks in advance.
You can use **MySQL** function [SEC\_TO\_TIME()](http://www.w3resource.com/mysql/date-and-time-functions/mysql-sec_to_time-function.php). Example: ``` SELECT SEC_TO_TIME(2378); ``` Output is: ``` 00:39:38 ``` So in your case: ``` SELECT SEC_TO_TIME(test_duration) as `Time` FORM YOUR_TABLE; ```
Do you store the time in Unixtime (Unix seconds?). If so, use: ``` FROM_UNIXTIME(unix_timestamp, '%h:%i:%s') ```
How to convert time in seconds to HH:MM:SS format in MySQL?
[ "", "mysql", "sql", "time", "" ]
So I have this table ``` Col1 Col2 Col3 A 34 X B 43 L A 36 L ``` Now if I query ``` select * from Table1 where col1 in ('A','B','C') ``` I am expecting something like ``` Col1 Col2 Col3 A 34 X B 43 L A 36 L C - - ``` ...
You could create a nested table schema object type: ``` create type T_List1 as table of varchar2(100); ``` And then construct your query as follows: ``` select s.column_value as col1 , nvl(to_char(t.col2), '-') as col2 , nvl(col3, '-') as col3 from Table1 t right join table(T_Li...
To do this you can use a driver table that has all the values you want returned in it ie: ``` col1 A B C D E ``` Then `LEFT JOIN` to your table. ``` SELECT * FROM driver d LEFT JOIN Table1 t ON d.col1 = t.col1 WHERE d.col1 in ('A','B','C') ```
Display record even if it doesn't exist
[ "", "sql", "oracle11g", "" ]
I am getting `ORA-00907: missing right parenthesis` Error while creating a table on oracle here is what I did: ``` create table customers( cust_num number(4), company varchar2(20), cust_rep number(3), credit_limit number(15), custraint cust_num_pk primary key(cust_num)); ``` whats wrong ??
There's nothing called `Custraint`. It's `Constraint`. It should be: ``` create table customers( cust_num number(4), company varchar2(20), cust_rep number(3), credit_limit number(15), constraint cust_num_pk primary key(cust_num) ); ```
Check your syntax, see the below statement works fine, ``` create table customers( cust_num number(4), company varchar2(20), cust_rep number(3), credit_limit number(15), constraint cust_num_pk primary key(cust_num)); ```
ORA-00907: missing right parenthesis Error while creating a table on oracle
[ "", "sql", "oracle", "" ]
I have an update trigger that updates some important status fields in a table `tblCurrent`. When I first upload the daily batch of records into `tblCurrent` (circa 10K records), I perform some UPDATEs via three separate stored procedures when these are first uploaded and only then. How can I prevent the update trigge...
You could temporary disable triggers for the table and then enable them back. [MSDN article](http://msdn.microsoft.com/en-us/library/ms189748%28v=sql.105%29.aspx). DISABLE TRIGGER { [ schema\_name . ] trigger\_name [ ,...n ] | ALL } ON { object\_name | DATABASE | ALL SERVER } [ ; ] ENABLE TRIGGER { [ schema\_name . ]...
One way to do this would be to have some data in `tblCurrent` that enables you to detect the situation you describe as "first uploaded". For example, a BIT column "FirstUploaded", or a column that is NULL when first uploaded, or even a BIT column "DontFireTrigger". Then write your trigger to detect this condition, and...
How can you `UPDATE` an SQL Server table without triggering the UPDATE trigger
[ "", "sql", "sql-server", "triggers", "" ]
I am working on modifying the existing SQL Server stored procedure. I added two new columns to the table and modified the stored procedure as well to select these two columns as well. Although the columns are available in the table, I keep getting this error: > Invalid column name 'INCL\_GSTAMOUNT' ![enter image desc...
Whenever this happens to me, I press `Ctrl`+`Shift`+`R` which refreshes `intellisense`, close the query window (save if necessary), then start a new session which usually works quite well.
Could also happen if putting string in double quotes instead of single.
SQL Server: Invalid Column Name
[ "", "sql", "sql-server", "sql-server-2008", "stored-procedures", "" ]
Sometimes it works anyway if I forget the `;`. But sometimes it doesn't. And in JDBC and Android SQLite, it seems that I don't need `;` at all. I am confused. When should I use a semicolon?
semicolon indicates end of a statement, so if there are multiple statements then you should use semicolon else it will work fine. I generally use semicolon as a practice, it can be useful even when you are running queries on sql client e.g. in Sql Developer using semicolon is very helpful if you have multiple statemen...
Usually the semicolon is not part of the actual syntax of a statement (as most database internal APIs execute a single statement at a time). Instead the semicolon is an 'end-of-statement' marker or statement separator that is - usually - defined in CLI or scripting tools for the database. This allows that tool to know ...
Is the semicolon necessary in SQL?
[ "", "sql", "jdbc", "android-sqlite", "" ]
I have used the following query: ``` select tblclass.classname,tblattendance.id from tblclass,tblattendance where tblclass.classcode=tblattendance.classcode and tblattendance.attdate='2013-07-01' ``` Output of this query is as follows: ![enter image description here](https://i.stack.imgur.com/9SjQn.png) Now wh...
Use the [Group By](http://www.w3schools.com/sql/sql_groupby.asp) SQL clause and add the aggregate function [Count](http://www.w3schools.com/sql/sql_func_count.asp) ``` select tblclass.classname, Count(tblattendance.id) as counter from tblclass,tblattendance where tblclass.classcode=tblattendance.classcode and tblatt...
Try this ``` select count(tblattendance.id),tblclass.classname from tblclass,tblattendance where tblclass.classcode=tblattendance.classcode and tblattendance.attdate='2013-07-01' group by tblclass.classname ```
How to get count of distinct rows in MySQL?
[ "", "mysql", "sql", "count", "" ]
I have a table from which I want to select data. One coloumn 'myCol' has datatype tinyint. It has values from 1 to 8. In my select I have a variable @myVar with datatype varchar(), that has values like '1,2' or '3,4'. Now I am trying to do something like this: ``` select * from myTable where myCol in (@myVar) ``` U...
Since you only have values from 1 to 8 you can use a string search method. Something like ``` select * from myTable where CHARINDEX(cast(mycol as varchar), @myVar) > 0 ``` ## [SQLFiddle demo](http://sqlfiddle.com/#!3/a28f8/3)
If you create a function similar to the accepted answer in [Splitting of comma separated values](https://stackoverflow.com/questions/5487961/splitting-of-comma-separated-values), you will then be able to do: ``` select * from myTable t inner join dbo.fnSplitStringAsTable(@myVar, ',') s on t.myCol = s.Value ``` No...
SQL select with 'in' casting from string to tinyint
[ "", "sql", "sql-server", "select", "" ]
I have a table, VehicleModelYear, containing columns id, year, make, and model. The following two queries work as expected: ``` SELECT DISTINCT make, model FROM VehicleModelYear SELECT COUNT(DISTINCT make) FROM VehicleModelYear ``` However, this query doesn't work ``` SELECT COUNT(DISTINCT make, model) FROM Vehicl...
`COUNT()` in `SQL Server` accepts the following syntax ``` COUNT(*) COUNT(colName) COUNT(DISTINCT colName) ``` You can have a subquery which returns unique set of `make` and `model` that you can count with. ``` SELECT COUNT(*) FROM ( SELECT DISTINCT make, model FROM VehicleModelY...
Try combining them into a single field: ``` SELECT COUNT(DISTINCT make + ' ' + model) FROM VehicleModelYear ```
SELECT COUNT(DISTINCT... ) error on multiple columns?
[ "", "sql", "sql-server", "t-sql", "" ]
UPDATE: This is resolved, I was making a syntax error. --- Can I join and filter across two columns in a left join? For example: ``` tbl_people id food side value a pizza fries 10 b pizza shake 2 c burger fries 3 tbl_sides food side pizza fries burger fries ``` The...
I think what you want is this: ``` SELECT id, food, side, value, CASE WHEN side.side = people.side THEN 1 ELSE 0 END AS match_flag FROM tbl_people AS people LEFT JOIN tbl_sides AS sides ON people.food = sides.food ```
With MySQL an expression will return a boolean true/false 1/0, works as a shorthand `CASE` statement when looking for boolean output. This will work to flag the non-matching with 1: ``` SELECT people.id, people.food, people.side, people.value ,sides.food IS NULL AS match_flag FROM tbl_people AS people LEFT JOI...
Sql left join across two columns with filter
[ "", "mysql", "sql", "" ]
I'm looking for a way to get the user friendly MSSQL product name. I've tried: ``` select @@version ``` but it returns to much information (I don't want to parse it now) `Microsoft SQL Server 2008 R2 (RTM) - 10.50.1617.0 (X64) Apr 22 2011 19:23:43 Copyright (c) Microsoft Corporation Developer Edition (64-bit) on Wi...
How about ``` SELECT LEFT(@@version, CHARINDEX(' - ', @@version)) ProductName; ``` *Note: you can obviously adjust it to your needs (like trim RTM if you have to etc.)* Sample output SQL Server 2008: ``` | PRODUCTNAME | |-------------------------------------| | Microsoft SQL Server 2008 R2 (...
Try this (if you need to remove `(RTM)`): ``` select case when charindex('-', @@version,0) < charindex('(', @@version,0) then left(@@version, charindex('-', @@version,0)-1) else left(@@version, charindex('(', @@version,0)-1) end as myserver --Results Microsoft SQL Server 2008 R2 Microsoft SQ...
Get user friendly MSSQL server's product name
[ "", "sql", "sql-server", "" ]
My database is like this - There are multiple Courses in a College. A Course is further divided into multiple streams. A stream has multiple Subjects , which in turn has multiple Topics. Finally there are multiple Notes for a Topic,Stream, Subject and Topic. Course -> Streams -> Subjects -> Topics -> Notes I want to...
``` select MC.CourseName, MCN.NoteCount MS.StreamName, MS.NoteCount MSub.SubjectName, MT.TopicName, MN.NoteName from Master_Course MC JOIN (select MasterCourseID, count(*) as NoteCount from Master_Course MC JOIN Master_Stream MS ON MC.CourseId = MS.CourseId JOIN Master_Subject MSub O...
Not 100% sure if this is what you want. However, you can get some counting adding the following after your JOIN statements: ``` GROUP BY CourseID, StreamID, SubjectID, TopicID WITH ROLLUP ``` or ``` GROUP BY CourseID, StreamID, SubjectID, TopicID WITH CUBE ``` This is of course the guessed names of you unique ident...
Please help in this SQL query
[ "", "sql", "database", "" ]
I have a column containing values like this, example: Farari - Made in 2013 Mercedes - Made in 2012 Jaguar - Made in 1978 I want to return the car with the highest or recent make year: Something like this will give me the year but obviously will truncate the rest of the string: ``` SELECT MAX(RIGHT(CarProfile, 4)...
``` SELECT * FROM Car WHERE RIGHT(CarProfile, 4) = (SELECT MAX(RIGHT(CarProfile, 4)) FROM Car) ``` * [SQLFiddle Demo](http://sqlfiddle.com/#!6/bd2ec/1) You should normalize your table properly. My ssugested schema would be adding a column for a year and have index it so that it would have great...
``` SELECT top 1 * FROM Car order by RIGHT(CarProfile, 4)*1 desc ```
Return string based on values within the string without truncating
[ "", "sql", "sql-server", "t-sql", "" ]
``` $consulta3 = "SELECT * FROM Dept INNER JOIN Userinfo INNER JOIN Checkinout on Dept.DeptName = '$departamento' where Dept.Deptid = Userinfo.Deptid AND Userinfo.Name = Checkinout.name"; ``` the thing im trying to do with this query is: i have a table called Dept where it has...
Access absolutely requires parentheses in the `FROM` clause of any query which includes more that one join. If you have Access available, create and test a new query in the query designer. One of the reasons the designer is useful is that it knows the rules for parentheses which keep the db engine happy. Start with a ...
I think it should be : ``` SELECT * FROM (Dept INNER JOIN Userinfo ON (Dept.Deptid = Userinfo.Deptid)) INNER JOIN Checkinout ON (Userinfo.Name = Checkinout.name) WHERE Dept.DeptName = '$departamento' ```
Access query error ("syntax error in from clause")
[ "", "sql", "ms-access", "ms-access-2007", "" ]
So basically which is better in terms of performance and space: ``` idPerson Name Gender Age 1 John Male 19 2 Anna Female 22 ``` or this way: ``` idPerson Name Age idGender 1 John 19 1 2 Anna 22 2 idGender Gender 1 Male 2 Female ``` I think the seco...
Assuming gender as a binary field, I would go with a third option: name the column `MALE` and the valid values will be either `Y` or `N` (or `1`/`0`) Things to consider: other genders like transgender ;)
> which is better in terms of performance and space Most decisions in Computer Science are usually a trade-off between time and space. In your case, the first solution (storing a string up to 6 characters in the table) will ultimately use more space but results in that string being directly available to queries upon ...
Use new table for gender or add it as field in person table
[ "", "mysql", "sql", "" ]
I have a table, something like ``` STUDENTNAME ISMANUALLYADDED ISEDITED ----------- --------------- -------- APPLE 0 0 ANT 0 1 BELL 0 0 DOLL 1 0 ``` Here, I am trying to sort the data by `studentnam...
The second criteria in the `order by` is only used when different rows have the same value in the previous criteria. Your rows all have different `studentname` values, so the second and third criteria are never used. Try this: ``` select studentname from table1 order by isedited, ismanuallyadded, studentname ```
Try this ``` select studentname from table1 order by studentname ASC, ismanuallyadded ASC, isedited ASC ```
SQL 'order by' first, and then next
[ "", "sql", "sql-server-2008", "" ]
I have a PL/SQL statement like this (it is not a stored procedure or function): ``` DECLARE curstatus VARCHAR(2); person_id varchar(6) := 100; BEGIN SELECT cur_status INTO curstatus FROM Persons WHERE PID=cast(person_id as number(6)); IF curstatus='F' THEN SELECT PID FROM Reports WHERE Report_Type='F' AN...
Surely a pure SQL solution, something like the following, would work? ``` SELECT r.PID FROM Reports r, Persons p WHERE r.Report_Type = 'F' AND r.PID = p.PID AND p.cur_status = 'F' AND p.PID = 100; ```
The reason for the error message is there is no `into` in second select statement. ``` DECLARE curstatus VARCHAR(16); person_id varchar(6) := 100; p_pid VARCHAR(32); BEGIN SELECT cur_status INTO curstatus FROM Persons WHERE PID=cast(person_id as number(6)); IF curstatus='F' THEN SELECT PID into p_pid F...
PLSQL return table set
[ "", "sql", "oracle", "plsql", "" ]
Is there a way in SQL Server 2012 to grant execute all stored procedures in one schema? For additional info, these stored procedures are doing just a select.
Try something like that. It creates a new role and grants execute permission to a schema. ``` CREATE ROLE db_executor GRANT EXECUTE ON SCHEMA::schema_name TO db_executor exec sp_addrolemember 'db_executor', 'Username' ``` Replace `schema_name` with your schema and `'Username'` with your user.
For granting execute permission for all of the stored procedures in one schema , the query by @szymon is enough. The below query will grant execute permission for the procedure to the user selected. Provided the user already exists. > GRANT EXECUTE > ON OBJECT::[schema].[procedurename] TO [user] > AS [schema]; > GO
How to grant execute permissions to the stored procedures in a specific schema?
[ "", "sql", "sql-server", "sql-server-2012", "" ]
I am using PostgreSQL and created the below table: ``` CREATE TABLE "TrainingMatrix" ( payroll text NOT NULL, "TrainingName" text NOT NULL, "Institute" text, "TrainingDate" date NOT NULL, "ExpiryDate" date, "RecorderName" text, "EnteringDate" date, CONSTRAINT "TrainingMatrix_pkey" PRIMARY KEY (payroll,...
``` CREATE TABLE "TrainingMatrix" ( payroll text NOT NULL, "TrainingName" text NOT NULL, "Institute" text, "TrainingDate" date NOT NULL, "ExpiryDate" date, "RecorderName" text, "EnteringDate" date NOT NULL default current_date,--"EnteringDate" date, CONSTRAINT "TrainingMatrix_pkey" PRIMARY KEY (payroll,...
``` CREATE TABLE "TrainingMatrix" ( payroll text NOT NULL, "TrainingName" text NOT NULL, "Institute" text, "TrainingDate" date NOT NULL, "ExpiryDate" date, "RecorderName" text, "EnteringDate" date not null default current_timestamp, CONSTRAINT "TrainingMatrix_pkey" PRIMARY KEY (payroll, "TrainingName", ...
Date field to be filled automatically
[ "", "sql", "database", "postgresql", "" ]
I have data set as a varchar(500), but I only know if it's numeric or character. I need to count the max spaces of the length of a column AND the max spaces after a decimal point. For Example: ``` ColumnA 1234.56789 123.4567890 ``` would return 11 spaces total AND 7 spaces after the decimal. It can be two separate...
``` SELECT LEN(ColumnA ) ,CHARINDEX('.',REVERSE(ColumnA ))-1 FROM Table1 ``` If a value has no decimal, the above will return -1 for the spaces after decimal, so you could use: ``` SELECT LEN(ColumnA) ,CASE WHEN ColumnA LIKE '%.%' THEN CHARINDEX('.',REVERSE(ColumnA))-1 ELSE 0 END FROM T...
``` SELECT len(ColumnA), len(columnA) - charIndex('.',ColumnA) FROM theTable ```
Counting spaces before and after a decimal point
[ "", "sql", "sql-server-2005", "" ]