Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I have an sql-statement, which should select all content of a table ordered by the row number. So i used the row\_number function. But I get everytime the error ``` Exception in thread "main" java.sql.SQLSyntaxErrorException: ORA-00923: FROM keyword not found where expected ``` or this error ``` ORA-00936: missing ...
If you're trying to use the name `row` for that result column, you'll have issues since it's a [Reserved Word](http://docs.oracle.com/cd/B10501_01/appdev.920/a42525/apb.htm) in Oracle. Either pick a different name for the column, or surround it with `""` quotes (a [quoted identifier](http://docs.oracle.com/cd/B10500_01...
I'm not an expert but maybe you have to select the columns for working with their, try syh like this: ``` SELECT name_column1, name_column2, ROW_NUMBER() OVER( ORDER BY name_column1) AS THE_NAME_THAT_YOU_WANT FROM NAME_OF_TABLE WHERE name_column2 ="any_string"; ``` take a look to the origin of error: ORA-00923 origi...
row_number() FROM keyword not found where expected
[ "", "sql", "select", "" ]
I am using the following script to add a column to my table. When I hit `F5` in the query window it gives an error on the 2nd update query that `fkRefTabNo` doesn't exist. ``` ALTER TABLE EPFieldSQLScripts ADD fkRefTabNo int DEFAULT 1 update EPFieldSQLScripts set fkRefTabNo = 1 where fkRefTabNo is null ALTER TABLE ...
Put `GO` between statements. This way the result of each statement will be committed before running the next one (each statement will be a separate transaction). ``` ALTER TABLE EPFieldSQLScripts ADD fkRefTabNo int DEFAULT 1 GO update EPFieldSQLScripts set fkRefTabNo = 1 where fkRefTabNo is null GO ALTER TABLE EP...
As others have answered, adding `GO` is the solution. It's not the *reason* though SQL Server is trying to run your entire script as a single transaction, and then only committing the data to the database when the script completes. So at the point at which ``` update EPFieldSQLScripts set fkRefTabNo = 1 where fkRefTa...
SQL script doesnt work but individual queries work
[ "", "sql", "sql-server", "t-sql", "" ]
There is such code(using PublicActivity gem & Squeel) ``` def index @activities = Activity.limit(20).order { created_at.desc } @one = @activities.where{trackable_type == 'Post'}.includes(trackable: [:author, :project]) @two = @activities.where{trackable_type == 'Project'}.includes trackable: [:owner] ...
In a nutshell, you can't optimize any further without using SQL. This is the way Rails does business. It doesn't allow access to join fields outside the AR model where the query is posed. Therefore to get values in other tables, it does a query on each one. It also doesn't allow `UNION` or fancy `WHERE` conditions tha...
A non-rails-4, non-squeel solution is: ``` def index @activities = Activity.limit(20).order("created_at desc") @one = @activities.where(trackable_type: 'Post') .joins(trackable: [:author, :project]).includes(trackable: [:author, :project]) @two = @activities.where(trackable_type: 'Project').joins(trackable: [:...
Optimize difficult query (possibly with squeel)
[ "", "sql", "ruby-on-rails", "activerecord", "rails-activerecord", "squeel", "" ]
What I'm trying to do with the statement is show all of the movies released in 1999, 2000, and 2001 that run over three hours (the actual column is in seconds). The output table is showing the correct years, but it's showing other things for title\_type other than movie, and it's showing times less than three (as well...
Or do it this way ``` select title_name, title_type, title_release_year, (title_runtime / 3600.0) as title_runtime_hrs from nf_titles where title_type = 'Movie' and title_runtime > 3 and title_release_year in ('1999','2000','2001') order by title_release_year, title_runtime_hrs desc ```
You need to wrap your `OR` statements in parantheses. Otherwise SQL Server will say "ok, here's a year 2000, we've met the criteria. ``` select title_name, title_type, title_release_year, (title_runtime / 3600.0) as title_runtime_hrs from nf_titles where title_type = 'Movie' and title_runtime > 3 and (title_re...
Mix of AND / OR in WHERE clause leads to unexpected results
[ "", "sql", "sql-server", "sql-server-2008", "" ]
So I think I understand the idea of querying the sys.partitions to get a **total** count on a table. `SELECT SUM(rows) FROM sys.partitions WHERE [object_id] = OBJECT_ID('dbo.myTable') AND index_id IN (0,1);` but how would I add conditions to the table I'm counting from? E.g. `MyTable WHERE communityID = 123` A gene...
``` select count(*) from table where communityID=123 ```
There's no other way than querying the table directly: ``` SELECT COUNT(*) FROM dbo.myTable WHERE UserName LIKE '%C%' ```
SQL count on large recordsets with conditions
[ "", "sql", "sql-server", "sql-server-2008", "" ]
i want to select distinct `customer_id` order by either `s.no` or `time` or anyhow ``` s.no customer_id time 1 3 100001 2 2 100002 3 4 100003 4 3 100004 5 2 100005 ``` i am using `...
So your problem statement is "You want the list of customer\_id, sorted in descended order from their largest time value", right? ``` SELECT customer_id, MAX(time) FROM table_name GROUP BY customer_id ORDER BY MAX(time) DESC ```
You have to do a second select like this: ``` SELECT `number` FROM ( SELECT DISTINCT(number) AS number FROM `table_name` ORDER BY `time` DESC ) AS `temp` ORDER BY `number` ASC ```
selecting distinct value order by desc
[ "", "mysql", "sql", "" ]
I have two tables in the database: *Artist* and *Filter*. Is there anyway to query columns of *Artist* based on the subquery results of *Filter* in a **single** SQL statement? Pseudo Code: `SELECT (SELECT ColumnName FROM Filter WHERE ShowColumn=1) FROM Artist` * Artist ``` ------------------------------------------...
This is not possible in SQLite. You have to read the columns from `Filter` first, and then to construct a query with those columns.
If your target is formatted output, ie, you don't need a dataset, you can compose a string in first column. Example for CSV output: ``` SELECT --Header 'id' ||CASE (SELECT ShowColumn FROM Filter WHERE ColumnName='FirstName') WHEN 1 THEN ',FirstName' ELSE '' END ||CASE (SELECT ShowColumn FROM Filter WHERE ...
SELECT columns based on a subquery results with single statement
[ "", "sql", "sqlite", "" ]
I'm using SQL Server 2005 and trying to build a query in a way that I can't seem to get working. I have two tables. One table has a list of ItemTypes and another with a list of mappings between ItemTypes and users. I want to have a query that will return these results: ``` ID | ItemType | Enabled? -----------...
You can't compare `null` values like other values. Use the `is null` operator in the `case`: ``` 'Enable' = CASE WHEN hid.ID IS NULL THEN 'true' ELSE 'false' END ```
A simple and efficient approach is to use `EXISTS` instead of a join: ``` SELECT systype.ID, systype.TypeDescription, [Enable] = CASE WHEN EXISTS( SELECT 1 FROM A7_HiddenNewsFeedTypes ft WHERE ft.SystemItemTypesID = systype.ID AND ft.UserName = @U...
SQL LEFT JOIN with a CASE Statement
[ "", "sql", "sql-server-2005", "" ]
I have to obtain the substring in a string without giving position using SQL in PostgreSQL. I have tried in this way but which is displaying only last number '2' This way i have worked The String is P1.B1.12 ``` SELECT SUBSTRING(REGISTRATIONNO from '.(.)*') AS REGISTRATIONNO FROM SUBSCRIBER; ``` The expected resul...
``` select (regexp_split_to_array(registrationno, '\.'))[3] from subscriber ``` Note that this assumes that the desired value is *always* at the third position. If this is not the case, the expression will return the wrong value. Here is an SQLFiddle example: <http://sqlfiddle.com/#!12/d41d8/1924>
Can you try this? ``` SELECT SUBSTRING(REGISTRATIONNO from '\w*.\w*.(\d+)') AS REGISTRATIONNO FROM SUBSCRIBER; ```
Obtain substring in SQL
[ "", "sql", "regex", "postgresql", "" ]
An application I am working on invokes a SP like this: ``` exec CreateChildRecord @ParentID = 123, @ChildID = 124 ``` The SP needs to copy all fields except the ID from the parent record into the child record. The child record may or may not currently exist. What I need is something like the below: ``` UPDATE [Tabl...
if you can use `merge` statement: ``` merge [Table] as T using ( select @ChildID as ID, data1, data2 from [Table] where ID = @ParentID ) as P on P.ID = T.ID when matched then update set data1 = P.data1, data2 = P.data2 when not matched then insert (ID, data1, data2) values (P.ID...
Depending on the version of SQL Server you are using (2008+) you can make use of [MERGE (Transact-SQL)](http://msdn.microsoft.com/en-us/library/bb510625%28v=sql.100%29.aspx) > Performs insert, update, or delete operations on a target table based > on the results of a join with a source table. For example, you can > sy...
Duplicating a record with different ID
[ "", "sql", "sql-server", "t-sql", "" ]
> **UPDATE:** > Someone marked this question as duplicate of > [How do I split a string so I can access item x](https://stackoverflow.com/questions/2647/how-do-i-split-a-string-so-i-can-access-item-x). > But it's different, my question is about Sybase SQL Anywhere, the other is about MS SQL Server. These are two differ...
Like *Mikael Eriksson* said, there is answer at **[dba.stackexchange.com](https://dba.stackexchange.com/a/51444/29314)** with two very good solutions, first with use of `sa_split_list` system procedure, and second slower with `CAST` statement. For the Sybase SQL Anywhere 9 `sa_split_list` system procedure not exist, s...
This can be done without using dynamic SQL but you will need to create a couple of supporting objects. The fist object is a table valued function that will parse your string and return a table of integers. The second object is a stored procedure that will have a parameter where you can pass the string (id\_list), parse...
Split/explode comma delimited string with Sybase SQL Anywhere
[ "", "sql", "t-sql", "split", "sybase", "sqlanywhere", "" ]
I'm trying to figure out how to use ActiveRecord to execute the following psuedocode: ``` rows_updated = UPDATE my_table SET my_column="abc" WHERE id=123 if rows_updated == 0 then INSERT INTO my_table (id, my_column) VALUES (123, "abc") ``` The reason for this is most of the time the record already exists. I want to ...
There is also different and more elegant solution (from my point of view) for this case One of the options is using a replace command instead of all this code. just run: ``` REPLACE INTO my_table (id, my_column) VALUES (123, "abc") ``` this solution works just fine in most cases, but if you have a very high load on ...
First do a find or initialize so that if the id is not there it will create the object. then check if it is new. If new save it else update it. ``` obj= find_or_initialize_by_id(obj) obj.new_record? ? prod.save! : *update the entry* ```
How to efficiently use first_or_initialize when records usually already exist
[ "", "mysql", "sql", "ruby-on-rails", "activerecord", "" ]
I have 2 tables, project/images related: ``` [project] project_id (int primary key) completed (date) [project_media] project_media_id (int primary key) project_id (int foreign key) image (varchar) ``` What I want to select is: from the last 5 project records based on completed, take the last image added based on p...
``` SELECT PR.*, ( SELECT PM.image FROM project_media PM WHERE PR.project_id = PM.project_id ORDER BY PM.project_media_id DESC LIMIT 1 ) AS image FROM ( SELECT P.project_id, P.completed FROM project P ORDER BY P.completed DESC LIMIT 5 ) AS PR ```
If you wanted to just get the five most recent things in the project table, you'd do this: ``` select * from project order by completed desc limit 5; ``` Joining in the other table, you'd end up with something like this: ``` select * from project p join project_media pm on p.project_id = pm.project_id order by compl...
SQL get the 5 last items inserted based on 2 table join
[ "", "mysql", "sql", "" ]
I am trying to get the avg of an item so I am using a subquery. **Update**: I should have been clearer initially, but i want the avg to be for the last 5 items only First I started with ``` SELECT y.id FROM ( SELECT * FROM ( SELECT * FROM products WHERE it...
I'm not an MySQL expert (in MS SQL it could be done easier), and your question looks a bit unclear for me, but it looks like you're trying to get average of previous 5 items. If you have **Id without gaps**, it's easy: ``` select p.id, ( select avg(t.deposit) from products as t where t...
This is my solution. It is easy to understand how it works, but at the same time it can't be optimized much since I'm using some string functions, and it's far from standard SQL. If you only need to return a few records, it could be still fine. This query will return, for every ID, a comma separated list of previous I...
Unknown column in mysql subquery
[ "", "mysql", "sql", "join", "subquery", "" ]
Sample Table ``` CustomerId | VoucherId | CategoryId | StartDate | EndDate ------------------------------------------------------------- 10 | 1 | 1 | 2013-09-01| 2013-09-30 10 | 1 | 2 | 2013-09-01| 2013-09-30 11 | 2 | 1 | 2013-09-01| 2013-11-30...
**`sql fiddle demo`** This SQL Fiddle addresses your concerns. You need to generate a Calendar table so that you have something to join your dates to. Then you can do a count of distinct MonthYears for each Customer. ``` create table test( CustomerId int, StartDate date, EndDate date ) insert into test value...
actually, in your case (when periods for each category are equal) you can use this query: ``` with cte as ( select distinct CustomerId, StartDate, EndDate from Table1 ) select CustomerId, sum(datediff(mm, StartDate, EndDate) + 1) as diff from cte group by CustomerId ``` **`sql fiddle demo`**
SQL: SUM after GROUP BY
[ "", "sql", "group-by", "sum", "" ]
I have the following piece of statement entered into MySQL5.6 Command Line Client. However, the following error was received. I haven't even been able to add in END// Delimiter; after the select statement. At the same time, i was wondering after the stored procedure has been created successfully, how do i CALL the sto...
``` mysql> delimiter // mysql> CREATE PROCEDURE GetUStocke() -> BEGIN -> SELECT * FROM buystocks ; -> END// ```
give space between `delimiter` and `//`. After your `select` statement write `end;` on next line and `//` at last line (after `end;` in next new line) ``` delimiter // create procedure GetUStocks() Begin Select * From buystocks; end; // ```
Cannot create stored procedure
[ "", "mysql", "sql", "database", "stored-procedures", "" ]
following T-Sql code: ``` DECLARE @usu VARCHAR(10); SET @usu = 'TOM'; PRINT @usu; RAISERROR ('Name of USU is %i ',14,2,@usu); ``` returns following error: > Msg 2786, Level 16, State 1, Line 4 > The data type of substitution > parameter 1 does not match the expected type of the format > specification. Does anyo...
Yeah, change your format to `Name of USU is %s`, the `%i` means the value of `@usu` is a signed integer. All of the format types are clearly [documented on MSDN](http://msdn.microsoft.com/en-us/library/ms178592.aspx).
Try to change that: ``` RAISERROR ('Name of USU is %i ',14,2,@usu); ``` into that ``` RAISERROR ('Name of USU is %s ',14,2,@usu); ``` since @usu is varchar(10) and %i means signed integer
RAISERROR raises substitution parameter error
[ "", "sql", "sql-server", "t-sql", "sql-server-2005", "" ]
How to get current date in sql to **MMMYY** i.e. OCT13 ``` select Convert(varchar(10),getdate(),6) this will generate 11 Oct 13 ``` I need to get OCT13 . Any help appreciated. Front end application cannot do this formating. I am exporting the data from sql to another sql server Thanks
``` SELECT REPLACE(RIGHT(CONVERT(VARCHAR(9), GETDATE(), 6), 6), ' ', '') AS [MMYY] ```
With the FORMAT Function its very easy to convert it to the right format: (for SQL Sever 2012) `SELECT FORMAT(GETDATE(), 'MMMyy')`
Sql Date in Format MMMYY
[ "", "sql", "sql-server-2008", "t-sql", "" ]
I have a table that looks like this: ``` Person (Ssn, Name, Age, Petname) ``` I need to form a question that returns the name of all persons that have the same amount of pets as the person with Ssn = 1 (i.e. if the person with Ssn = 1 has Petname = "Zeus" in the Petname all the persons that also have a pet should be ...
This should do the trick: ``` SELECT Name FROM Person WHERE SSN <> 1 GROUP BY Name HAVING COUNT(PetName) = (SELECT COUNT(PetName) FROM PERSON WHERE SSN='1') ``` Here is also a [SQLFiddle](http://sqlfiddle.com/#!3/64860/16) with the code.
Try this ``` select Name from Person group by Name having sum(case when Pnr = '1' then 1 else 0 end) = sum(case when Pnr <> '1' then 1 else 0 end) ```
Select rows with the same count in a column from a table
[ "", "sql", "select", "join", "" ]
I am trying the following query and it works as I expect it to `SELECT RIGHT('0000' + CAST(MAX(party_id)+1 AS VARCHAR(4)),4) FROM PARTY` The result is: > 0147 But when I execute the following query so that I can store this value in a variable ``` DECLARE @pid varchar; SELECT @pid = RIGHT('0000' + CAST(MAX(party_id...
You should **always** define a **length** when you declare a `varchar` !! This ``` DECLARE @pid varchar; ``` gives you a `varchar` of **exactly ONE character** length!! Use ``` DECLARE @pid varchar(20); ``` and your problem is solved ...
Yo have not declared size of varchar that is why it is truncating. Set size sufficiently large to store result. ``` DECLARE @pid varchar(10); SELECT @pid = RIGHT('0000' + CAST(MAX(party_id)+1 AS VARCHAR(4)),4) FROM PARTY SELECT @pid as party_id ``` [From SQL Server MSDN](http://technet.microsoft.com/en-us/library/ms1...
SQL Server : How to use variables?
[ "", "sql", "sql-server", "stored-procedures", "" ]
I have a series of sql statements that I am reading into my db - specificially, I am seeding a table with cities and coordinates, but am a little confused as how to handle missing ID columns in sql dumps. My migration to create the table: ``` class CreateCitiesExtended < ActiveRecord::Migration def change creat...
If you do require the default id column, you can amend the INSERT sql to specify the columns used: ``` INSERT INTO `cities_extended` (city, state_code, zip, latitude, longtitude, county) VALUES ('Holtsville', 'NY', '00501', '40.8152', '-73.0455', 'Suffolk'); ``` This should give you the normal auto-incremented id col...
So i found a work around, but I'm not convinced its the best way: ``` class CreateCitiesExtended < ActiveRecord::Migration def change create_table :cities_extended, :id => false do |t| ``` Setting :id => false allows me to bypass the requirements. It works for my cause, but I'm not sure its the best way ...
rails import sql, column mismatch on id
[ "", "sql", "ruby-on-rails", "sqlite", "" ]
I am running an SQL query as below, selecting data for each property with a LEFT JOIN selecting data mainly from table1 ('main\_table') for each property and also displaying data in table 2('houses') if table2 also holds data on each property. However I want to only show results 1 per property. I have tried various re...
Maybe like this? ``` SELECT main_table.housenumber, main_table.streetname, max(main_table.rent) houses.houseID, houses.path, houses.rooms FROM main_table LEFT JOIN houses ON main_table.housenumber = houses.housenumber AND main_table.streetname = houses.streetname group by main_table.housenu...
Say a house has more than one entry. If you don't care which of the possible values you get in the other columns then you can use a much maligned MySQL extension to group by: ``` Select m.housenumber, m.streetname, m.rent, h.houseID, h.path, h.rooms From main_table m Left Join ...
SQL query multiple columns DISTINCT on one column
[ "", "mysql", "sql", "join", "" ]
I just have a quick question. Can a table have it's only primary key as a foreign key? To clarify. When I've been creating tables I sometimes have a table with multiple keys where some of them are foreign keys. For example: ``` create table Pet( Name varchar(20), Owner char(1), Color varchar(10), primary key(Name, Ow...
Yes. Because of the following reasons. 1. Making them the primary key will force uniqueness (as opposed to imply it). 2. The primary key will presumably be clustered (depending on the dbms) which will improve performance for some queries. 3. It saves the space of adding a unique constraint which in some DBMS also crea...
Yes, it's perfectly legal to do that. In fact, this is the basis of [IS-A relations](http://www.geomagas.gr/index.php/is-a-relations-in-relational-databases/) ;)
Can a foreign key be the only primary key
[ "", "sql", "" ]
I am stuck here working on a homework and this is what I have got. Instruction is: Display department name, city and number of different jobs in each department. tables employees (has job\_id and department\_id), deptos (has location\_id, department\_id but no job ids), locations (has location\_id and city) I need to ...
locations can have data missing in other tables, so right join or you start from it and use left joins. You also need to group by city. Tried to do minimum changes to OP query. ``` select d.department_name, l.city, count(distinct e.job_id) from employees e join deptos d on (e.department_id=d.department_id) right join ...
You need to use a OUTER JOIN to accomplish this... like the below. You do not necessarily have to use the keyword outer as it is implied, just remember the the difference between using LEFT and RIGHT joins there is a post on that here. Example below [LEFT JOIN vs. LEFT OUTER JOIN in SQL Server](https://stackoverflow.c...
Join 3 tables and Group
[ "", "sql", "oracle", "join", "oracle11g", "oracle-sqldeveloper", "" ]
I'm trying to return a count of return users which happens when there is a duplicate 'user\_id and action\_type'. So if you refer below, I would like my output to be = 2, since user\_id (5) has 2 similar action\_types (234) and user\_id (6) also has 2 similar action\_types (585). How do I structure my query to reflec...
``` SELECT COUNT(DISTINCT User_Id) FROM ( SELECT User_Id FROM t1 GROUP BY User_Id, Action_Type HAVING COUNT(*) > 1 ) t ```
``` SELECT COUNT(User_Id) FROM ( SELECT User_Id FROM t1 GROUP BY User_Id, Action_Type HAVING COUNT(*) > 1 ) t ``` `DISTINCT` not required just count the ids returned
SQL count of return users
[ "", "mysql", "sql", "hive", "hue", "" ]
I am using Liquibase for generating a MySQL and a HSQLDB databases. In several tables I have a column called 'last\_modified' which is the TIMESTAMP of the last update on that particular record. ``` <changeSet author="bob" id="7"> <createTable tableName="myTable"> <column autoIncrement="true" name="id"...
You can't do this with a default value. The MySQL behaviour is non-standard and not supported by other databases. The proper way to do this is with a TRIGGER which is defined as BEFORE UPDATE and sets the timestamp each time the row is updated. Update: From HSQLDB version 2.3.4 this feature is supported. For example: ...
Or you could try this, as you have already have `modifySql` tag added: ``` <column defaultValue="CURRENT_TIMESTAMP" name="timestamp" type="TIMESTAMP"> <constraints nullable="false"/> </column> <modifySql dbms="mysql"> <regExpReplace replace="'CURRENT_TIMESTAMP'" with="CURRENT...
Default Value ON UPDATE Liquibase
[ "", "mysql", "sql", "database", "hsqldb", "liquibase", "" ]
I have a temporary table I insert values into, something like; ``` SELECT ColourID INTO #TEMP FROM [Orders] WHERE [Order] = 12345 ``` Then later on I have a statement which does something like this; ``` SELECT ColourName FROM Colours WHERE [ID] IN(SELECT ColourID FROM #TEMP) DROP TABLE #TEMP ``` This will return; ...
**IF** I understand you correctly, you want to display, say, 'Red' for every order line that contains Red. Then you need `INNER JOIN`: ``` SELECT c.ColourName, t.* FROM #TEMP as t INNER JOIN Colours as c ON t.ColourID = c.ID ```
If I understand you correctly, you need a join to show the non-unique colors for each instance in your temp table: ``` SELECT ColourName FROM Colours, #TEMP WHERE ID = ColourID ```
WHERE - IN Query Shows Only Distinct Values
[ "", "sql", "sql-server", "" ]
Is it possible to set the `ORDER BY` in a sql statement to the values you want? For example, if I want to choose the values for Day in this order: `Thu, Sat, Sun, Mon` ``` SELECT * FROM `NFL_Games` WHERE Week = '1' ORDER BY Day ```
you can use a `case when` clause for personal orderings... ``` order by (case Day when 'Thu' then 1 when 'Sat' then 2 when 'Sun' then 3 when 'Mon' then 4 else 5 end), Day ```
Yes, you can use expressions in `ORDER BY` ``` SELECT * FROM `NFL_Games` WHERE Week = '1' ORDER BY DAYOFWEEK( date_field ) ```
SQL setting ORDER BY
[ "", "mysql", "sql", "" ]
I am using postgresql is it possible for me to change a table when a specific time happens. I would like to modify values when a specific date happens that is specified in the table being modified. For example: a piece of artwork is located in a museum, after it's exhibition ends it is automatically placed back into s...
postgres does not have triggers on system-wide event (such as time). What you can do, however, is have the OS's `cron` or `at` services do it for you by scheduling a statement like this: ``` echo "UPDATE artwork SET location='storage' WHERE name='Mona Lisa' | psql -u some_user -d some_database ```
It is not possible. See cron jobs, as suggested by Muleinik... but then, to expand on your example: > a piece of artwork is located in a museum, after it's exhibition ends it is automatically placed back into storage, changing its location attribute. This occurs on a specified date. What happens if the piece of art i...
SQL change rule based off when a time happens
[ "", "sql", "database", "postgresql", "" ]
I have a general doubt in sql. What is actually "Top 1 1" will do ? What is the meaning of the below query ? ``` select top 1 1 from Worker W where not exists (select 1 from Manager M where M.Id = W.Id) ``` what is the diff between select "TOP 1 1" and "SELECT 1" in sql server query ?
`SELECT TOP 1` Means Selecting the very 1st record in the result set `SELECT 1` Means return 1 as the result set `SELECT TOP 1 1 FROM [SomeTable] WHERE <SomeCondition>` Means if the condition is true and any rows are returned from the select, only return top `1` row and only return integer `1` for the row (no data ju...
In the following, the first "1", which is part of the "TOP 1" means to stop after it gets to a single result. The second "1" is just because the author really does not care what the result is. ``` SELECT TOP 1 1 FROM WORKER ``` is essentially the same as ``` SELECT TOP 1 * FROM WORKER ``` The only question is wheth...
Diff between Top 1 1 and Select 1 in SQL Select Query
[ "", "sql", "sql-server", "" ]
i have multiple tables in a database: **tblOjt** ``` ID studentid courseid companyid addresseeid dateadded datestarted dateended ojthours 1 3 1 1 1 9/25/2013 500 ``` **tblStudent** ``` ID lastname firstn...
If you are writing a query against an Access database backend, you need to use the following join syntax: ``` select t1.c1 , t2.c2 , t3.c3 , t4.c4 from ((t1 inner join t2 on t1.something = t2.something) inner join t3 on t2.something = t3.something) inner join t4 on t3.something = t4.something ``` The table and colu...
``` SELECT tblOjt.id, tblStudent.firstname, tblStudent.middlename, tblStudent.lastname, tblStudent.course, tblCompany.companyname, tblAddressee.addressee FROM (((tblOjt INNER JOIN tblStudent ON tblOjt.studentid = tblStudent.id) INNER JOIN tblCourse ON tblOjt.courseid = tblCourse.id) I...
Access-SQL: Inner Join with multiple tables
[ "", "sql", "ms-access", "vb6", "ado", "" ]
I have a query which is looking like this, ``` select * from tbl1 where field1 in (select field2 from tbl2 where id=1) ``` * where field1 is of type integer * and `select field2 from tbl2 where id=1` will return '1,2,3' which is a string Obviously, we cannot pass string in order to check a field which is of type int...
``` select * from tbl1 where field1 in ( select regexp_split_to_table(field2, ',')::int from tbl2 where id=1 ) ``` Variation suggested by **Igor** ``` select * from tbl1 where field1 = any ( select regexp_split_to_array(field2, ',')::int[] from tbl2 where id=1 ) ```
You need to first split the input using [regex\_split\_to\_array()](http://www.postgresql.org/docs/9.1/static/functions-string.html) method and then use those IDs by casting them to integers Try this - ``` select * from tbl1 where field1 in (select NULLIF(x[1],'')::int,NULLIF(x[2],'')::int,NULLIF(x[3],'')::int from ...
Pass a query inside Where in ()
[ "", "sql", "database", "postgresql", "" ]
In postgres I have two tables like so ``` CREATE TABLE foo ( pkey SERIAL PRIMARY KEY, name TEXT ); CREATE TABLE bar ( pkey SERIAL PRIMARY KEY, foo_fk INTEGER REFERENCES foo(pkey) NOT NULL, other TEXT ); ``` What I want to do is to write a .sql script file that does the following ``` INSERT I...
You can combine the queries into one. Something like: ``` with foo_ins as (INSERT INTO foo(name) VALUES ('A') RETURNING pkey AS foo_id) INSERT INTO bar(foo_fk,other) SELECT foo_id, 'other1' FROM foo_ins UNION ALL SELECT foo_id, 'other2' FROM foo_ins UNION ALL SELECT foo_id, 'other3'...
You can use **[`lastval()`](https://www.postgresql.org/docs/current/functions-sequence.html)** to ... > Return the value most recently returned by `nextval` in the current session. This way you do not need to know the name of the seqence used. ``` INSERT INTO foo(name) VALUES ('A'); INSERT INTO bar(foo_fk,other) VAL...
How to to get the value of an auto increment column in postgres from a .sql script file?
[ "", "sql", "postgresql", "" ]
In SQL there is an expressive way to count how many values differ from `'x'`: ``` SELECT COUNT(NULLIF(col, 'x')) FROM table ``` I find it less elegant to count values equal to `'x'`: * `SELECT COUNT(*) - COUNT(NULLIF(col, 'x')) FROM table` * `SELECT SUM(CASE WHEN col = 'x' THEN 1 ELSE 0 END) FROM table` * *[oracle]*...
``` SELECT COUNT(CASE WHEN col='x' THEN 1 END) AS XCount, COUNT(CASE WHEN col='y' THEN 1 END) AS YCount, COUNT(CASE WHEN col='z' THEN 1 END) AS ZCount FROM table ```
The straightforward way is to do the filtration in the `WHERE` clause: ``` SELECT COUNT(*) FROM table WHERE col = 'x' ``` **EDIT:** If you cannot use the where clause (because you are performing several counts in the same SELECT), then I think the ways you suggested yourself are the most elegant ones. My personal pr...
Aggregate to count values equal to a constant
[ "", "sql", "oracle", "count", "aggregate-functions", "" ]
Consider the following sql command run in MySQL command prompt- ``` select 'aBc'='Abc'; ``` O/P ``` +-------------+ | 'aBc'='Abc' | +-------------+ | 1 | +-------------+ ``` I expected the result to show '0' in place of '1'. How can I differentiate between two strings if they are not in the same case?
You can use a binary collation. For example: ``` select 'aBc'='Abc' collate utf8_bin; ``` Or you can transform one of the strings into a binary type: ``` select binary('aBc')=binary('Abc'); ``` For the differences between these two, see [The \_bin and binary Collations](http://dev.mysql.com/doc/refman/5.6/en/charse...
By default, MySQL is case-insensitive. Either change column collation, or use `COLLATE` keyword, like: ``` SELECT 'abc' COLLATE 'utf8_bin' = 'abc' COLLATE 'utf8_bin' ```
Differentiate between two strings with different case in mysql
[ "", "mysql", "sql", "string", "" ]
I was wondering how to simplify this query, here(<http://sqlfiddle.com/#!3/2789c/4>) you have the complete example ``` SELECT distinct (R.[roleId]) FROM [Role] R LEFT JOIN [userRole] U ON R.[roleId] = U.[roleId] WHERE R.RoleID NOT IN( SELECT [roleId] from [dbo].[userRole] WHERE userId = 2) ``` I want to get ...
As simple as it gets: ``` select roleId from Role except select roleId from userRole where userId = 2 ```
``` SELECT R.roleId FROM [Role] R LEFT JOIN [userRole] U ON R.roleId = U.roleId group by r.roleId having sum(case when U.userId = 2 then 1 else 0 end) = 0 ``` ## [SQLFiddle demo](http://sqlfiddle.com/#!3/2789c/20)
How to simplify a query between Many to Many Relationship
[ "", "sql", "sql-server", "" ]
This has been asked in different ways before, but I can't seem to get something that works for what I need exactly. The goal here is to make a search query that returns Photos based on tags that are selected. Many tags can be applied to the filter simultaneously, which would need to make it so that the query only retu...
Admittedly a bit ugly. But assuming that PhotosTags.Category has the 'Blue', 'White', etc, try something along this line. ``` SELECT p.* From `Photos` AS p WHERE p.`Description` LIKE "%test%" AND AND Exists ( Select 1 FROM `PhotosTagsXref` AS pt Inner JOIN `PhotosTags` AS t ON pt.`TagId` = t.`ID` ...
Supposing the requested set of tags is (`red`,`blue`) you can do: ``` SELECT * FROM `Photos` WHERE `Description` LIKE "%test%" AND `ID` IN ( SELECT pt.`PhotoId` FROM `PhotosTagsXref` AS pt JOIN `PhotosTags` AS t ON pt.`TagId` = t.`ID` WHERE t.Title in ('red','blue') /* your set here */ GROUP BY pt.`PhotoId` ...
MySQL Query show results based on multiple filters/tags
[ "", "mysql", "sql", "" ]
I added Item in `dropdownlist` and when I select the Item I added, it does not show up in `Label1`. Here is my code: **ASPX** ``` <asp:Label ID="Label1" runat="server"></asp:Label> <asp:DropDownList ID="drpOne" runat="server" AutoPostBack="true"> </asp:DropDownList> ``` **VB** ``` Protected Sub Page_Load(s...
i haven't checked the code, but try it this way ``` Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load con.Open() If Not IsPostBack Then Dim Sql = "SELECT College FROM College" cmdAdd = New SqlDataAdapter(Sql, con) Dim ds As New DataSet() cmdAdd.Fi...
``` drpOne.SelectedItem.Text == "enter the value which you want to search" ```
Get the value of selected item in dropdownlist
[ "", "asp.net", ".net", "sql", "vb.net", "drop-down-menu", "" ]
I have a date function returning today date minus date of birth. How can I select or exec result? ``` CREATE FUNCTION [dbo].[udfCalculateAge] ( @DOB AS DATE, @EndDate as DATE = '2999-01-01' -- Defaul is today's date (see below) but any date can be used here ) RETURNS TINYINT AS BEGIN DECLARE @Result as TINYINT -- IF ...
You can just simply return it in select ``` DECLARE @dob AS DATE = '19800101' DECLARE @enddate AS DATE = '20200101' SELECT [dbo].[udfCalculateAge](@dob, @enddate) ``` You can also use it when selecting from a table to return the value of the function together with other columns: ``` SELECT dob, enddate, [dbo].[udfC...
Is this what you're looking for? ``` DECLARE @dob date; SET @dob = '1980-01-01'; SELECT udfCalculateAge(@dob, NULL); ```
SELECT or exec result
[ "", "sql", "sql-server", "" ]
I have ex 17 rows and 2 columns in my tabel. Like this: ``` ColA ColB ---- ---- X 1 X 2 X 3 X a Y 1 Y 2 Y a Z 4 Z 4 Z b Q 1 Q 2 Q 3 Q a W 4 W b W 5 ``` Is there a way to look for a pattern in colB of ...
Your sample data shows distinct rows. In that case, you can use this `GROUP BY` query. ``` SELECT y.ColA FROM YourTable AS y WHERE y.ColB In ('1','2','3','a') GROUP BY y.ColA HAVING Count(*) = 4; ``` If your actual data might include duplicate rows, you can start with `SELECT DISTINCT` in a subquery before applying t...
*(I've assumed that your table is named [PatternData].)* If you use Allen Browne's [`ConcatRelated`](http://allenbrowne.com/func-concat.html) function you can create a query to "string together" all of the [ColB] values for each distinct value of [ColA] like this... ``` SELECT ColA, ConcatRelated("ColB", "Pat...
How to find a specific pattern in some Access data?
[ "", "sql", "ms-access", "pattern-matching", "" ]
I just realized I've had a headache for years. Well, metaphorically speaking. In reality I was looking at my database structure and somehow just realized I never use transactions. Doh. There's a lot of data on the internet about transactions (`begin transaction`, `rollback`, `commit`, etc.), but surprisingly not much ...
> This made a lot of sense when one is doing multiple updates, for > example, in multiple tables in one go. But **basically all of my queries > just update one table at a time**. If a query errors, it cancels, > transaction or no transaction. In your case, it does nothing. A single statement has its own transaction it...
Most important property of the database is to keep your data, reliably. Database reliability is assured by conforming to [ACID](http://en.wikipedia.org/wiki/ACID) principles (Atomicity, Consistency, Isolation, Durability). In the context of databases, a single logical operation on the data is called a transaction. Wit...
SQL - Why transactions?
[ "", "sql", "" ]
I am trying to sort alphabetically case insensitive using `COLLATE NOCASE` but getting error > ORA - 00933 SQL command not properly ended. below is the query I am firing: ``` SELECT LPN.LPN_ID, LPN.TC_ORDER_ID, ORDERS.D_NAME, ORDERS.PURCHASE_ORDER_NUMBER AS ORDER_PURCHASE_ORDER_NUMBER, ...
Oracle does not support `COLLATE NOCASE` option of the `order by` clause. To be able to perform case-insensitive ordering you have two options: 1. Set `NLS_COMP='ANSI'` and `'NLS_SORT=BINARY_CI'`, `CI` suffix means case-insensitive, session or system wide by using `alter session` or `alter system` statement: ``` ...
`COLLATE NOCASE` does not work with Oracle, Try this: ``` SELECT LPN.LPN_ID, LPN.TC_ORDER_ID, ORDERS.D_NAME, ORDERS.PURCHASE_ORDER_NUMBER AS ORDER_PURCHASE_ORDER_NUMBER, ORDERS.D_NAME AS D_NAME_2, LPN.LPN_NBR_X_OF_Y FROM orders orders, lpn lpn where orders.order_id=lpn.order_id ORDER BY l...
how to sort by case insensitive alphabetical order using COLLATE NOCASE
[ "", "sql", "oracle", "sorting", "" ]
``` "id" "parent" "name" "1" "0" "Books" "2" "1" "Crime Fiction" "3" "2" "Death On the Nile" ``` From something like the above, how can I select the `name` of the parent row along with the name of the `child`. Here, the name of the child row will be supplied. I need to get the...
``` select parent.name, child.name from your_table child left join your_table parent on child.parent = parent.id where child.id = 3 ```
``` select t1.name, t2.name as parent_name from tablename t1 join tablename t2 on t1.id=t2.parent where t1.id=3 ```
Select parent row from same table when a child row is supplied
[ "", "mysql", "sql", "" ]
I'm trying to get all users that speak English **and** French based on the schema above. How can I achieve this? I've tried with something like: ``` SELECT * FROM User INNER JOIN UserLanguage on User.idUser = UserLanguage.idUser INNER JOIN Language on UserLanguage.idLanguage = Language.idLanguage WHERE Language.name ...
I'm using a subquery that counts the number of languages (that are either FR or EN) spoken by each user. It then returns all the id of all users that speaks both of these languages. The outer query returns all columns for each of these users: ``` SELECT Users.* FROM Users WHERE idUser IN ( SELECT UserLanguage.idUser...
Change your conditional from ``` WHERE Language.name = "FR" AND Language.name = "EN" ``` to ``` WHERE (Language.name = "FR" OR Language.name = "EN") ``` You should never have an entry in the database that has two values for a single field, but if you use the "OR" operator, you should be selecting the entry if eithe...
SQL query - double condition on relational table
[ "", "mysql", "sql", "database", "" ]
Sorry for the weird title, couldn't write it better... ![enter image description here](https://i.stack.imgur.com/c9l8A.png) Take a look at the image above. In mysql, is it possible/feasible to have column UNIQUE based on user\_id? Let me rephrase this, is it possible to have order column values all unique only for ...
You are asking a couple of independent questions. (1) Yes, you can have unique orders only for a customer. In this case you need to create an unique index using both columns. (2) Is it better/faster to control this in php script that interfaces with mysql? The first question has to do with data integrity not performa...
You can have a compund index that enforces uniqueness on its compound values like this: ``` CREATE UNIQUE INDEX `myUniqueIndex` ON mytable (user_id, order) ``` Any attempt to insert a row with a duplicate compound value will return an error you can check for
Is it possible to have mysql unique index for specific column value?
[ "", "mysql", "sql", "" ]
Howsit everyone I am trying to do something i think is impossible on MYSQL. We have a very large database where we pull production reports from for our products created. At the moment we run multiple queries to get these results and then transfer the data manually to a table before it gets sent off to whomever needs ...
You can put everything into a Select clause, like this: ``` Select (SELECT count(id) from ProductA_T where created between '<date>' and '<date>' and productstatus = "<successful>") as CountA (SELECT count(id) from ProductB_T where created between '<date>' and '<date>' and productstatus = "<successful>") as CountB (SEL...
You could use UNION ALL: ``` SELECT 'ProductA', count(id) from ProductA_T where created between '<date>' and '<date>' and productstatus = "<successful>" UNION ALL SELECT 'ProductB', count(id) from ProductB_T where created between '<date>' and '<date>' and productstatus = "<successful>" UNION ALL SELECT 'ProductC', cou...
Multiple SQL counts into single result set
[ "", "mysql", "sql", "sqlyog", "" ]
I have a SQL query question. I have a table with first name, last name and mobile numbers of clients. ``` Thor Prestby 98726364 Thor Prestby 98726364 Lars Testrud 12938485 Lise Robol 12938485 ``` I want to find rows with the same mobile number, that have different names. As you see above Thor has 2...
You pretty much outlined yourself the actions needed to take in your question. In a nutshell * use a subselect to get all the distinct rows * group on mobilenumber from this unique resultset from the subselect * retain only those mobilenumbers that occur at least twice **SQL Statement** ``` SELECT mobilenumber, COU...
I am assuming that you are using MS SQL Server here but you could use: ``` Declare @t table ( FirstName varchar(100), LastName varchar(100), Mobile bigint ) Insert Into @t values ('Thor','Prestby',98726364), ('Thor','Prestby', 98726364), ('Lars','Testrud',12938485), ('Lise','Robol', 12938485...
How do I find duplicate rows, and at the same time distinct?
[ "", "sql", "" ]
This is what I have so far to find all tables with more than 100 rows: ``` SELECT sc.name +'.'+ ta.name TableName ,SUM(pa.rows) RowCnt FROM sys.tables ta INNER JOIN sys.partitions pa ON pa.OBJECT_ID = ta.OBJECT_ID INNER JOIN sys.schemas sc ON ta.schema_id = sc.schema_id WHERE ta.is_ms_shipped = 0 AND pa.index_i...
Please see my answer to [How do I find a value anywhere in a SQL Server Database?](https://stackoverflow.com/a/12306613/880904) where I provide a script to search all tables in a database. A pseudo-code description of this would be be `select * from * where any like 'foo'` It also allows you to search specific column...
I dont know whether my solutions works for you or not. But instead of that i would use the query below to get all possible tables having guitar in any combination . `Select t.name, c.name from sys.columns c inner join sys.tables t on c.object_id=t.object_id Where c.name like '%guitar%'` Suppose it will give 20-25 tab...
Find specific row data in all database tables? Without Creating A Procedure Or Table
[ "", "sql", "sql-server", "database", "t-sql", "" ]
I Would like to produce a `MySql` Query to be execute on `sales_flat_order` table. and to fetch a list of customers that has made their first order between dates. ``` select customer_id from sales_flat_order where created_at between '1/1/2013' and '30/1/2013' and (this is the first time that the customer has made an ...
First, get every customer's earliest order date: ``` SELECT customer_id, MIN(entity_id) AS entity_id, MIN(increment_id) AS increment_id, MIN(created_at) AS created_at FROM sales_flat_order GROUP BY customer_id ``` Results: ``` +-------------+-----------+--------------+---------------------+ | custome...
You could try something like this: ``` $collection = Mage::getModel('sales/order')->getCollection() ->addFieldToSelect('customer_id') ->addFieldToFilter('created_at', array( 'from' => '1/1/2013', 'to' => '30/1/2013', )) ->distinct(true); ```
Magento MySql Query to fetch List of first time buyers
[ "", "mysql", "sql", "magento", "analytics", "" ]
I have a procedure where I insert values into my table. ``` declare @fName varchar(50),@lName varchar(50),@check tinyint INSERT INTO myTbl(fName,lName) values(@fName,@lName) ``` **EDITED:** Now I want check if it inserted successfully set @check = 0 else @check = 1
You can use `@@ROWCOUNT` server variable immediately after the insert query to check number of affected rows by the insert operation. ``` declare @fName varchar(50) = 'Abcd', @lName varchar(50) = 'Efgh' INSERT INTO myTbl(fName,lName) values(@fName,@lName) PRINT @@ROWCOUNT --> 0- means no rows affected/nothing...
You need to use [@@ROWCOUNT](http://technet.microsoft.com/en-us/library/ms187316.aspx) It returns the number of rows affected by the last statement. If the number of rows is more than 2 billion, use `ROWCOUNT_BIG`. > @@ROWCOUNT is both scope and connection safe. > > In fact, it reads only the last statement row count...
How to check if value is inserted successfully or not?
[ "", "sql", "sql-server", "" ]
I have one table analytics\_metrics. i am trying to get count from visitorsStatistics and pageviewsStatistics for the last x days. the date range can change. ``` id metrics count date 67 visitorsStatistics 15779 2013-10-10 69 pageviewsStatistics 282141 2013-10-10 90 visitorsStatistics 14588 20...
If I got that correctly, you want to combine paired rows within one date, like: ``` SELECT l.count AS visitorsStatistics, r.count AS pageviewsStatistics FROM (SELECT * FROM analytics_metrics WHERE metrics='visitorsStatistics') AS l LEFT JOIN (SELECT * FROM analytics_metrics WHERE metrics='pageviewsStatistics...
Try this out: ``` SELECT sum(if(metrics = 'visitorsStatistics', `count`, 0)) visitorsStatistics, sum(if(metrics = 'pageviewsStatistics', `count`, 0)) pageviewsStatistics FROM analytics_metrics am WHERE <WHATEVER YOU NEED> GROUP BY `date` ``` Fiddle [here](http://sqlfiddle.com/#!2/999bb/1).
Mysql join using date between
[ "", "mysql", "sql", "" ]
I have troubles to SUM time in a varchar/nvarchar data type field. This is the format what I'm trying to SUM: (HH:mm:ss)
I have figured it out: ``` select convert(decimal(18, 2), convert(decimal(18, 2), ppt.hour) + convert(decimal(18, 2), convert(decimal(18, 2), ppt.minute/ 60)) + convert(decimal(18, 2), convert(decimal(18, 2), ppt.second / 3600))) AS Hours, ppt.[column] from (select SUM(convert(decimal(2),left([column], 2))) AS hour, S...
Here you go: ``` create table tblTime (dt datetime) insert tblTime values ('00:25:00'), ('00:20:00') ``` Here is the calculation: ``` Select cast(sum(datediff(second,0,dt))/3600 as varchar(12)) + ':' + right('0' + cast(sum(datediff(second,0,dt))/60%60 as varchar(2)),2) + ':' + right('0' ...
SUM time in varchar/nvarchar data type field
[ "", "sql", "time", "sum", "varchar", "nvarchar", "" ]
I have a database column containing an integer value that represents a systems up time in seconds. I'd really like a query to be able to show me that up time in a easy to read format day(s) hour(s) minute(s) but I'm not quite sure how to do it. A lot of examples I've found appear to use parameters as an example but nev...
I tend to use: ``` CAST(FLOOR(seconds / 86400) AS VARCHAR(10))+'d ' + CONVERT(VARCHAR(5), DATEADD(SECOND, Seconds, '19000101'), 8) ``` The top part just gets your days as an integer, the bottom uses SQL-Server's convert to convert a date into a varchar in the format HH:mm:ss after converting seconds into a date. ...
Depending on the output you want: ``` DECLARE @s INT = 139905; SELECT CONVERT(VARCHAR(12), @s /60/60/24) + ' Day(s), ' + CONVERT(VARCHAR(12), @s /60/60 % 24) + ':' + RIGHT('0' + CONVERT(VARCHAR(2), @s /60 % 60), 2) + ':' + RIGHT('0' + CONVERT(VARCHAR(2), @s % 60), 2); ``` ...
SQL server, Converting Seconds to Minutes, Hours, Days
[ "", "sql", "sql-server-2008", "" ]
I've made a stored procedure and got the error message below, dont know why. I've been looking around for some answers and with some other guys here at the office but they're all unsure of the problem. Hoping someone here has had the same problem and knows the solution to this. ``` Msg 116, Level 16, State 1, Procedur...
If you're going to build a string of SQL and execute it with dynamic SQL, then you need to treat it as a string ``` Set @SQLstring = 'Update #TempTable set Col' + case when len(Convert(Varchar, (4+@counter)))=1 then '0' else '' end ... ``` In your inner select, remove the `@year, @month` from...
Take the year , month , count in the below part in separate select queries. ``` (select @Year, @Month, Convert(Varchar,count(distinct Table.Column1)) from Databse.Table where DATEPART(yy,Time) = @Year and DATEPART(mm,Time) = @Month and Table.Column2 = @Column2 and Column3 in ('X','Z','Y - A')) ```
Subquery is not introduced with exists, stored procedure
[ "", "sql", "sql-server", "sql-server-2008", "" ]
In a perfect world for this type of setup, we would have an integer column that expects only numbers; But what if you have a `varchar` column and you want to add a `WHERE` clause that said something like this: `WHERE <value> is NOT a number` In essence, you are selecting all rows that contain any characters that are...
try this ``` SELECT * FROM myTable WHERE concat('',col1 * 1) != col1 ``` [demo here](http://www.sqlfiddle.com/#!2/2984dc/1)
[`REGEXP`](http://dev.mysql.com/doc/refman/5.1/en/regexp.html#operator_regexp) or [`RLIKE`](http://dev.mysql.com/doc/refman/5.1/en/regexp.html#operator_regexp) are your friends: ``` SELECT * FROM `MyTable` WHERE `Column` RLIKE '^[^0-9]*$'; ``` --- **UPDv1:** You may use different regexes to detect negative integers...
Checking rows that are not numbers in a varchar column for MySQL Query
[ "", "mysql", "sql", "" ]
I'm new to sql server. I googled the use of coalesce and find out it is another words a replace of ISNULL. I came across a piece of code posted in the [forum](http://www.mssqltips.com/sqlservertip/1521/the-many-uses-of-coalesce-in-sql-server/) about the different uses of coalesce. ``` use adventureworks DECLARE @Dep...
add `set @DepartmentName = ''` after `DECLARE @DepartmentName VARCHAR(1000)` and you won't need the coalesce statement. edit: updated after comment clarified things for me
`coalesce` simply returns the value of **the 1st `non-NULL` argument** in its parameter list. e.g. ``` 1.select coalesce(NULL,0,2,1); ``` will return 0 as **0 doesn't mean NULL**. ``` 2.select coalesce(id,emp_id,0) from tab1; ``` In this case attribute-`id` will be returned if it is `NOT NULL` otherwise if `emp_id...
what is the use of coalesce in sql?
[ "", "sql", "sql-server-2008-r2", "" ]
According to multiple sources [Microsoft](http://technet.microsoft.com/en-us/library/ms181627.aspx) , [SQL Server Administration Blog | zarez.net](http://zarez.net/?p=1581) adding comments to SQL and doing so with SSMS is a piece of cake. And for the most part they are probably right. But when I log in and create a vie...
Stop using the clunky and buggy view designer. For a new view, just open a new query window and start typing. This will work fine: ``` USE MyDatabase; GO CREATE VIEW dbo.MyView AS -- this view is cool SELECT whatever FROM dbo.wherever; ``` For an existing view, right-click the view and choose Script As > Alter ...
When you're creating database objects there are two places you can store comments. Before the object definition (and after any GO statements) and inside the object itself. ``` USE GODUCKS; -- This comment will not be preserved GO -- This comment precedes the view definition -- This too CREATE VIEW dbo.CommentedView A...
How do you leave comments in SQL Server 2008 R2 view with SSMS?
[ "", "sql", "sql-server-2008", "comments", "ssms", "" ]
What is the best way to obtain the numeric value from a guid column? I am trying this line but i am getting: ``` ORA-00904: "HASHBYTES": invalid identifier 00904. 00000 - "%s: invalid identifier" ``` Query is below: ``` SELECT HASHBYTES('MD5',CAST(prod AS varchar2(30))) FROM PRODS; ``` Please advice.
Oracle doesn't have the `HASHBYTES` function. You can convert hex to decimal using `TO_NUMBER(hex-string, 'xx')`, but you must have enough `x` characters in your format string to cover the input value. In the case of a GUID, that's 32 `x` characters: ``` SELECT TO_NUMBER(prod, RPAD('x', 32, 'x')) FROM PRODS; ```
This will convert MD5 hash (hex) to decimal number ``` SELECT CONV('MD5', 16, 10) FROM PRODS; ```
Converting guids to numeric value
[ "", "sql", "database", "oracle", "primary-key", "guid", "" ]
Let's say I have a table with the following columns: field 1 | field 2 | field3 | field4 I want to insert multiple rows in this table, but the values of field1, field2 and field3 are identical for each row. Only the value of field4 will change. Obviously I could insert each row separately but the resulting query wou...
You could use a variation on Nicholas Krasnov's answer with a `case` statement to set the string values: ``` insert into my_table(field1, field2, field3, field4) select 'foo', 'bar', 'baz', case level when 1 then 'value one' when 2 then 'value two' when 3 then 'value three' when 4 then 'value four' ...
The simplest way to accomplish this would be taking advantage of the `connect by` clause of `select` statement to generate as many synthetic rows as you need. Suppose `field1` to `field3` are of `varchar2` data type and the `field4` is of number data type, as the sample of data and `insert` statement you have provided...
Insert multiple rows into a table with only one value changing
[ "", "sql", "oracle", "" ]
Difference between inner and outer join. i am using two table and want to fetch data from both table so which type join we should use owning of that we can solve our problem
Inner join - An inner join using either of the equivalent queries gives the intersection of the two tables, i.e. the two rows they have in common. Left outer join - A left outer join will give all rows in A, plus any common rows in B. Full outer join - A full outer join will give you the union of A and B, i.e. All ...
This is the best and simplest way to understand joins: ![enter image description here](https://i.stack.imgur.com/rOeAz.jpg) **Credits go to the writer of this article [HERE](http://www.codeproject.com/Articles/33052/Visual-Representation-of-SQL-Joins)**
What is difference between INNER join and OUTER join
[ "", "sql", "join", "" ]
I have little problem with my MySql query: I have two tables: Table **timeline** ``` id | date | text 1 2013-10-13 Hello ``` Table **reps** ``` id | date | text 1 2013-10-12 Its me again 1 2013-10-11 What? 1 2013-10-10 Lorem ipsum ``` What i am doing is `UNION ALL` timeline and reps.Fir...
Put the UNION in a subquery: ``` SELECT id, date, text FROM (SELECT id, date, text, 1 AS priority FROM timeline UNION ALL SELECT *, 2 AS priority FROM reps) u ORDER BY priority, date DESC ```
your query is right , you just close second query by () like that: and it will order just the second query . without () it will order the two queries. ``` select id,date,text from timeline UNION all (select * from reps order by date desc) ```
Order by date a select query on UNION ALL
[ "", "mysql", "sql", "sql-order-by", "union-all", "" ]
I would like to know if there's a way for a mysql query to return the username of the user that issues the query. Is this possible?
Try the `CURRENT_USER()` function. This returns the username that MySQL used to authenticate your client connection. It is this username that determines your privileges. This may be different from the username that was sent to MySQL by the client (for example, MySQL might use an anonymous account to authenticate your ...
Try to run either ``` SELECT USER(); ``` or ``` SELECT CURRENT_USER(); ``` It can sometimes be different, [USER()](http://dev.mysql.com/doc/refman/5.5/en/information-functions.html#function_user) will return by which login you attempted to authenticate and [CURRENT\_USER()](http://dev.mysql.com/doc/refman/5.5/en/in...
Show the current username in MySQL?
[ "", "sql", "mysql", "database", "mysqlcommand", "mysql-command-line-client", "" ]
I am thinking and exploring options on designing database for my new application. In general, I will have registered users and info about them. They will be able to do some things in app and that data will be in the sam DB as users data (so I can have FK's shared and stuff) But, then I plan to have second database tha...
As soon as you have two databases you have potential complexity. You have not given any particular reason why you need two databases. So keep it simple until you have a reason. An example of what folks do: have a "current" database, small, holding just the data needed right now. That might be where orders are taken an...
Also agree that unless volume of your data is going to be huge (judging by the question, doesn't seem like that is the case here), you can use single database to store your data without performance issues. For "visual" separation of data structure, you can always create tables in two schemas of single database.
Database design - Sharing data between two databases?
[ "", "sql", "sql-server", "database", "database-design", "" ]
Ok, I tried to simplify my question by abstracting away the details but I'm afraid I wasn't clear and didn't meet moderator requirements. So I will post the full query with my problem in more detail and the actual query I am struggling with. If the question is still inadequate, could you please comment with specifics a...
In some cases (but not in all cases) you can do it without a sub-select. You would need to `GROUP BY` a unique field in table A, typically an ID. This ensures that you get only one (or none) row from table B. However, selecting the row you want is the tricky part. You need an aggregating function such as MAX(). If the ...
Use: ``` LEFT JOIN (SELECT * FROM OtherTable WHERE <criteria> ORDER BY CASE status WHEN 'Active' THEN 1 WHEN 'Waiting Approval' THEN 2 WHEN 'Canceled' THEN 3 ... END ...
LEFT JOIN to a single row in order of criteria in MySQL
[ "", "mysql", "sql", "" ]
I have a big strange error in SQL Server 2008R2: I have the following statement: ``` DROP TABLE TEST_ -- here it says that this table doesn't exists GO CREATE TABLE TEST_( [ID_] [int] IDENTITY(1,1) NOT NULL, [ITEM_] NVARCHAR(255) NOT NULL, CONSTRAINT [TEST_] PRIMARY KEY CLUSTERED ( [ID_] ASC )W...
I think you may be confused, it complains that 'TEST\_' already exists, but likely it means the constraint 'test\_' already exists; use a different name for the constraint, and it works OK for me.
**I cannot run your query, because of next error:** *Msg 3701, Level 11, State 5, Line 1* *Cannot drop the table 'TEST*', because it does not exist or you do not have permission.\_ *Msg 102, Level 15, State 1, Line 5* *Incorrect syntax near '('.* *Msg 319, Level 15, State 1, Line 7* *Incorrect syntax near th...
When drop a table it says doesn't exists, when create it says that exists in SQL Server 2008R2
[ "", "sql", "sql-server", "" ]
If I use following query: ``` SELECT DISTINCT comment FROM table; ``` And I have for example following data: (IDs are just there to SHOW the order...) ``` ID | comment ------------- 1 | comment1 2 | comment1 3 | comment2 4 | comment1 ``` What I could get back are following three results: *Result 1:* ``` 1 | ...
Your query doesn't request the ID column, only the comment column: ``` SELECT DISTINCT comment FROM table; ``` In the result, the ID is not included, so the row each value comes from is irrelevant. ``` comment1 comment2 ``` As for how it will sort them, I think it depends on index order. I'll do a test to confirm: ...
You can experiment and see which of the unique rows is returned, and you can experiment and see which order they're returned in, but that will only show you how things turn out with your experimental table, today, under the current database engine version. Bottom line: * If you `SELECT DISTINCT comment` the `id` is im...
Distinct - which items are taken? The first or the last occurance?
[ "", "mysql", "sql", "distinct", "greatest-n-per-group", "" ]
This seems like such an easy query to run yet I cannot get it to work and I'm starting to rethink why I chose to tackle this project. I am trying to find how many records are in a table where an id is identical. For example ``` select productid, productgroup, shelflvl, shelfaisle, Count(Shelfaisle) AS totalaisles fro...
I'm assuming a product cannot belong to many `productgroup`s. Remove `Shelfaisle` from `GROUP BY` as this is what you're trying to count. Also, a `COUNT(DISTINCT Shelfaisle)` would prevent duplicates (if applicable). Lastly, you don't need a `productid=productid` condition which apparently always yields `true`. Cut...
Don't group by the column you are trying to aggregate: ``` select productid, productgroup, Count(Shelfaisle) AS totalaisles from productlocation Where productid=productid AND productgroup = 'canned' Group By productid, productgroup ```
Counting records in a table given corresponding ID
[ "", "sql", "" ]
I have a table of logs that contain a ID and TIMESTAMP. I want to ORDER BY ID and then TIMESTAMP. For example, this is what the result set would look like: ``` 12345 05:40 12345 05:50 12345 06:22 12345 07:55 12345 08:33 ``` Once that's done, I want to INSERT a order value in a third column that...
Try this `update` *not an* `insert`: **[Fiddle demo here](http://sqlfiddle.com/#!3/5aecb/3)**: ``` ;with cte as( select id, yourdate, row_number() over(order by id,yourdate) rn from yourTable ) Update ut Set thirdCol = rn From yourTable ut join cte on ut.Id = cte.id and ut.yourdate = cte.yourdate ``` **NOTE:** i...
Using a derived table and an update. ``` IF OBJECT_ID('tempdb..#TableOne') IS NOT NULL begin drop table #TableOne end CREATE TABLE #TableOne ( SomeColumnA int , LetterOfAlphabet varchar(12) , PositionOrdinal int not null default 0 ) INSERT INTO #TableOne ( SomeColumnA , LetterOfAlphabet ) select 123 ...
How do you order a group of records then insert their order placement too?
[ "", "sql", "sql-server", "t-sql", "" ]
I've got two postgresql tables: ``` table name column names ----------- ------------------------ login_log ip | etc. ip_location ip | location | hostname | etc. ``` I want to get every IP address from `login_log` which doesn't have a row in `ip_location`. I tried this query but it throws a syntax err...
There are basically 4 techniques for this task, all of them standard SQL. ### [`NOT EXISTS`](https://www.postgresql.org/docs/current/functions-subquery.html#FUNCTIONS-SUBQUERY-EXISTS) Often fastest in Postgres. ``` SELECT ip FROM login_log l WHERE NOT EXISTS ( SELECT -- SELECT list mostly irrelevant; can ju...
A.) The command is NOT EXISTS, you're missing the 'S'. B.) Use NOT IN instead ``` SELECT ip FROM login_log WHERE ip NOT IN ( SELECT ip FROM ip_location ) ; ```
Select rows which are not present in other table
[ "", "sql", "postgresql", "null", "left-join", "exists", "" ]
In my SQL table, I'd like to find the state codes that appear more than 300 times and also what the total row counts are for records containing each respective state code. More than a bit rusty on my SQL (plus it's 8am on a Monday...) and this is what i have so far: ``` SELECT StateCode FROM ZipCodeTerritory HAVING CO...
``` SELECT StateCode, Count(*) As StateCodeCount FROM ZipCodeTerritory Group By StateCode HAVING COUNT(*) > 300 ```
Something like this? ``` SELECT StateCode, count(StateCode) FROM ZipCodeTerritory GROUP BY StateCode HAVING COUNT(StateCode) > 300 ```
Return row counts for field that appears more than x times
[ "", "sql", "t-sql", "" ]
I'm running a really simple query, however for some of the results the value in one field is null. How can I set that value to "a string" if its value is null? Something like ``` SELECT RegName, RegEmail, RegPhone, RegOrg, RegCountry, DateReg, (Website IS NULL? 'no website' : Website) AS WebSi...
Use the following: ``` SELECT RegName, RegEmail, RegPhone, RegOrg, RegCountry, DateReg, ISNULL(Website,'no website') AS WebSite FROM RegTakePart WHERE Reject IS NULL ``` or as, @Lieven noted: ``` SELECT RegName, RegEmail, RegPhone, RegOrg, R...
As noted above, the coalesce solution is preferred. As an added benefit, you can use the coalesce against a "derived" value vs. a selected value as in: ``` SELECT {stuff}, COALESCE( (select count(*) from tbl where {stuff} ), 0 ) AS countofstuff FROM tbl WHERE {something} ``` Using "iif" o...
Set default value in query when value is null
[ "", "sql", "sql-server-2005", "" ]
I am struggling with MySQL joins at the moment. I have 3 tables, users, gifts and users\_gifts. ``` - Users - id - username - email - password - Gifts - id - gift - value - users_gifts - uid - gift_id ``` I want to return all gifts but do not include the gifts that the user has ...
I recommend you change your approach. Currently, you are trying to select all gifts sent by a user other than #3. In addition, you are using an inner join, meaning *only* gifts *sent* by a user other than #3 are included. Gifts which have never been sent by anyone are, therefore, excluded. Instead, you should start w...
Your query is looking for users other than #3. Instead, you need to look in users\_gifts, for user=3. But, you want to exclude any gifts that exist in that sub-query: ``` SELECT * FROM gifts WHERE NOT EXISTS (SELECT 1 FROM users_gifts WHERE users_gifts.uid = 3 AND user_gifts.gift_id = gifts.id...
Select all and excluding results. SQL join
[ "", "mysql", "sql", "database", "" ]
Consider a table with a composite primary key: ``` create table T ( C1 int not null, C2 int not null, ... primary key (C1, C2) ) ``` and the problem of retrieving the rows greater than a certain primary key tuple: ``` select * from T where (C1, C2) > (10, 100) ``` The pseudo-syntax above is invalid ...
afair there is no elegant and fast way to do it, if you really have only 2 int columns - try to combine them into one bigint, but for more - you will need to produce such ugly where condition, good news - it will use primary key index and will work pretty fast
What you are looking for is a comparision of glued keys: ``` '11000' > '10100' '10101' > '10100' '10099' < '10100' '09999' < '10100' ``` To achieve this you need a virtual column. In Oracle you would just build a functional index, in SQL Server you would create a computed column first and build the index on that. Yo...
Is it possible to use column tuples in a where condition?
[ "", "sql", "sql-server", "oracle", "" ]
I'm trying to check if a country code exists in a cell `country` before a user can add anything to the database. So, if a country code did not exist, he would not be able to add anything. I'm storing country codes as comma separated values. The column type is VARCHAR. ``` "id" "rtype" "country" "1" "0" "US...
Try this out: ``` SELECT id, rtype FROM test WHERE FIND_IN_SET('US', country) > 0 ``` This is how the `FIND_IN_SET(str,strlist)` function works: > Returns a value in the range of 1 to N if the string str is in the string list strlist consisting of N substrings. A string list is a string composed of substrings separa...
MySQL has a really nice [Set Datatype](http://dev.mysql.com/doc/refman/5.0/en/set.html). It is very efficient and can store till 64 distinct members of 255 values. I don't know if you could change your column type, but it would solve a lot of problems: 1. your column would be indexable 2. you wouldn't store duplicated...
Check if a country code exists in a cell
[ "", "mysql", "sql", "" ]
I cannot seem to figure out how to get an output of a SQL query as a variable in VB. I need something like what's below so that I can use that variable in another SQL query. SQL doesn't allow the use of variables as column headers when running queries, so I thought I could use VB to insert the actual output of one SQL ...
Your code is wrong because you insist in using `ExecuteNonQuery` for `SELECT` statements. `ExecuteNonQuery` doesn't return the rows selected but just a count of the rows affected by an INSERT/DELETE/UPDATE query (I think that for SELECT it returns always zero) What you need is [ExecuteScalar](http://msdn.microsoft.com...
Do a little research into what the different methods of a `command` are. When you call `ExecuteNonQuery`, this return the *number of records effected*. I think you want `ExecuteScalar` as your `cmd` and `cmd2` methods, so you can get a value from the database.
SQL output as variable in VB.net
[ "", "sql", "vb.net", "variables", "" ]
So I have the query: ``` select states, count(numberofcounty) from countytable group by states order by count(distinct numberofcounty) ASC; ``` which return a table of 2 columns: number of state and number of county from least to most. How can I get the avg of how many county are there per state in a single real ...
This might be it? ``` countytable: state|county a aa a ab a ac b ba SELECT AVG(counties) FROM (SELECT state, COUNT(county) as counties FROM countytable GROUP BY state) as temp ``` result: 2
You can use your current query as a subquery to one that gets the average of the number of counties per state ``` Select avg (c) average_counties From (select count(numberofcounty) c from countytable group by states) s ```
sql find average from counting?
[ "", "sql", "count", "average", "" ]
Imagine the following `Loans` table: ``` BorrowerID StartDate DueDate ============================================= 1 2012-09-02 2012-10-01 2 2012-10-05 2012-10-21 3 2012-11-07 2012-11-09 4 2012-12-01 2013-01-01 4 ...
## **Solution for dbo.Loan with PRIMARY KEY** To solve this you need a two step approach as detailed in the following [SQL Fiddle](http://sqlfiddle.com/#!3/4c533/6). I did add a LoanId column to your example data and the query requires that such a unique id exists. If you don't have that, you need to adjust the join c...
I got it working but in a bit convoluted way. It first gets borrowers that don't meet criteria in the inner query and returns the rest. The inner query has 2 parts: Get all overlapping borrowings not starting on the same day. Get all borrowings starting on the same date. ``` select distinct BorrowerID from borrowing...
Select rows with no date range overlap
[ "", "sql", "sql-server", "date-range", "" ]
hello guys I need a little help writing a sql statement that would basically point out the rows that don't have a corresponding negative matching number, based on my\_id,report\_id. Here is the table declaration for better explanation. ``` CREATE TABLE ."TEST" ( "REPORT_ID" VARCHAR2(100 BYTE), "AMOUNT" NUMB...
**New Version** This should return just the rows that you want. If you are not concerned with org or fund then you can just use the query that is aliased x: ``` select distinct t1.report_id, t1.fund, t1.my_id, t1.org, t1.amount from test t1, (select distinct t.report_id, t.my_id, abs(amount) as amount ...
**EDIT:** Here's an updated query based on the feedback and additional sample data provided. This query has the advantage of querying the TEST table just once, and it returns the expected results (3 rows of amount 71, one row of amount 100, and one row of amount 40.17). ``` SELECT report_id, MAX(fund) fund, my_id...
oracle sql how to get the unmatch positive records
[ "", "sql", "oracle", "oracle11g", "" ]
I have a query which returns the following results... ``` SELECT wk, cost FROM my_table WHERE id = '234' order by week WK COST -------- 17 446 18 446 19 446 26 588 27 588 28 588 ``` What I need to try and do is write a query to achieve the following results... ``` WKS COST ------------------ 17, 18...
Try like this, ``` WITH t(wk, COST) AS ( SELECT 17, 446 FROM dual UNION SELECT 18, 446 FROM dual UNION SELECT 19, 446 FROM dual UNION SELECT 26, 588 FROM dual UNION SELECT 27, 588 FROM dual UNION SELECT 28, 588 FROM dual ) SELECT listagg(wk,',') WITHIN GROUP(ORDER BY wk) AS wks, COST FROM t GROUP BY COST...
``` By using LISTAGG function you can achieve what you are trying to do. SELECT deptno ,LISTAGG(sal, '-') WITHIN GROUP (ORDER BY sal) AS employees FROM emp GROUP BY deptno; ----------------------------------------------------- OUTPUT -----------...
Oracle SQL - Group by one column and list results in another
[ "", "sql", "oracle", "oracle-sqldeveloper", "" ]
I'm currently unable to email out time based subscription reports from SSRS on a new SQL Server 2012 installation on Server 2012. I receive the following error in the SSRS LogFiles > schedule!WindowsService\_5!dc4!10/14/2013-10:01:09:: i INFO: Handling Event TimedSubscription with data 1a762da1-75ab-4c46-b989-4711855...
This thread seems to address your issue. <http://www.sqlservercentral.com/Forums/Topic553765-147-1.aspx> Please do a modicum of research before posting error messages. From the Link " After much consternation, I have found a trigger referencing the invalid object. Trigger [Schedule\_UpdateExpiration] on ReportServer...
After a while searching for a solution to fix this issue, I found that this is caused by the jobs definition of SQL Server Agent was not fully migrated to the new service. For every subscription created in SSRS, there is an associated job defined in SQL Server Agent. For services reply heavily on report delivery via su...
SSRS - Renamed TempDB and now Subscription Reports not Emailing
[ "", "sql", "sql-server", "reporting-services", "sql-server-2012", "database-migration", "" ]
I'm using a SQL query to determine the z-score (x - μ / σ) of several columns. In particular, I have a table like the following: ``` my_table id col_a col_b col_c 1 3 6 5 2 5 3 3 3 2 2 9 4 9 8 2 ``` ...and I want to select the z-score of every number of ev...
you can use window functions like this: ``` select t.id, (t.col_a - avg(t.col_a) over()) / stdev(t.col_a) over() as col_d, (t.col_b - avg(t.col_b) over()) / stdev(t.col_b) over() as col_e from my_table as t ``` or cross join with precalculated `avg` and `stdev`: ``` select t.id, (t.col_a - tt.col...
Using a WITH clause: ``` WITH stats AS ( SELECT avg ( col_a ) a_avg, stddev ( col_a ) a_stddev, avg ( col_b ) b_avg, stddev ( col_b ) b_stddev FROM my_table ) SELECT id, ( col_a - a_avg) / a_stddev col_d, ( col_b - b_avg) / b_stddev col_e FROM m...
Calculating the respective z-score of several columns
[ "", "sql", "postgresql", "" ]
I need an sql query that given table of values of the form ``` | id | day1 | day2 | day3 | day4 | day5 | | 1 | 4 | 0 | 5 | 0 | 0 | | 2 | 2 | 0 | 0 | 0 | 0 | ``` gives ``` | id | trailing_zeros | | 1 | 2 | | 2 | 4 | ``` that is, the number of consecutive tr...
Here is possible solution ``` select id, length(@k:=concat(day1,day2,day3,day4,day5&&1)) - length(trim(trailing '0' from @k)) as trailing_zeros from days_table ```
I'd go for something like this. Of course this is assuming you only have 5 days: ``` SELECT id, CASE WHEN day5 = 0 THEN CASE WHEN day4 = 0 THEN CASE WHEN day3 = 0 THEN CASE WHEN day2 = 0 THEN CASE WHEN day1 = 0 THEN 5 ELSE 4 END ELSE 3 END ELSE 2 END ELSE 1 E...
SQL query to find number of trailing zeros across columns
[ "", "mysql", "sql", "" ]
I have a table with following data: ``` Name Score A 2 B 3 A 1 B 3 ``` I want a query which give the following output. ``` Name Score A 2 A 1 Subtotal 3 B 3 B 3 Subtotal 6 ``` Please help me with an SQL code
In general, it would be something like this: ``` select Name, Score from ( select Name, Score, Name as o from Table1 as a union all select 'Subtotal', sum(Score), Name as o from Table1 as a group by Name ) as a order by o, score ``` But, just as @ypercube said, there're different specific impl...
Some DBMS (like MySQL and SQL-Server) have the `WITH ROLLUP` modifier of the `GROUP BY` clause, that can be used for such a query: ``` SELECT pk, name, SUM(score) AS score FROM tableX GROUP BY name, pk -- pk is the PRIMARY KEY of the table WITH ROLLUP ; ``` Test at **[SQL-Fiddle](http://sql...
How to add a subtotal row in sql
[ "", "sql", "" ]
I want to make specific order of JOINs ``` SELECT * FROM (lives_in as t1 NATURAL JOIN preferences p1) l1 JOIN (lives_in t2 NATURAL JOIN preferences p2) l2 ON l1.dormid = l2.dormid ``` Returns an error. Anyone can help? Thanks a lot!
Your aliased queries are missing a `SELECT` clause, so try this: ``` SELECT * FROM ( select * -- added this FROM lives_in as t1 NATURAL JOIN preferences p1) l1 JOIN ( select * -- added this FROM lives_in t2 NATURAL JOIN preferences p2) l2 ON l1.dormid = l2.dormid ```
The order of joins doesn't matter for the results. You probably want something like this: ``` SELECT * FROM lives_in t1 NATURAL JOIN preferences p1 ON p1.some_id = t1.id NATURAL JOIN preferences p2 ON p2.some_id = t1.id ``` Also, most people call it an INNER JOIN, not a NATURAL JOIN, btw.
(A join B) join (C join D)
[ "", "mysql", "sql", "" ]
I have used four tables, namely VehicleMaster, OwnerMaster, CustomerMaster and CustomerVehicle in my project As name explains, first three are master tables and last table (CustomerVehicle) contains CustomerID & VehicleID. The table hierarchy are as follows ``` OwnerMaster (OwnerID, OwnerName) VehicleMaster (Vehic...
There can be owners without vehicles, we don't know... something like this should work as well: ``` SELECT om.OwnerName, count(vm.VehicleID) Total, sum(case when vm.VehicleID is not null and cv.VehicleID is not null then 1 else 0 end) Runnng, sum(case when vm.VehicleID is not null an...
Something like this should work; left join the tables and (distinct) count the respective fields; ``` SELECT om.OwnerName, COUNT(DISTINCT vm.VehicleID) TotalVehicles, COUNT(DISTINCT cv.VehicleID) Running, COUNT(DISTINCT vm.VehicleID)-COUNT(DISTINCT cv.VehicleID) NotRunning FROM OwnerMaster om L...
SQL-Using JOINS to get the values from three tables
[ "", "sql", "linq", "" ]
I have very little knowledge of how access works, but I need some more efficient then what I am doing now. I have these queries: ``` UPDATE [Receipt Audit] SET [Receipt Audit].[Receipt Date] = #04/07/2003# WHERE ((([Receipt Audit].[Receipt Date])=#4/7/303#)); UPDATE [Receipt Audit] SET [Receipt Audit].[Receipt Date]...
Perhaps something like this? ``` UPDATE [Receipt Audit] SET [Receipt Date] = DateSerial(Switch(Year([Receipt Date])=303,2003,Year([Receipt Date])=404,2004,True,Year([Receipt Date])),Month([Receipt Date]),Day([Receipt Date])) WHERE Year([Receipt Date]) IN (303,404) ```
Unfortunately Microsoft Access can't run multiple queries simultaneously. You have two approaches I can think of. * [Write a Macro] or VBA Procedure[1](http://office.microsoft.com/en-us/access-help/create-a-macro-HA010030811.aspx): > You can create a macro to perform a specific series of actions, and > you can create...
Doing Multiple Updates in Access at the same time
[ "", "sql", "ms-access", "updates", "" ]
I have an SQL database with 3 tables: 1. `Customer record` table, holding master data (each row is unique) 2. `Customer notes`, each note data/time stamped (there could be many notes per customer, or none at all) 3. `Product` table, showing which customer has bought which product **Table: tbl\_Customer\_Records** ...
There're a few tricks to do this kind of query (row\_number or join with grouped data), but I think most cleanest one in your case is to use outer apply: ``` select cr.[CustomerID], cr.[Company Name], cr.[Company Segment], cr.[Promo Code], cn.[Note], cp.[Product Category] from tbl_Customer_Record...
You can add your filter condition in `ON` predicate to preserve rows from left table and fetch only required matching rows from right table, from first LEFT OUTER JOIN operator. Following query should work: ``` SELECT CR.[CustomerID], CR.[Company_Name], CR.[Company_Segment], CR.[Promo_Code], CN.[Note], CP....
SQL - query to report MAX DATE results or NULL results
[ "", "sql", "sql-server", "max", "" ]
I want to fetch **category name** too. I have following table **Product Table** ``` mysql> describe prod; +----------+-----------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +----------+-----------------+------+-----+---------+----------------+...
query: ``` select pid, pro_name, cat_pro.cat_id, cat.cat_name from prod inner join cat_pro on (cat_pro.pro_id = prod.pid) inner join cat on (cat.cid = cat_pro.cat_id) where pid='2'; ``` works without errors for the db structure you provided
Hope this will helpful to you. In below query we are using sub-query to get category name based on category\_id. ``` select prod.pid, prod.pro_name, cat_pro.cat_id, ( select cat_name from Category c where c.cid = cat_pro.cat_id ) as category_name from prod left join...
Fetching column data from 3 table with Relation table in-between as mediator in mysql
[ "", "mysql", "sql", "" ]
I've got this recursive function. For a table of hierarchical values, I receive a id and want to return the parent of that id for a certain level (unity\_id) ``` CREATE FUNCTION getObs ( @obs int ) RETURNS table -- <-- returns table so it's a table function as return -- <- here's actual return ( WITH ret2 AS(...
You can use the code below to declare a variable, assign a value to it and return it. ``` CREATE FUNCTION getObs ( @obs int ) RETURNS int as begin declare @return int ;WITH ret2 AS( SELECT * FROM OBS WHERE OBS_Id = @obs UNION ALL SELECT t...
Change the function to explicitly return the int, rather than casting it from a table. ``` as begin declare @ret int ;WITH ret2 AS( SELECT * FROM OBS WHERE OBS_Id = @obs UNION ALL SELECT t.* FROM OBS as t INNER JOIN ret2 r ON t.OBS_Id = r.UnitI...
Returning a scalable value from a recursive function
[ "", "sql", "sql-server", "" ]
I have a table `mytable(**id**,colA,colB)` with 5 million records. colA, colB has no other constraints. I have to copy the values in colB to colA and make colB null. Here is the procedure I created below. Some times it runs in 5 minutes and some times it takes 45 minutes. What is wrong with this script? I'm sure that n...
Why aren't you writing a simple SQL statement ``` UPDATE mytable SET colB = null, colA = colB WHERE colA IS NULL; ``` A pure SQL solution is going to be faster than a PL/SQL solution. If you don't try to understand why your runtimes vary, however, it will be exceptionally difficult to do much to improve p...
Dump the cursors and procedural logic, and rewrite it as SQL.
PL/SQL script running very slow
[ "", "sql", "performance", "oracle", "plsql", "" ]
I want to be able to select persons that are *ONLY* Asian *AND* White. For example in my table below, the only person I would like to retrieve records for is PersonId 1 and 2 (Desired Result). Table: ![enter image description here](https://i.stack.imgur.com/EuuvN.png) Desired Result: ![enter image description here]...
There are a few ways that you can get the result. Using a HAVING clause with an aggregate function: ``` select personid, race from yourtable where personid in (select personid from yourtable group by personid having sum(case when race = 'white' then 1 else 0 end) > 0 and sum(case wh...
This should do ``` select * from table where personID in ( select personID from table group by personID having count(distinct race) = 2 and min(race) = 'Asian' and max(race) = 'White') ```
Selecting records matching ONLY/AND criteria on one column
[ "", "sql", "sql-server", "" ]
Example 1 ``` +--------------------------+ | IDENT | CURRENT | SOURCE | +--------------------------+ | 12345 | 12345 | A | | 23456 | 12345 | B | | 34567 | 12345 | C | +--------------------------+ ``` Example 2 ``` +--------------------------+ | IDENT | CURRENT | SOURCE | +-----------------------...
1. If `SOURCE` values are guaranteed to be unique per `CURRENT`: ``` SELECT CURRENT FROM atable GROUP BY CURRENT HAVING COUNT(SOURCE) = 2 AND COUNT(CASE WHEN SOURCE IN ('A', 'B') THEN SOURCE END) = 2 ; ``` 2. If `SOURCE` values aren't unique per `CURRENT` but `CURRENT`s with duplicate entrie...
We're clearly missing more information. Let's take example data (thanks gloomy for the initial fiddle). ``` | ID | CURRENT | SOURCE | |----|---------|--------| | 1 | 111 | A | | 2 | 111 | B | | 3 | 111 | C | | 4 | 222 | A | | 5 | 222 | B | | 6 | 333 | A | | ...
Select query where record count = 2 and column contains either two values
[ "", "sql", "count", "having", "" ]
I want to make a combined search on the first, middle and lastname. The query is: ``` SELECT picture,person_id, firstname+ ' ' +middlename+ ' ' +lastname AS fullName FROM PERSON WHERE (firstname+ ' ' +middlename+ ' ' +lastname LIKE"%#queryString#%") ``` Now this is working for: Peter den Test (first/ middle/ ...
try like this : ``` SELECT picture,person_id, firstname+ ' ' +middlename+ ' ' +lastname AS fullName FROM PERSON WHERE (firstname+ ' ' + LTRIM(middlename + ' ') + lastname LIKE"%#queryString#%") ```
I think this would work: ``` WHERE (firstname+ ' ' +LTRIM(middlename+ ' ' +lastname) LIKE"%#queryString#%") ```
Firstname, middlename and lastname MS SQL
[ "", "sql", "sql-server-2008", "" ]
I have a table `orders`, consisting of 3 columns: * `order_id int primary key`, * `cust_id integer`, * `order_date integer` with data: ``` order_id | cust_id | order_date 1 | 10 | 1325376000 2 | 10 | 1325548800 3 | 10 | 1325894400 4 | 11 | 132546240...
Try this ``` select order_number , cust_number , order_date from orders o1 where order_number = ( select order_number from orders o2 where o2.cust_number = o1.cust_number and order_date = ( select max(order_date) from orders o3 where o3.cust_number = ...
If you just want the latest record for each customer, I think this will work: ``` SELECT order_number, cust_number, max(order_date) as max_date FROM orders GROUP BY cust_number ```
Complex SQL query in Android SQLite
[ "", "android", "sql", "sqlite", "" ]
I want to know what the (+) in the below query signify, ``` select .. from ..., Fat fat where prop = fat.prop (+) ``` Thanks
It is the obsolete outer join symbol. In Oracle, **(+)** denotes the "optional" table in the JOIN. You may check out this for **[Left and Right Outer Joins](http://www.java2s.com/Tutorial/Oracle/0140__Table-Joins/LeftandRightOuterJoins.htm)**. **On a side note:-**(Although its obsolete) The placement of the (+) det...
For Oracle specifically, indicates a Left Outer Join. Older notation.
what is (+) syntax in SQL query
[ "", "sql", "oracle", "" ]
I have 3 input parameters,based on values of each input parameter i have to prepare the SQL in procedure dynamically. I am doing below way but it is failing, if the parameter value is null,then i have to exclude that from the where clause. **IN Parameters:** > empid in varchar2 || empname IN varchar2 || empsal IN var...
Here you are another alternative: ``` V_SQL_WHERE := null; V_SQL :='SELECT EMP_NAME INTO V_empname FROM employee'; BEGIN IF(EMPID IS NOT NULL) THEN V_SQL_WHERE := V_SQL_WHERE || ' emp_id='||EMPID; END IF; IF(EMPNAME IS NOT NULL) THEN IF (V_SQL_WHERE is not null) THEN V_SQL_W...
You can create one from scratch, including if's and elses, or you can use a package called plsql-utils, the SQL\_BUILDER\_PKG. It does the whole work for you. Have a look on **SQL utilities** <http://code.google.com/p/plsql-utils/> Eg: ``` declare l_my_query sql_builder_pkg.t_query; l_sql varchar2(32000); begin...
preparing sql dynamically in oracle stored procedure
[ "", "sql", "plsql", "" ]
I have table with departments. I need to count how many people are within which dept. This is easily done by ``` SELECT DEPT, COUNT(*) as 'Total' FROM SR GROUP BY DEPT; ``` Now I need to also do cumulative count as below: ![enter image description here](https://i.stack.imgur.com/e82Kq.png) I have fou...
Here's a way to do it with a CTE instead of a cursor: ``` WITH Base AS ( SELECT ROW_NUMBER() OVER (ORDER BY [Count] DESC) RowNum, [Dept], [Count] FROM SR ) SELECT SR.Dept, SR.Count, SUM(SR2.[Count]) Total FROM Base SR INNER JOIN Base SR2 ON SR2.RowNum <= SR.RowNum GROUP BY SR.Dept, SR.Count ORDER B...
I think you can use some temporary / variable table for this, and use solution from [here](https://stackoverflow.com/questions/860966/calculate-a-running-total-in-sqlserver/13744550#13744550): ``` declare @Temp table (rn int identity(1, 1) primary key, dept varchar(128), Total int) insert into @Temp (dept, Total) sel...
SQL Cumulative Count
[ "", "sql", "sql-server", "sql-server-2008", "running-count", "" ]
we are implementing a search application we have implemented a exact word search by the following sql query ``` SELECT * FROM jreviews_content WHERE jr_produits REGEXP '[[:<:]]ryan[[:>:]]' ``` which works well now we have another requirement in some of our field ie in jr\_title field if the user fill one missing let...
This will allow one alphanumerich character before the search string, and one after: ``` SELECT * FROM jreviews_content WHERE jr_produits REGEXP '[[:<:]][[:alnum:]]{0,1}ryan[[:alnum:]]{0,1}[[:>:]]' ``` if you want to allow one alphanumeric character before the search string OR one after, you could use this instead: ...
Look for "Levenshtein distance" An implementation is here <http://www.artfulsoftware.com/infotree/queries.php#552> or as a compiled function <http://samjlevy.com/2011/03/mysql-levenshtein-and-damerau-levenshtein-udfs/>
One Letter mistake allowed in exact word search
[ "", "mysql", "sql", "" ]
Hi guys is something like that possible in SQL. ``` declare a as varchar(20) set a = 'ID = 34 and ID = 22' select * from something where ID = 1 and a ```
You can use the command `exec` for that - concatenating strings to one and then running an SQL query of that string. So in your case it would be: ``` declare @a varchar(20) set @a = 'ID = 34 and ID = 22' exec ('select * from something where ID = 1 and ' + @a) ``` Just be careful of SQL injections.
Yes, you can use use `EXEC` ``` declare @a as varchar(20) set @a = 'ID = 34 and ID = 22' EXEC ('select * from something where ID = 1 and ' + @a) ``` Warning: this type of concatenating SQL queries is a security risk because of [SQL injection](http://en.wikipedia.org/wiki/SQL_injection).
(MS)SQL execute query with additional varchar/text in where condition
[ "", "sql", "sql-server", "select", "" ]
It's maybe a noob question but I found some T-SQL query example to verify database size with `SELECT` and `WHERE` clause [here](http://technet.microsoft.com/en-us/library/ms176061.aspx) Here is the code: ``` SELECT name, size, size*1.0/128 AS [Size in MBs] FROM sys.master_files WHERE name = N'mytest'; ``` My questi...
It's declaring the string as nvarchar data type (Unicode), rather than varchar (8-bit encoding, including ASCII). FYI, this is a duplicate of the question: [What is the meaning of the prefix N in T-SQL statements?](https://stackoverflow.com/questions/10025032/what-is-the-meaning-of-the-prefix-n-in-t-sql-statements)
From the [docs](http://databases.aspfaq.com/general/why-do-some-sql-strings-have-an-n-prefix.html):- > You may have seen Transact-SQL code that passes strings around using > an N prefix. **This denotes that the subsequent string is in Unicode > (the N actually stands for National language character set).** Which > mea...
SQL Server T-SQL N prefix on string literal
[ "", "sql", "sql-server", "t-sql", "" ]